<template>
	<view class="">
		<u--form style="margin: 0 20px;" labelPosition="left" :model="form" :rules="rules" ref="uForm"
			labelWidth='140rpx'>
			<u-form-item v-if="taskDefinitionKey === 'deptLeaderAssign'" label="采购部门" prop="useDeptId">
				<u--input clearable placeholder="请选择" border="surround" v-model="form.useDeptName"
					@click.native="openDepartmentPicker"></u--input>
			</u-form-item>
			<u-form-item v-if="taskDefinitionKey === 'deptLeaderAssign'" label="采购员" prop="assignList" required>
				<u--input clearable placeholder="请选择" border="surround" v-model="form.assignListName"
					@click.native="openPicker"></u--input>
			</u-form-item>
			<u-form-item label="审批建议" prop="reason" required>
				<u--textarea style="width: 100%;" height='120' border='surround' placeholder="请输入审批建议"
					v-model="form.reason"></u--textarea>
			</u-form-item>
		</u--form>
		<view>
			<u-button v-if="!['storeManagerApprove'].includes(taskDefinitionKey)" style="width: 100%;margin-bottom: 10rpx;" icon="edit-pen" :loading='loading' type="success"
				text="通过" @click="handleAudit(1)">
			</u-button>
			<u-button v-if="['storeManagerApprove'].includes(taskDefinitionKey)" style="width: 100%;margin-bottom: 10rpx;" icon="edit-pen" :loading='loading' type="success"
				text="申请入库" @click="handleAudit(1)">
			</u-button>
			<u-button style="width: 100%;" :loading='loading' type="error" icon="close" text="驳回"
				@click="rejectTask" v-if="!['starter'].includes(taskDefinitionKey)"></u-button>
		</view>
		<view class="btnConcel">
			<u-button @click="showAction = true">更多</u-button>
		</view>
		<u-action-sheet :actions="actionList" :closeOnClickOverlay="true" :closeOnClickAction="true" title="更多操作" :show="showAction" @close="showAction = false" @select="selectActionClick"></u-action-sheet>
		<u-picker itemHeight='60' :show="technicianShow" visibleItemCount='10' :columns="userOptions" keyName="name"
			@confirm='selectTechnicianInfo' @cancel='technicianShow = false' title='选择采购员'></u-picker>
		<ba-tree-picker ref="departmentPicker" :multiple="false" @select-change="departmentConfirm" title="选择采购部门"
			:localdata="departmentOption" valueKey="id" textKey="name" childrenKey="children" />
		<ba-tree-picker ref="treePicker" :multiple="true" @select-change="confirm" title="选择采购员"
			:localdata="userOptions" valueKey="id" textKey="name" childrenKey="child" />
	</view>
</template>

