<template>
	<view class="">
		<uni-nav-bar background-color="#157A2C" color="#fff" fixed="true" statusBar="true" left-icon="back"
			:title="title" @clickLeft="back">
		</uni-nav-bar>
		<view class="scrollable-tabs" ref="tabsContainer">
			<u-subsection :list="tabs" :current="currentIndex" @change="(e)=>sectionChange(e)"></u-subsection>
		</view>
		<accessoryList title="配件回收清单" ref="accessoryRef" :itemList="accessList" v-show="currentValue == 2" />
		<!-- 需求信息 -->
		<DemandInfo :demandForm="demandForm" v-show="currentValue == 3" :itemList="productDetail" />
		<!-- 计划信息 -->
		<PlanInfo :planForm="planForm" v-show="currentValue == 4" />
		<!-- 售后对象 -->
		<AfterSales ref="salesRef" v-show="currentValue == 5" :itemList="productDetail" :type="type"
			:isReport="isReport" />
		<!-- 联系人列表 -->
		<ContactList ref="contactRef" :type="type" v-show="currentValue == 6" :itemList="contactInfoVOS"
			:isReport="isReport" />
		<!-- 方案列表 -->
		<SchemeList ref="schemeRef" v-show="currentValue == 7" :type='type' :itemList="costListVOS" />
		<!-- 报工信息 -->
		<ReportInfo ref="reportInfoRef" :form="reportForm" v-show="currentValue == 1" />
		<view :class=" type == 'report' ? 'footerButton footer_button':'footerButton'" v-if="isDisable">
			<u-button type="default" text="返回" @click="back"></u-button>
			<u-button type="primary" text="报工" v-if="type == 'report'" @click="save('report')"></u-button>
			<u-button type="primary" @click="save" text="保存"></u-button>
		</view>
		<!-- 	<ba-tree-picker ref="treePicker" :multiple="false" @select-change="confirm" title="选择部门" :localdata="listData"
			valueKey="id" textKey="name" childrenKey="children" /> -->
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		getSalesWorkOrderById,
		updateScheme,
		reportWorkingSalesWorkOrder
	} from '@/api/salesServiceManagement/workOrder/index.js';
	import {
		contactDetail
	} from '@/api/saleManage/contact/index.js';
	import accessoryList from './accessoryList.vue';
	import ReportInfo from './reportInfo.vue';
	import AfterSales from '@/pages/salesServiceManagement/demandList/components/AfterSales.vue';
	import ContactList from '@/pages/salesServiceManagement/demandList/components/contactList.vue';
	import PlanInfo from './planInfo.vue';
	import DemandInfo from './demandInfo.vue';
	import SchemeList from './schemeList.vue';
	import {
		getByCode
	} from '@/api/pda/common.js';
	import {
		listOrganizations,
		getUserPage
	} from '@/api/myTicket/index.js';
	let resData = {};
	let contractInfo = {};
	export default {
		components: {
			SchemeList,
			PlanInfo,
			DemandInfo,
			AfterSales,
			ContactList,
			ReportInfo,
			accessoryList
		},
		computed: {
			isDisable() {
				let flag = this.type != 'view';
				return flag;
			},
			isReport() {
				let flag = this.type != 'view' ? true : false;
				return flag;
			},
			currentIndex() {
				return this.tabs.findIndex(item => item.id == this.currentValue);
			}
		},
		data() {
			return {
				title: '修改工单',
				type: 'edit',
				Usertype: '',
				tabs: [{
						name: '售后对象',
						id: 5
					}, {
						name: '联系人',
						id: 6
					},
					{
						name: '方案',
						id: 7
					}, {
						name: '需求信息',
						id: 3
					}, {
						name: '计划信息',
						id: 4
					},
				],
				listData: [], // 部门数据
				userList: [], // 执行人列表
				demandForm: {}, // 需求基本信息
				planForm: {}, // 计划基本信息
				productDetail: [], // 售后对象
				contactInfoVOS: [], // 联系人
				costListVOS: [], // 方案
				currentValue: 5,
				accessList: [], // 配件回收
				reportForm: {
					acceptTime: '',
					finishTime: '',
					inFactDuration: ''
				}
			}
		},
		onLoad(params) {
			this.type = params.type;
			this.title = params.type == 'view' ? '工单详情' : params.type == 'edit' ? '修改工单' : '报工';
			if (params.type == 'report') {
				this.tabs.unshift({
					name: '报工信息',
					id: 1
				}, {
					name: '配件回收',
					id: 2
				});
				this.currentValue = 1;
			}
			this.getDetails(params.id);
		},
		onUnload() {},
		created() {},
		methods: {
			async getDetails(id) {
				// await this.getByData();
				// this.getDept();
				const res = await getSalesWorkOrderById(id);
				console.log(res, 'res ----')
				this.reportForm = {
					acceptTime: res.acceptTime,
					finishTime: res.finishTime,
					inFactDuration: res.inFactDuration
				}
				this.accessList = res.accessoryApply?.detailList || []
				this.contactData(res.afterSalesDemandVO.contactId, 'init');
				resData = res;
				this.costListVOS = res.costListVOS;
				this.demandData(res.afterSalesDemandVO);
				this.planData(res.afterSalesPlanVO);
			},
			// 工单绑定的客户数据
			async contactData(id) {
				let {
					base
				} = await contactDetail(id);
				base.contactName = base.name;
				contractInfo = base;
			},
			// 需求数据
			async demandData(data) {
				this.contactInfoVOS = data.contactInfoVOS || [];
				this.productDetail = data.productDetail || [];
				let fault_level = await this.getByData('fault_level', data.faultLevel);
				this.demandForm = {
					code: data.code,
					name: data.name,
					contactName: data.contactName,
					orderCode: data.orderCode,
					contactAddress: data.contactAddress,
					expectedTime: data.expectedTime,
					createUserName: data.createUserName,
					fault_level,
				}
			},
			// 计划信息
			async planData(data) {
				let isSyncBill = data.isSyncBill == '0' ? '否' : data.isSyncBill == '1' ? '是' : ''
				let urgent = await this.getByData('urgent_type', data.urgent);
				this.planForm = {
					code: data.code,
					name: data.name,
					isSyncBill,
					executeGroupName: data.executeGroupName,
					executeUserName: data.executeUserName,
					remark: data.remark,
					duration: data.duration,
					durationUnit: data.durationUnit,
					urgent,
				}
			},
			async getByData(code, value) {
				const codeValue = await getByCode(code);
				let label = '';
				codeValue.forEach((el) => {
					if (el[value]) {
						label = el[value];
						return;
					}
				})
				return label || ''
			},
			getDept() {
				listOrganizations(1).then(data => {
					this.listData = data;
				})
			},
			clistData(arrList) {
				let list = JSON.parse(JSON.stringify(arrList));
				let arr = [];
				if (list.length == 0) return list;
				list.map((item) => {
					this.addData(item, arr);
				});
				return arr;
			},
			addData(item, arr) {
				let totalCount = item.totalCount ? item.totalCount - 0 : '';
				if (!totalCount || totalCount == 1) {
					arr.push(item);
					return;
				}
				for (let i = 0; i < totalCount; i++) {
					item.totalPrice = item.singlePrice || 0;
					item.totalCount = 1;
					arr.push(item);
				}
			},
			process(type) {
				let productDetail = this.$refs.salesRef.getTabData();
				// 点击报工 逻辑
				if (type == 'report') {
					let flag = true;
					productDetail[0].faultDetails.forEach((el) => {
						if (!el.faultReason || !el.maintenanceProcess) {
							this.$refs.uToast.show({
								type: "warning",
								message: "故障原因跟维修过程不能为空",
							})
							this.currentValue = 5;
							flag = false;
							return;
						}
					})
					if (!flag) {
						return flag;
					}
				}
				let contactInfoVOS = this.$refs.contactRef.getTabData();
				let costListVOS = this.$refs.schemeRef.getTabData();
				let obj = resData.afterSalesDemandVO;
				let data = {
					attachments: resData.attachments,
					costListVOS: costListVOS,
					faultPhenomenon: resData.inFactDuration,
					faultReason: resData.faultReason,
					id: resData.id,
					inFactDuration: resData.inFactDuration,
					maintenanceProcess: resData.maintenanceProcess,
					salesDemandUpdatePO: {
						orderCode: obj.orderCode,
						orderId: obj.orderId,
						name: obj.name,
						faultLevel: obj.faultLevel ? String(obj.faultLevel) : '',
						code: obj.code,
						expectedTime: obj.expectedTime || '',
						contactAddress: obj.contactAddress || '',
						id: obj.id,
					}
				}
				productDetail.map((el) => {
					delete el.produceTime;
				})
				data.salesDemandUpdatePO.productDetail = productDetail;
				data.salesDemandUpdatePO.contractInfo = contractInfo;
				data.salesDemandUpdatePO.contactInfoVOS = contactInfoVOS;
				// 处理报工信息的数据
				if (this.type == 'report') {
					let reportForm = this.$refs.reportInfoRef.getReportForm();
					if (!reportForm.acceptTime || !reportForm.finishTime) {
						this.currentValue = 1;
						this.$refs.uToast.show({
							type: "warning",
							message: "请选择开始时间跟结束时间",
						})
						return false;
					}
					data = {
						...data,
						...reportForm
					}
				}

				// 报工进来 保存或者报工 数据
				if (this.type == 'report' && productDetail[0].faultDetails.length > 0) {
					let list = this.$refs.accessoryRef.getTabData() || [];
					if (list.length > 0) {
						let detailList = this.clistData(list);
						// 指定绑定第一条设备信息
						let item = data.salesDemandUpdatePO.productDetail[0];
						let accessoryApply = {
							demandDetailId: item.id,
							categoryCode: item.categoryCode,
							categoryName: item.categoryName,
							contactName: data.salesDemandUpdatePO.contractInfo.name,
							contactCode: data.salesDemandUpdatePO.contractInfo.code,
							detailList
						};
						data.accessoryApply = accessoryApply;
					}
				}
				return data;
			},
			save(type) {
				// 获取 报工信息以外的数据
				let data = this.process(type);
				if (!data) {
					return
				}
				console.log(data, 'data')
				uni.showLoading({
					title: '加载中'
				});
				let api = type != 'report' ? updateScheme : reportWorkingSalesWorkOrder;
				api(data).then(res => {
					this.$refs.uToast.show({
						type: "success",
						message: "操作成功",
					})
					uni.hideLoading();
					this.back();
				}).catch(e => {
					uni.hideLoading();
				})
			},
			//返回添加页
			backAdd() {
				this.back();
				// uni.navigateBack();
			},
			// confirm(data, name) {
			// 	this.form.executeGroupName = name
			// 	this.form.executeGroupId = data[0]
			// 	this.form.executeUserName = ''
			// 	this.form.executeUserId = ''
			// 	this.getUser(data[0])
			// },
			// getUser(deptCode) {
			// 	getUserPage({
			// 		pageNum: 1,
			// 		size: -1,
			// 		groupId: deptCode
			// 	}).then(data => {
			// 		this.userList = data.list.map(item => {
			// 			item.text = item.name
			// 			item.value = item.id
			// 			return item
			// 		})
			// 	})
			// },
			sectionChange(index) {
				this.currentValue = this.tabs[index].id;
			},
		}
	}
</script>

<style lang="scss" scoped>
	/deep/.u-subsection__item__text {
		font-size: 28rpx !important;
	}

	/deep/.u-cell__body__content {
		flex: none;
		margin-right: 16rpx;
	}

	/deep/ .time_select .uni-data-tree-input {
		width: 200rpx;
	}

	/deep/ .executor_user {
		background: #fff;
	}

	.footerButton {
		width: 100%;
		height: 84rpx;
		display: flex;
		position: fixed;
		bottom: 0;
		z-index: 10;
		justify-content: space-between;

		/deep/.u-button {
			height: 100%;
			width: 50%;
		}

		>view {
			flex: 1;

		}
	}

	.footer_button {
		/deep/.u-button {
			height: 100%;
			width: 30%;
		}
	}

	.scrollable-tabs {
		white-space: nowrap;
		/* 防止选项卡换行 */
		overflow-x: auto;
		/* 启用横向滚动 */
		-webkit-overflow-scrolling: touch;
		/* 优化iOS滚动体验 */

		/deep/ .u-subsection {
			overflow-x: auto;
		}

		/deep/ .u-subsection__item__text {
			width: 144rpx;
			text-align: center;
			display: inline-block;
		}
	}
</style>