<template>
	<view class="">
		<u--form style="margin: 0 20px;" labelPosition="left" :model="form" :rules="rules" ref="uForm"
			labelWidth='140rpx'>
			<u-form-item v-if="['QCLeaderApprove'].includes(taskDefinitionKey)" label="质检员" prop="qualityInspectorName"
				required>
				<u--input clearable placeholder="请选择" border="surround" v-model="form.qualityInspectorName"
					@click.native="showTechnicianPicker"></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 class="btnList">
			<u-button v-if="passBtnDisabled" style="width: 45%;margin-bottom: 10rpx;" :loading='loading' type="success" text="通过" @click="handleAudit(1)">
			</u-button>
			<u-button v-if="acceptBtnDisabled" style="width: 45%;margin-bottom: 10rpx;" :loading='loading' type="success" text="申请入库" @click="storeManagerApprove">
			</u-button>
			<u-button style="width: 45%;" :loading='loading' type="error" text="驳回" @click="handleAudit(0)"></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>
	</view>
</template>

<script>
	import {
		approveTaskWithVariables,
		rejectTask,
		getWarehouseListByIdsAPI,
		getOutInBySourceBizNo,
		purchaseOrderReceiveGetByIdAPI
	} from '@/api/wt/index.js'
	import {
		listAllUserBind
	} from '@/api/common.js'
	import { storage } from '@/api/warehouseManagement/index.js'
	export default {
		name: 'taskSubmit',
		props: {
			businessId: {
				default: ''
			},
			taskId: {
				default: ''
			},
			id: {
				default: ''
			},
			taskDefinitionKey: {
				default: ''
			},
			fromUser: {
				default: ''
			}
		},
		computed: {
			acceptBtnDisabled() {
				return ['storeManagerApprove'].includes(this.taskDefinitionKey) && ![1, 2].includes(Number(this.outInData.flowableStatus))
			},
			passBtnDisabled() {
				return !['storeManagerApprove'].includes(this.taskDefinitionKey) || (['storeManagerApprove'].includes(this.taskDefinitionKey) && [2].includes(Number(this.outInData.flowableStatus)));
			}
		},
		data() {
			return {
				showAction: false,
				loading: false,
				technicianShow: false,
				userOptions: [],
				actionList: [{
					name: '作废',
					fontSize: '28',
					color: '#ffaa7f'
				}],
				outInData: {
					flowableStatus: ''
				},
				form: {
					qualityInspectorName: '',
					qualityInspector: '',
					reason: '同意',
				},
				rules: {
					reason: {
						type: 'string',
						required: true,
						message: '请输入审批建议',
						trigger: 'blur'
					},
					qualityInspectorName: {
						type: 'string',
						required: true,
						message: '请选择质检员',
						trigger: ['blur', 'change']
					},
				}
			}
		},
		mounted() {
			this.$refs.uForm.setRules(this.rules)
			this.getUserOptions()

		},
		methods: {
			async getUserOptions() {
				const data = await listAllUserBind()
				this.userOptions.push(data)

				if (this.taskDefinitionKey == 'storeManagerApprove') {
					let data = await purchaseOrderReceiveGetByIdAPI(this.businessId);
					try {
						this.outInData = await getInfoBySourceBizNo(
							data.receiveNo
						);
					console.log('outInData----------', this.outInData);
					} catch (error) {}
				}
			},
			showTechnicianPicker(val) {
				if (val.target.nodeName == 'I') {
					this.form.qualityInspector = ''
					this.form.qualityInspectorName = ''
					return
				}
				this.technicianShow = true
			},
			selectTechnicianInfo(e) {
				this.form.qualityInspector = e.value[0]?.id
				this.form.qualityInspectorName = e.value[0]?.name
				this.technicianShow = false
			},
			async handleAudit(status) {
				if (!!status) await this.$refs.uForm.validate()
				let storemanIds = []
				if (this.taskDefinitionKey === 'deptLeaderApprove') {
					let form = await this.getTableValue();
					let ids = form.productList.map((item) => item.warehouseId);
					let data = await getWarehouseListByIdsAPI(ids || []);
					storemanIds = data.map((item) => item.ownerId) || [];
					if (!storemanIds.length) return uni.$u.toast('未配置仓管人员，请检查')
				}
				this.loading = true
				await this._approveTaskWithVariables(status, Array.from(new Set(storemanIds)).toString());
			},
			async _approveTaskWithVariables(status, storemanIds) {
				let variables = {
					pass: !!status,
					storemanIds
				};
				if (this.form.qualityInspector) {
					variables['qualityInspector'] = this.form.qualityInspector;
				}
				const requestUrl = !!status ? approveTaskWithVariables : rejectTask
				let res = await requestUrl({
					id: this.taskId,
					reason: this.form.reason,
					variables
				})

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

			async storeManagerApprove() {
				let res = await this.getTableValue();
				let storageData = res.returnStorageData;
				console.log('storageData~~~', storageData);
				// return
				// 出库来源isSkip 0-正常  1-外部(外部跳过内部审核流程)
				storageData.isSkip = 1;
				storageData.fromUser = this.fromUser;
				try {
					this.loading = true;
					await storage(storageData);
					approveTaskWithVariables({
						id: this.taskId,
						reason: this.form.reason,
						variables: {
							pass: true
						}
					}).then((res) => {
						if (res.code != '-1') {
							this.$emit('handleAudit', {
								status: 1,
								title: '入库'
							});
						}
						this.loading = false;
					});
				} catch (error) {
					this.loading = false;
					console.error('保存失败：', error);
				}
			},

			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('用户点击取消');
							}
						}
					});
				}
			},

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

<style scoped>
.btnList {
	display: flex;

}

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