<script>
	import {
		approveTaskWithVariables,
		AssignPurchasePlanUserAPI,
		cancelTask
	} from '@/api/wt/index.js'
	import {
		listOrganizations,
		getUserPage,
		listAllUserBind
	} from '@/api/common'
	import {
		toTreeData
	} from '@/utils/utils.js'
	export default {
		name: 'taskSubmit',
		props: {
			businessId: {
				default: ''
			},
			taskId: {
				default: ''
			},
			id: {
				default: ''
			},
			taskDefinitionKey: {
				default: ''
			}
		},

		data() {
			return {
				departmentOption: [],
				showAction: false,
				loading: false,
				actionList: [{
					name: '作废',
					fontSize: '28',
					color: '#ffaa7f'
				}],
				technicianShow: false,
				userOptions: [],
				form: {
					userId: '',
					useDeptId: '',
					useDeptName: '',
					userName: '',
					assignListName: '',
					assignList: [],
					reason: '',
				},
				rules: {
					reason: {
						type: 'string',
						required: true,
						message: '请输入审批建议',
						trigger: 'blur'
					},
					useDeptId: {
						type: 'string',
						required: false,
						message: '请选择采购部门',
						trigger: ['blur','change']
					},
					assignList: {	
						type: 'array',
						required: true,
						message: '请选择采购员',
						trigger: ['blur','change']
					},
				}
			}
		},
		created() {
			this.initDeptData()
			this.getUserOptions()
		},
		mounted() {
			this.$refs.uForm.setRules(this.rules)
		},
		methods: {
			openPicker() {
				this.$refs.treePicker._show()
			},
			confirm(data, name, allList) {
				console.log('name-------', data,name, allList)
				this.form.assignListName = name
				this.form.assignList = allList
				this.form.userId = allList.map(item => item.id)?.[0] || ''
				this.form.userName = allList.map(item => item.name)?.[0] || ''
			},

			openDepartmentPicker() {
				this.$refs.departmentPicker._show()
			},
			departmentConfirm(data, name, allList) {
				console.log(data, name, allList)
				this.form.useDeptId = data
				this.form.useDeptName = name
				this.form.userName = ''
				this.form.userId = ''
				this.form.assignListName = ''
				this.form.assignList = []
				if(!data) {
					this.getUserOptions()
				return;
				}
				getUserPage({
					groupId: data,
					size: 999
				}).then((data) => {
				    this.userOptions = data.list;
				});
			},
			async initDeptData() {
				let deptTreeList = await listOrganizations()
				this.departmentOption = toTreeData({
					data: deptTreeList,
					idField: 'id',
					parentIdField: 'parentId'
				})
			},
			selectActionClick(item) {
				console.log('selectActionClick', item)
				if (item.name == '作废') {
					uni.showModal({
						title: '提示',
						content: '是否确认作废？',
						success: (res) => {
							if (res.confirm) {
								this.loading = true
								cancelTask({
									taskId: this.taskId,
									id: this.id,
									reason: this.form.reason,
									businessId: this.businessId,
								}).then(() => {
									if (res.code != '-1') {
										this.loading = false
										this.$emit('handleAudit', {
											title: '作废'
										});
									}
								}).catch(() => {
									this.loading = false
									this.$message.error("流程作废失败");
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}
			},
			async getUserOptions() {
				const data = await listAllUserBind()
				this.userOptions = data
				console.log('userOptions~~~', this.userOptions)
			},
			showTechnicianPicker(val) {
				if (val.target.nodeName == 'I') {
					this.form.userId = ''
					this.form.userName = ''
					return
				}
				this.technicianShow = true
			},
			selectTechnicianInfo(e) {
				this.form.userId = e.value[0]?.id
				this.form.userName = e.value[0]?.name
				this.technicianShow = false
			},
			// async handleAudit(status) {
			// 	if (!!status) await this.$refs.uForm.validate()

			// 	await AssignPurchasePlanUserAPI({
			// 		userId: this.form.userId,
			// 		userName: this.form.userName,
			// 		id: this.taskId,
			// 		reason: this.form.reason,
			// 		businessId: this.businessId
			// 	})
			// 	this.loading = true
			// 	await this._approveTaskWithVariables(status);
			// },
			async handleAudit(status) {
				console.log(this.form)
				if (!!status) await this.$refs.uForm.validate()
				//主管指派采购员
				if (this.taskDefinitionKey === 'deptLeaderAssign') {
					await AssignPurchasePlanUserAPI({
						userId: this.form.userId,
						userName: this.form.userName,
						assignList: this.form.assignList,
						id: this.taskId,
						reason: this.form.reason,
						businessId: this.businessId
					});
				}
				let API = !!status ? approveTaskWithVariables : rejectTask;
				await API({
				id: this.taskId,
				reason: this.form.reason,
				variables: {
					// userId: this.form.userId,
					userId: this.form.assignList.map(item => item.id).join(','),
					pass: !!status
				}
				});
				this.$emit('handleAudit', {
				status,
				title: status === 0 ? '驳回' : ''
				});
			},
			async rejectTask(status) {
				await rejectTask({
					id: this.taskId,
					reason: this.form.reason,
					variables: {
						pass: !!status
					}
					});
				this.$emit('handleAudit', {
					status,
					title: status === 0 ? '驳回' : ''
				});
			},
			async _approveTaskWithVariables(status) {
				let variables = {
					pass: !!status
				};
				let res = await approveTaskWithVariables({
					id: this.taskId,
					reason: this.form.reason,
					variables
				})

				if (res.code != '-1') {
					this.$emit('handleAudit', {
						status,
						title: status === 0 ? '驳回' : ''
					});
				}
				this.loading = false
			},

			getTableValue() {
				return new Promise((resolve, reject) => {
					this.$emit('getTableValue', async (data) => {
						resolve(await data);
					});
				});
			}
		}
	}
</script>

<style scoped>
.btnConcel {
		margin-top: 20rpx;
	}
</style>