<template>
	<view class="mainBox">
		<uni-nav-bar background-color="#157A2C" color="#fff" fixed="true" statusBar="true" left-icon="back"
			:title="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">
				<u--input slot="value" placeholder="请选择" border="surround" v-model="form.projectName"
					@click.native="selectProjectShow"></u--input>
			</u-cell>
			<u-cell title="选择合同" arrow-direction="down">
				<u--input slot="value" placeholder="请选择" border="surround" v-model="form.contractName"
					@click.native="selectContractShow"></u--input>
			</u-cell>
			<u-cell arrow-direction="down">
				<view slot="title">
					<text class="required-mark">*</text>
					<text>销售类型</text>
				</view>
				<uni-data-picker v-model="form.saleType" slot="value" placeholder="请选择" :localdata="order_type">
				</uni-data-picker>
			</u-cell>
			<u-cell title="销售部门" arrow-direction="down">
				<u--input slot="value" placeholder="请选择" border="surround" v-model="form.salesDeptName"
					@click.native="salesDeptShow"></u--input>
			</u-cell>
			<u-cell title="合同编号" arrow-direction="down">
				<u--input slot="value" :disabled="true" placeholder="请输入" border="surround"
					v-model="form.contractNumber"></u--input>
			</u-cell>

			<u-cell arrow-direction="down">
				<view slot="title">
					<text class="required-mark">*</text>
					<text>结算方式</text>
				</view>
				<uni-data-picker v-model="form.settlementMode" slot="value" placeholder="请选择" :localdata="settlement_mode" @change="settlementModeChange">
				</uni-data-picker>
			</u-cell>
			<u-cell title="订单类型" arrow-direction="down">

				<radio-group v-model="form.needProduce" slot="value">
					<radio value="1" :checked="form.needProduce==1" @click="form.needProduce=1">生产性订单</radio>
					<radio value="0" :checked="form.needProduce==0" @click="form.needProduce=0">库存式订单</radio>
					<radio value="2" :checked="form.needProduce==2" @click="form.needProduce=2">无客户生产性订单</radio>

				</radio-group>
			</u-cell>
			<u-cell title="计价方式" arrow-direction="down">

				<radio-group @change="radioChange" v-model="form.pricingWay" slot="value">
					<radio :disabled="!!form.contractId" value="1" :checked="form.pricingWay==1">按数量计价</radio>
					<radio :disabled="!!form.contractId" value="2" :checked="form.pricingWay==2">按重量计价</radio>

				</radio-group>
			</u-cell>
			<u-cell title="自动生成采购计划" arrow-direction="down">
				<radio-group v-model="form.generatePurchase" slot="value">
					<radio value="1" :checked="form.generatePurchase==1" @click="form.generatePurchase=1">是</radio>
					<radio value="0" :checked="form.generatePurchase==0" @click="form.generatePurchase=0">否</radio>
				</radio-group>
			</u-cell>
			<u-cell title="自动生成生产计划" arrow-direction="down">
				<radio-group v-model="form.generateProduce" slot="value">
					<radio value="1" :checked="form.generateProduce==1" @click="form.generateProduce=1">是</radio>
					<radio value="0" :checked="form.generateProduce==0" @click="form.generateProduce=0">否</radio>
				</radio-group>
			</u-cell>
			<u-cell title="自动生成项目立项" arrow-direction="down">
				<radio-group v-model="form.generateProject" slot="value">
					<radio value="1" :checked="form.generateProject==1" @click="form.generateProject=1">是</radio>
					<radio value="0" :checked="form.generateProject==0" @click="form.generateProject=0">否</radio>
				</radio-group>
			</u-cell>

			<u-cell title="收货地址" arrow-direction="down">
				<u--textarea border="surround" v-model="form.receiveAddress" placeholder="请输入内容"
					slot="value"></u--textarea>
			</u-cell>
			<u-cell title="备注" arrow-direction="down">
				<u--textarea border="surround" v-model="form.remark" placeholder="请输入内容" slot="value"></u--textarea>
			</u-cell>
		</u-cell-group>

		<u-cell-group v-show='current==1&&form.needProduce!=2'>

			<u-cell arrow-direction="down">
				<view slot="title">
					<text class="required-mark">*</text>
					<text>客户名称</text>
				</view>

				<u--input slot="value" placeholder="请选择" border="surround" v-model="form.partaName" @click.native="selectContactShow"></u--input>

			</u-cell>
			<u-cell title="客户统一社会信用代码" arrow-direction="down">
				<u--input slot="value" placeholder="请输入" border="surround"
					v-model="form.partaUnifiedSocialCreditCode"></u--input>
			</u-cell>
			<u-cell arrow-direction="down">
				<view slot="title">
					<text class="required-mark">*</text>
					<text>客户联系人</text>
				</view>
				<uni-data-picker slot="value" v-model="form.partaLinkId" placeholder="请选择" :localdata="linkList" :map="{text:'linkName',value:'id'}" @change="linkChange">
				</uni-data-picker>
			</u-cell>
			<u-cell arrow-direction="down">
				<view slot="title">
					<text class="required-mark">*</text>
					<text>客户电话</text>
				</view>
				<u--input slot="value" placeholder="请输入" border="surround" v-model="form.partaTel"></u--input>
			</u-cell>
			<u-cell title="客户传真" arrow-direction="down">
				<u--input slot="value" placeholder="请输入" border="surround" v-model="form.partaFax"></u--input>
			</u-cell>
			<u-cell title="客户Email" arrow-direction="down">
				<u--input slot="value" placeholder="请输入" border="surround" v-model="form.partaEmail"></u--input>
			</u-cell>
			<u-cell title="客户客户地址" arrow-direction="down">
				<u--input slot="value" placeholder="请输入" border="surround" v-model="form.partaAddress"></u--input>
			</u-cell>
			<u-cell arrow-direction="down">
				<view slot="title">
					<text class="required-mark">*</text>
					<text>售出方名称</text>
				</view>
				<u--input slot="value" placeholder="请输入" v-if="enterprisePage.length <= 1" border="surround" v-model="form.partbName"></u--input>
				<uni-data-picker v-model="form.partbName" slot="value" placeholder="请选择" :localdata="enterprisePage" :map="{text:'name',value:'name'}" @change="sourceCodeOnchange">
				</uni-data-picker>
			</u-cell>

			<u-cell title="售出方统一社会信用代码" arrow-direction="down">
				<u--input slot="value" placeholder="请输入" border="surround"
					v-model="form.partbUnifiedSocialCreditCode"></u--input>
			</u-cell>
			<u-cell arrow-direction="down">
				<view slot="title">
					<text class="required-mark">*</text>
					<text>售出方联系人</text>
				</view>
				<u--input slot="value" placeholder="请选择" border="surround" v-model="form.partbLinkName" @click.native="selectUserShow"></u--input>
			</u-cell>
			<u-cell arrow-direction="down">
				<view slot="title">
					<text class="required-mark">*</text>
					<text>售出方联系电话</text>
				</view>
				<u--input slot="value" placeholder="请输入" border="surround" v-model="form.partbTel"></u--input>
			</u-cell>
			<u-cell title="售出方传真" arrow-direction="down">
				<u--input slot="value" placeholder="请输入" border="surround" v-model="form.partbFax"></u--input>
			</u-cell>
			<u-cell title="售出方Email" arrow-direction="down">
				<u--input slot="value" placeholder="请输入" border="surround" v-model="form.partbEmail"></u--input>
			</u-cell>
			<u-cell title="售出方地址" arrow-direction="down">
				<u--input slot="value" placeholder="请输入" border="surround" v-model="form.partbAddress"></u--input>
			</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>
		<view class="" v-show="current==2">
			<u-cell-group>
				<u-cell title="总金额" arrow-direction="down">
					<text slot="value"> {{ form.totalAmount || 0 }}元</text>
				</u-cell>
				<u-cell title="优惠后总金额" arrow-direction="down">
					<u--input type="number" @blur="discountInput" slot="value"
						:disabled="!!form.contractId || !form.totalAmount" placeholder="请输入" border="surround"
						v-model="form.payAmount">
						<template slot="suffix">元</template>
					</u--input>
				</u-cell>
			</u-cell-group>

			<produceList ref="produceListRef" :pricingWay="form.pricingWay" :contractId="form.contractId"
				:columns="columns"></produceList>
		</view>


		<u-toast ref="uToast"></u-toast>
		<ba-tree-picker ref="treePicker" :multiple="false" @select-change="confirm" :localdata="listData" valueKey="id"
			textKey="name" childrenKey="children" />
	</view>
