<template>
	<view class="mainBox">
		<uni-nav-bar background-color="#157A2C" color="#fff" fixed="true" statusBar="true" left-icon="back"
			:title="this.form.id?'修改采购需求':'新建采购需求'" @clickLeft="back">
		</uni-nav-bar>
		<u-subsection :list="list" :current="current" @change="sectionChange"></u-subsection>
		<u-cell-group v-show='current==0'>
			<u-cell :title="'需求类型'" arrow-direction="down">
				<view slot="title" style="display: flex; align-items: center;">
					<text class="required-mark">*</text>
					需求类型
				</view>
				<uni-data-picker v-model="form.sourceType" slot="value" placeholder="请选择"
					:localdata="requirementSourceType" @change="sourceCodeOnchange">
				</uni-data-picker>
			</u-cell>
			<u-cell :title="'需求单名称'" arrow-direction="down">
				<view slot="title" style="display: flex; align-items: center;">
					<text class="required-mark">*</text>
					需求单名称
				</view>
				<u--input slot="value" placeholder="请输入" border="surround" v-model="form.requirementName"></u--input>
			</u-cell>
			<u-cell :title="'需求部门'" arrow-direction="down">
				<view slot="title" style="display: flex; align-items: center;">
					<text class="required-mark">*</text>
					需求部门
				</view>
				<!-- <u--input slot="value" placeholder="请输入" border="surround" v-model="form.requireDeptId"></u--input> -->
				<u--input slot="value" @click.native="classification" style="flex:1" border="surround"
					placeholder="请选择需求部门" v-model="form.requireDeptName">
				</u--input>
			</u-cell>
			<u-cell :title="'需求人'" arrow-direction="down">
				<view slot="title" style="display: flex; align-items: center;">
					<text class="required-mark">*</text>
					需求人
				</view>
				<!-- <u--input slot="value" placeholder="请输入" border="requireUserId" v-model="form.name"></u--input> -->
				<u--input slot="value" style="flex:1" border="surround" v-model="form.requireUserName"
						placeholder="请选择需求人" @click.native="openSelector">
				</u--input>
			</u-cell>
			<u-cell title="销售合同" arrow-direction="down">
				<u--input slot="value" placeholder="请选择" border="surround" v-model="form.saleContractNo"
					@click.native="selectContractShow"></u--input>
			</u-cell>
			<u-cell title="销售订单" arrow-direction="down">
				<!-- <u--input slot="value" placeholder="请输入" border="requireUserId" v-model="form.name"></u--input> -->
				<u--input slot="value" style="flex:1" border="surround" v-model="form.saleOrderNo"
						placeholder="请选择销售订单" @click.native="slectOrderShow">
				</u--input>
			</u-cell>
			<u-cell title="是否接受拆单" arrow-direction="down">
				<uni-data-picker v-model="form.acceptUnpack" slot="value" placeholder="请选择"
					:localdata="acceptUnpackList" @change="sourceCodeOnchange">
				</uni-data-picker>
				<!-- <u--input slot="value" :disabled="true" placeholder="请输入" border="surround"
					v-model="form.responsibleName"></u--input> -->
				<!-- <u-radio-group
					v-model="form.acceptUnpack"
					placement="column"
					@change="groupChange"
				>
					<u-radio
						:customStyle="{marginBottom: '8px'}"
						v-for="(item, index) in radiolist1"
						:key="index"
						:label="item.name"
						:name="item.name"
						@change="radioChange"
					>
					</u-radio>
				</u-radio-group> -->
			</u-cell>
			<u-cell title="'用途" arrow-direction="down">
				<view slot="title" style="display: flex; align-items: center;">
					<text class="required-mark">*</text>
					用途
				</view>
				<!-- <uni-data-picker v-model="form.useTo" slot="value" placeholder="请选择"
					:localdata="business_opport_code" @change="sourceCodeOnchange">
				</uni-data-picker> -->
				<u--textarea slot="value" placeholder="请输入" border="surround" v-model="form.useTo"></u--textarea>
			</u-cell>
			<u-cell title="附件" arrow-direction="down">
				<view slot="value" style="display: flex;align-items: center;width: 100%;">
					<fileMain v-model="form.fileId"></fileMain>
				</view>
			</u-cell>
			<u-cell title="备注" arrow-direction="down">
				<u--textarea slot="value" placeholder="请输入" border="surround" v-model="form.remark"></u--textarea>
			</u-cell>
		</u-cell-group>


		<view class="footerButton">
			<u-button type="default" text="返回" @click="back"></u-button>
			<u-button type="primary" @click="save" text="保存"></u-button>
		</view>
		<produceList ref="produceListRef" v-show="current==1"  :isTemporary="true"></produceList>
		 <ba-tree-picker ref="treePicker" key="verify" :multiple="false" @select-change="confirm" title="选择部门"
			:selectedData="selectedData" :localdata="classificationList" valueKey="id" textKey="name"
			childrenKey="children" />
		<search-select ref="selector" v-model="form.requireUserId" :data-list="executorList" title="选择需求人" @change="onClose">
		</search-select>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import { getByCode } from '@/api/pda/common.js'
	import { contactDetail } from '@/api/saleManage/contact/index.js'
	import searchSelect from '@/pages/salesServiceManagement/accessory/components/searchSelect.vue';
	import produceList from '../components/produceList.vue'
	import fileMain from "@/pages/doc/index.vue"
	import { requirementSourceType } from '@/enum/dict'
	import { listOrganizations } from '@/api/salesServiceManagement/workOrder/index.js';
	import { toTreeData } from '@/utils/utils.js';
	import { getUserPage } from '@/api/common.js';
	import { getTableList, getSaleOrderDetail } from '@/api/saleManage/saleorder/index'
	import {
		getDetail,
		addPurchaseNeedManage,
		UpdateInformation
	} from '@/api/purchasingManage/purchaseNeedManage.js'
	export default {
		components: {
			produceList,
			fileMain,
			searchSelect
		},
		data() {
			return {
				list: ['基本信息', '需求清单'],
				acceptUnpackList: [{text: '接受', value: 1}, { text: '不接受', value: 0}],
				current: 0,
				show: false,
				requirementSourceType,
				classificationList: [],
				isUpdate: false,
				form: {
					id: '',
					receiveDate: null,
					remark: null,
					requireDeptId: '',
					requireDeptName: '',
					requireUserId: '',
					requireUserName: '',
					sourceCode: '',
					sourceId: '',
					sourceType: '',
					requirementName: '',
					saleContractName: '',
					saleContractNo: '',
					saleContractId: '',
					saleOrderId: '',
					saleOrderNo: '',
					files: [],
					acceptUnpack: 1,
					fileId: [] //附件集合
				},
				business_opport_code: [],
				linkList: [],
				selectedData: [], // 使用部门绑定值
				executorList: []
			}
		},

		created() {

			this.getByCode()
			//选择合同回调
			uni.$off('setContractList')
			uni.$on('setContractList', async (data) => {
				if (data && data.length > 0) {
					this.form = Object.assign({}, this.form, {
						saleContractId: data[0].id,
						saleContractName: data[0].contractName,
						saleContractNo: data[0].contractNo,
					});
					this.getSaleOrderList(data[0].id);
				}

			})

			uni.$off('setSaleOrder')
			uni.$on('setSaleOrder', async (data) => {
				if(data && data.length > 0) {
					this.form = Object.assign({}, this.form, {
						saleContractId: '',
						saleContractName: '',
						saleContractNo: '',
						saleOrderId: data[0].id,
						saleOrderNo: data[0].orderNo
					});
					this.getSaleOrderDetail(this.form.saleOrderId)
				}
			})

			// uni.$off('setSelectList')
			// uni.$on('setSelectList', async (data) => {
			// 	if (data && data.length > 0) {
			// 		const {
			// 			linkList
			// 		} = await contactDetail(data[0].id)
			// 		this.linkList = linkList
			// 		this.$set(this.form, 'contactId', data[0].id);
			// 		this.$set(this.form, 'contactName', data[0].name);
			// 	}

			// })
		},
		onLoad(data) {
			this.getTreeList()
			if (data && data.id) {
				this.isUpdate = true
				getDetail(data.id).then(async res => {
					this.form = res
					this.form.fileId = JSON.parse(res.fileId)
					if(this.form.requireDeptId) {
						this.getUserList(this.form.requireDeptId);
					}
					// setTimeout(() => {
						// this.current = 0
						this.$nextTick(() => {
							// this.$refs.infoRef.init(res)
							const tempData = res.detailList.map(item => {
								return {
									...item,
									packageDispositionList: item.packageDispositionList.map(i => {
										return {
											...i,
											text: i.conversionUnit,
											value: i.id
										}
									})
								}
							})
							this.$refs.produceListRef.init(tempData)
							// if (data.current) {
							// 	this.current = +data.current
							// }
						})
					// }, 300)
				})
			} else {
				const userInfo = uni.getStorageSync('userInfo')
				this.$set(this.form, 'requireUserId', userInfo.userId);
				this.$set(this.form, 'requirementName', userInfo.name);
			}

		},
		onUnload() {
			// uni.$off('setSelectList')
			uni.$off('setContractList')
			uni.$off('setSaleOrder')
			// uni.$off('updatelinkList')
		},
		methods: {
			async getSaleOrderList(contractId) {
				let res = await getTableList({
				pageNum: 1,
				size: 10,
				contractId
				});
				this.form.saleOrderId = res.list[0]?.id;
				this.form.saleOrderNo = res.list[0]?.orderNo;
				this.getSaleOrderDetail(this.form.saleOrderId);
			},
			async getSaleOrderDetail(id) {
				const data = await getSaleOrderDetail(id);
				data.productList.forEach((item) => {
				item.expectReceiveDate = item.produceDeliveryDeadline;
				item.arrivalWay = 1;
				});

				this.$nextTick(() => {
				this.$refs.produceListRef.init(data.productList);
				});
			},
			async getTreeList() {
				const data = await listOrganizations({});
				let treeList = toTreeData({
					data: data || [],
					idField: 'id',
					parentIdField: 'parentId'
				});
				this.classificationList = treeList;
			},
			// 打开部门弹窗
			classification() {
				this.$refs.treePicker._show();
			},
			// 使用部门选择
			confirm(id, name) {
				this.form.requireDeptName = name;
				this.form.requireDeptId = id[0];
				this.form.requireUserId = '';
				this.form.requireUserName = '';
				this.executorList = [];
				this.getUserList(id[0]);
				this.$refs.selector.clearSearchText();
			},
			// 打开使用人弹窗
			openSelector() {
				this.$refs.selector.open();
			},
			// 获取使用人数据
			async getUserList(id) {
				let params = {
					pageNum: 1,
					size: -1,
					groupId: id
				}
				try {
					const res = await getUserPage(params);
					let list = res.list && res.list.map((el) => {
						return {
							text: el.name,
							value: el.id
						}
					})
					this.executorList = list;
				} catch (error) {
					this.executorList = [];
				}
			},
			// 使用人选择
			onClose(item) {
				this.form.requireUserName = item.text;
			},
			//选择合同
			selectContractShow() {
				uni.navigateTo({
					url: '/pages/saleManage/components/selectContract?isAll=' + 2
				})
			},
			slectOrderShow() {
				uni.navigateTo({
					url: '/pages/purchasingManage/components/selectSaleOrder?isAll=' + 2
				})
			},
			getByCode() {
				const codeS = ['business_opport_code']
				codeS.forEach(async (code) => {
					const codeValue = await getByCode(code);
					this[code] = codeValue.map(item => {
						const key = Object.keys(item)[0]
						return {
							value: key,
							text: item[key]
						}
					})
				})

			},
			sourceCodeOnchange(e) {
				const value = e.detail.value
				this.form.sourceCode = value.map(item => item.value).toString()
				this.form.sourceName = value.map(item => item.text).toString()
			},

			radioChange(e) {
				this.form.pricingWay = e.detail.value
				this.$nextTick(() => {
					this.$refs.produceListRef.getTotalPrice()
				})


			},
			sectionChange(index) {
				this.current = index;
			},

			async save() {
				try {
					if (!this.form.sourceType) {
						this.$refs.uToast.show({
							type: "error",
							message: "请选择需求类型",
						})
						return
					}
					if (!this.form.requirementName) {
						this.$refs.uToast.show({
							type: "error",
							message: "请输入需求名称",
						})
						return
					}
					if (!this.form.requireDeptName) {
						this.$refs.uToast.show({
							type: "error",
							message: "请选择需求部门",
						})
						return
					}

					if (!this.form.requireUserName) {
						this.$refs.uToast.show({
							type: "error",
							message: "请选择需求人",
						})
						return
					}

					const detailList = this.$refs.produceListRef.getValue();

					if (detailList.length == 0) {
						this.$refs.uToast.show({
							type: "error",
							message: "产品清单不能为空",
						})
						return;
					}

					let isArrivalBatch = false;
					detailList.forEach((v) => {
						if (v.arrivalWay == 2 && (!v.arrivalBatch || v.arrivalBatch.length == 0) ) {
							isArrivalBatch = true;
						}
					});
					if (isArrivalBatch) {
						uni.showToast({title: '请设置分批时间'});
						return;
					}

					uni.showLoading({
						title: '加载中'
					})

					const data = {
						...this.form,
						detailList: detailList
					};

					console.log('data~~~', data)

					const requestApi = this.isUpdate ? UpdateInformation : addPurchaseNeedManage

					requestApi(data)
						.then((res) => {
							uni.hideLoading()
							this.back()
						})
						.catch((e) => {
							uni.hideLoading()
						});
				} catch (error) {
					uni.hideLoading()
					console.log(error, 'error')
				}
			},

		}
	}
</script>

<style lang="scss" scoped>
	.required-mark {
		color: #FF3333;
		margin-right: 4rpx;
	}
	
	/deep/.u-cell__body__content {
		flex: none;
		margin-right: 16rpx;
	}

	.mainBox {
		padding-bottom: 84rpx;
	}

	.footerButton {
		width: 100%;
		height: 84rpx;
		display: flex;
		position: fixed;
		bottom: 0;
		z-index: 10;
		background-color: #fff;

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

		>view {
			flex: 1;

		}
	}

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

	/deep/.u-subsection__item__text {
		font-size: 28rpx !important;
	}
	/deep/.uni-input-placeholder {
		font-size: 28rpx !important;
	}
	/deep/.selected-item {
		font-size: 28rpx !important;
	}
	/deep/.uni-input-input {
		font-size: 28rpx !important;
	}

	
</style>