<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>
				<!-- <u--input slot="value" placeholder="请选择" border="surround" v-model="form.sourceType"
					@click.native="selectContactShow"></u--input> -->
				<!-- <u-picker :show="show" :columns="requirementSourceType" keyName="label"></u-picker> -->
				<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.requireDeptId">
				</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.requireUserId"
						placeholder="请选择需求人" @click.native="openSelector">
				</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.requireUserId"
						placeholder="请选择需求人" @click.native="openSelector">
				</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.requireUserId"
						placeholder="请选择需求人" @click.native="openSelector">
				</u--input>
			</u-cell>
			<u-cell title="是否接受拆单" arrow-direction="down">
				<uni-data-picker v-model="form.acceptUnpack" slot="value" placeholder="请选择"
					:localdata="[{text: '接受', value: '1'}, { text: '不接受', value: '0'}]" @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>
		<!-- <businessList ref="businessListRef" v-show="current==2"></businessList> -->
		<!-- <personnelList ref="personnelListRef" :linkList="linkList" v-show="current==3"></personnelList> -->
		 <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>
	// file:///D:/中赢/aiot-app/pages/warehouse/enterHouse/selectEnterType.vue

	import {
		getByCode
	} from '@/api/pda/common.js'
	import {
		contactDetail,
	} from '@/api/saleManage/contact/index.js'
	import {
		businessopportunitySave,
		getDetail
	} from '@/api/saleManage/businessOpportunity/index.js'
	import searchSelect from '@/pages/salesServiceManagement/accessory/components/searchSelect.vue';
	import produceList from '../components/produceList.vue'
	// import businessList from './components/businessList.vue'
	// import personnelList from './components/personnelList.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';
	export default {
		components: {
			produceList,
			// businessList,
			// personnelList,
			fileMain,
			searchSelect
		},
		data() {
			return {
				list: ['基本信息', '需求清单'],
				current: 0,
				show: false,
				requirementSourceType,
				classificationList: [],
				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()

		},
		onLoad(data) {
			this.getTreeList()
			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);
				}

			})
			if (data && data.id) {
				getDetail(data.id).then(async res => {
					this.form = res
					const {
						linkList
					} = await contactDetail(res.contactId)
					this.linkList = linkList
					this.$nextTick(() => {

						this.$refs.produceListRef.init(res.productList)
						this.$refs.businessListRef.init(res.competAnalysisList)
						this.$refs.personnelListRef.init(res.partyList)
					})

				})
			} else {
				const userInfo = uni.getStorageSync('userInfo')
				this.$set(this.form, 'responsibleId', userInfo.userId);
				this.$set(this.form, 'responsibleName', userInfo.name);
			}

		},
		onUnload() {
			uni.$off('setSelectList')
			// uni.$off('updatelinkList')
		},
		methods: {
			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.useDeptName = name;
				this.form.useDeptId = id[0];
				this.form.userId = '';
				this.form.userName = '';
				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.userName = item.text;
			},
			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]
						}
					})
				})

			},
			selectContactShow() {
				uni.navigateTo({
					url: '/pages/saleManage/components/selectContact?isAll=' + 2
				})
			},
			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.contactName) {
						this.$refs.uToast.show({
							type: "error",
							message: "请选择客户",
						})
						return
					}
					if (!this.form.name) {
						this.$refs.uToast.show({
							type: "error",
							message: "请输入商机名称",
						})
						return
					}
					if (!this.form.sourceCode) {
						this.$refs.uToast.show({
							type: "error",
							message: "请选择商机来源",
						})
						return
					}

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

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

					const data = {
						opportunity: this.form,
						competAnalysisList: this.$refs.businessListRef.getValue(),
						partyList: this.$refs.personnelListRef.getValue(),
						productList: this.$refs.produceListRef.getValue()
					};

					businessopportunitySave(data)
						.then((id) => {
							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>