</template>

<script>
	import {
		getByCode
	} from '@/api/pda/common.js'
	import {
		getcontactlink,
	} from '@/api/saleManage/contact/index.js'
	import {
		getContract,
		saveSaleorder,
		getSaleOrderDetail,
	} from '@/api/saleManage/saleorder'
	import {
		listOrganizations,
	} from '@/api/myTicket/index.js'
	import {
		enterprisePage,
	} from '@/api/mainData/index.js'

	import baTreePicker from '@/components/ba-tree-picker/ba-tree-picker.vue'
	import produceList from '../components/produceList.vue'


	export default {
		components: {
			produceList,

			baTreePicker
		},
		data() {
			return {
				list: ['订单信息', '基本信息', '产品清单'],
				current: 0,
				listData: [],
				userList: [],
				form: {
					id: '',
					contractId: '',
					orderFiles: [],
					contractName: '',
					salesDeptName: '',
					pricingWay: 1,
					payAmount: '',
					generatePurchase: 0,
					generateProduce: 0,
					generateProject: 0,
					projectName: '',
					projectId: '',
					receiveAddress: '',
					remark: '',
					saleType: '',
					saleTypeName: '',
					totalAmount: '',
					settlementMode: '4',
					settlementModeName: '分期付款',
					partaUnifiedSocialCreditCode: '',
					partbUnifiedSocialCreditCode: '',
					partaAddress: '',
					partaEmail: '',
					partaFax: '',
					partaId: '',
					partaLinkId: '',
					partaLinkName: '',
					partaName: '',
					partaTel: '',
					partbAddress: '',
					partbEmail: '',
					partbFax: '',
					partbId: '',
					partbLinkId: '',
					partbLinkName: '',
					partbName: '',
					partbTel: '',
					needProduce: 1
				},
				order_type: [],
				settlement_mode: [],
				linkList: [],
				enterprisePage: [],
				columns: [
					[{
						label: '产品名称：',
						prop: 'productName',
						type: 'title',
						className: 'perce100',
					}],
					[{
						label: '编码：',
						prop: 'productCode'
					}, {
						label: '牌号：',
						prop: 'productBrand'
					}],
					[{
						label: '规格：',
						prop: 'specification'
					}, {
						label: '型号：',
						prop: 'modelType'
					}],
					[{
						label: '数量：',
						prop: 'totalCount',
						slot: 'totalCount',
					}, {
						label: '计量单位：',
						prop: 'measuringUnit',
					}],


					[{
						label: '单价：',
						prop: 'singlePrice',
						slot: 'singlePrice',
					}, {
						label: '折让单价：',
						formatter: (item) => {
							return (item.discountSinglePrice ?
								Number(item.discountSinglePrice).toFixed(2) :
								'') + '元';
						}
					}],
					[{
						label: '合计：',
						prop: 'totalPrice',
						formatter: (item) => {
							return (item.totalPrice || '') + '元';
						}
					}, {
						label: '折让合计：',
						formatter: (item) => {
							return (item.discountTotalPrice ?
								Number(item.discountTotalPrice).toFixed(2) :
								'') + '元';
						}
					}],
					[{
						label: '客户代号：',
						prop: 'customerMark',
						slot: 'customerMark',
					}],
					[{
						label: '单重：',
						prop: 'singleWeight',
						slot: 'singleWeight',
					}, {
						label: '总重：',
						prop: 'totalWeight',
					}],
					[{
						label: '客户期望交期：',
						prop: 'customerExpectDeliveryDeadline',
						slot: 'customerExpectDeliveryDeadline',
						className: 'perce100',
					}],
					[{
						label: '质保期：',
						prop: 'guaranteePeriod',
						slot: 'guaranteePeriod',
					}, {
						label: '单位：',
						prop: 'guaranteePeriodUnitCode',
						slot: 'guaranteePeriodUnitCode',
					}],
					[{
						label: '操作：',
						prop: 'action',
						type: 'action',
						className: 'perce100',
					}],
				],
				projectData: {}

			}
		},


		created() {

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

			})
			//选择客户回调
			uni.$off('setSelectList')
			uni.$on('setSelectList', async (data) => {
				if (data && data.length > 0) {
					this.changeParent(data[0])
				}

			})
			//总金额回显
			uni.$off('allsum')
			uni.$on('allsum', (allsum) => {
				this.form.totalAmount = allsum
				this.form.payAmount = allsum
			})
			//选择用户
			uni.$off('setUserInfo')
			uni.$on('setUserInfo', (data) => {
				if (data && data.length > 0) {
					this.$set(this.form, 'partbLinkId', data[0].id);
					this.$set(this.form, 'partbLinkName', data[0].name);
					this.$set(this.form, 'partbTel', data[0].phone);
					this.$set(this.form, 'partbEmail', data[0].email);
				}
			})
			//选择项目
			uni.$off('setProject')
			uni.$on('setProject', async (data) => {
				if (data && data.length > 0) {
					this.projectData = data[0];
					this.form = Object.assign({}, this.form, {
						projectName: this.projectData.name,
						projectId: this.projectData.id
					});

					if (this.projectData.contractId) {

						this.form = Object.assign({}, this.form, {
							contractId: this.projectData.contractId,
							contractName: this.projectData.contractName
						});
						this.getContract(this.projectData.contractId);
					} else if (this.projectData.contactId) {
						const data = await contactDetail(this.projectData.contactId);
						if (data.base?.id) {
							this.changeParent(data.base);
						}
					}
				}
			})
		},
		onLoad(data) {

			if (data && data.id) {
				this.getSaleOrderDetail(data.id)
			}
			this.enterprisePageFn(data.id)

		},
		onUnload() {
			uni.$off('setContractList')
			uni.$off('setSelectList')
			uni.$off('allsum')
			uni.$off('setUserInfo')
			uni.$off('setProject')

		},
		methods: {
			getDept() {
				listOrganizations(1).then(data => {
					this.listData = data
				})
			},


			//获取订单详情
			async getSaleOrderDetail(id) {
				const data = await getSaleOrderDetail(id);
				if (data) {
					this.$nextTick(() => {

						this.form = data;
						this.$refs.produceListRef.init(data.productList)
						this.getLinkInfo(data.partaId);

					});
				}
			},
			getByCode() {
				const codeS = ['order_type', 'settlement_mode']
				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]
						}
					})
				})

			},
			enterprisePageFn(id) {
				enterprisePage({
					pageNum: 1,
					size: 100
				}).then((res) => {
					this.enterprisePage = res.list;

					if (!id) {
						this.form.partbName = this.enterprisePage[0].name;
						this.form.partbUnifiedSocialCreditCode =
							this.enterprisePage[0].unifiedSocialCreditCode;
						this.form.partbFax = this.enterprisePage[0].fax;
						this.form.partbAddress = this.enterprisePage[0].address;
					}

				});
			},
			discountInput() {
				this.$refs.produceListRef.discountInputByOrder(this.form.payAmount)
			},
			settlementModeChange(e) {
				this.form.settlementModeName = e.detail.value[0].text;
			},
			//选择部门
			salesDeptShow() {
				this.$refs.treePicker._show()
			},
			//部门回调
			confirm(data, name) {
				this.form.salesDeptName = name || ''
				this.form.salesDeptId = data[0] || ''
			},

			//选择客户
			selectContactShow() {
				if (this.form.contractId) {
					this.$refs.uToast.show({
						type: "error",
						message: "选择了合同不能更改客户",
					})
					return
				}
				uni.navigateTo({
					url: '/pages/saleManage/components/selectContact?isAll=' + 2
				})
			},
			//选择客户回调
			async changeParent(obj) {
				this.form = Object.assign({}, this.form, {
					partaId: obj.id,
					partaName: obj.name,
					partaAddress: obj.addressName + obj.address,
					partaLinkId: '',
					partaLinkName: '',
					partaEmail: '',
					partaTel: '',
					customerMark: obj.serialNo
				});
				await this.getLinkInfo(obj.id);
				this.$nextTick(() => {
					let firstLink =
						this.linkList.find((item) => item.ifChief == 1) || {};
					this.form = Object.assign({}, this.form, {
						partaLinkId: firstLink.id || this.linkList[0]?.id,
						partaLinkName: firstLink.linkName || this.linkList[0]?.linkName,
						partaTel: firstLink.mobilePhone || this.linkList[0]?.mobilePhone
					});
					this.setCustomerMark();
				});
			},
			setCustomerMark() {
				this.$refs.produceListRef.setCustomerMark(this.form.customerMark)

			},
			//选择用户
			selectUserShow() {
				uni.navigateTo({
					url: '/pages/saleManage/components/selectUser?isAll=' + 2
				})
			},
			//选择合同
			selectContractShow() {
				uni.navigateTo({
					url: '/pages/saleManage/components/selectContract?isAll=' + 2
				})
			},
			//选择合同
			selectProjectShow() {
				uni.navigateTo({
					url: '/pages/saleManage/components/selectProject?isAll=' + 2
				})
			},

			//选择合同获取合同的详情
			async getContract(id) {
				const data = await getContract(id);
				if (data) {
					this.$nextTick(() => {
						let {
							contractVO
						} = data;
						// this.form=contractVOform.receiveAddress
						let {
							partaAddress,
							partaEmail,
							partaFax,
							partaId,
							partaLinkId,
							partaLinkName,
							partaName,
							partaTel,
							partbAddress,
							partbEmail,
							partbFax,
							partbId,
							partbLinkId,
							partbLinkName,
							partbName,
							partbTel,
							totalPrice,
							discountTotalPrice,
							partaUnifiedSocialCreditCode,
							partbUnifiedSocialCreditCode,
							settlementMode,
							settlementModeName,
							pricingWay,
							contractNo,
							contractNumber
						} = contractVO;
						this.form = Object.assign({}, this.form, {
							partaAddress,
							partaEmail,
							partaFax,
							partaId,
							partaLinkId,
							partaLinkName,
							partaName,
							partaTel,
							partbAddress,
							partbEmail,
							partbFax,
							partbId,
							partbLinkId,
							partbLinkName,
							partbName,
							partbTel,
							pricingWay,
							totalPrice,
							discountTotalPrice,
							partaUnifiedSocialCreditCode,
							partbUnifiedSocialCreditCode,
							totalAmount: totalPrice,
							payAmount: discountTotalPrice || totalPrice,
							receiveAddress: partaAddress,
							settlementMode,
							settlementModeName,
							contractNo,
							contractNumber
						});
						this.getLinkInfo(partaId);
						this.$refs.produceListRef.init(data.productList)

					});
				}
			},

			//更新联系人数据
			async getLinkInfo(contactId) {
				const data = await getcontactlink({
					contactId
				});
				if (data && data?.length) {
					this.linkList = data;
				}
			},
			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()
			},
			linkChange(e) {
				const value = e.detail.value
				if (value.length > 0) {
					const data = this.linkList.find(item => item.id == value[0].value)
					this.form = Object.assign({}, this.form, {
						partaEmail: data?.email,
						partaLinkName: data?.linkName || '',
						partaTel: data?.mobilePhone || data?.phone || '',
						partaLinkId: data?.id
					});
				}


			},
			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.settlementMode) {
						this.$refs.uToast.show({
							type: "error",
							message: "请选择结算方式",
						})
						return
					}
					if (!this.form.saleType) {
						this.$refs.uToast.show({
							type: "error",
							message: "请选择销售类型",
						})
						return
					}
					if (!this.form.partaName) {
						this.$refs.uToast.show({
							type: "error",
							message: "请选择客户",
						})
						return
					}
					if (!this.form.partaLinkName) {
						this.$refs.uToast.show({
							type: "error",
							message: "请选择客户联系人",
						})
						return
					}
					if (!this.form.partaTel) {
						this.$refs.uToast.show({
							type: "error",
							message: "请输入客户联系电话",
						})
						return
					}
					if (!this.form.partbName) {
						this.$refs.uToast.show({
							type: "error",
							message: "请输入售出方名称",
						})
						return
					}
					if (!this.form.partbLinkName) {
						this.$refs.uToast.show({
							type: "error",
							message: "请输入售出方联系人",
						})
						return
					}
					if (!this.form.partbTel) {
						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 saleTypeName = this.order_type.find(item => item.value == this.form.saleType)?.text
					const data = Object.assign({}, this.form, {
						productList: this.$refs.produceListRef.getValue(),
						saleTypeName
					})
					saveSaleorder(data)
						.then((id) => {
							uni.hideLoading()
							this.back()
						})
						.catch((e) => {
							uni.hideLoading()
						});
				} catch (error) {
					uni.hideLoading()
					console.log(error, 'error')
				}
			},

		}
	}
</script>

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

	.mainBox {
		padding-bottom: 84rpx;
	}

	.required-mark {
		color: #FF3333;
		margin-right: 4rpx;
	}

	.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-subsection__item__text {
		font-size: 28rpx !important;
	}
</style>