<template>
	<el-dialog v-model="state.dialogVisible" draggable title="特提审核" width="50%" append-to-body destroy-on-close @close="close">
		<div class="collapse-container pb1">
			<el-form label-width="110px" ref="ruleFormRef" :model="state.ruleForm">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="工单编码" class="mb5"> {{ state.detail?.order?.no }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="工单标题" class="mb5"> {{ state.detail?.order?.title }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="申请人" class="mb5"> {{ state.detail?.creatorName }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="申请部门" class="mb5"> {{ state.detail?.creatorOrgName }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="申请时间" class="mb5"> {{ formatDate(state.detail?.creationTime, 'YYYY-mm-dd HH:MM:SS') }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<el-form-item label="特提节点" class="mb5">
							{{ state.detail?.trace?.name }}
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<el-form-item label="特提原因" class="mb5">
							{{ state.detail?.cause }}
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="特提理由" class="mb5">
							{{ state.detail?.reason }}
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="附件" class="mb5">
							<annex-list name="特提附件" ref="annexListRef" businessId="" classify="特提申请" />
						</el-form-item>
					</el-col>
					<el-divider></el-divider>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<el-form-item label="特提节点" prop="traceId" :rules="[{ required: true, message: '请选择特提节点', trigger: 'change' }]">
							<el-select v-model="state.ruleForm.traceId" placeholder="请选择特提节点" class="w100" @change="selectTrace">
								<el-option v-for="item in traces" :value="item.id" :key="item.id" :label="item.name">
									<span style="float: left">{{ item.name }}</span>
									<span style="float: right; color: var(--el-text-color-secondary); font-size: var(--el-font-size-extra-small)">{{ item.acceptorOrgName }}</span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" v-if="state.ruleForm.traceId">
						<el-form-item label="办理时限" prop="timeLimit" :rules="[{ required: true, message: '请输入办理时限', trigger: 'blur' }]">
							<el-row :gutter="10" class="w100">
								<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
									<el-input-number
										placeholder="办理时限"
										v-model="state.ruleForm.timeLimit"
										controls-position="right"
										class="w100"
										:min="1"
										:max="99"
									></el-input-number>
								</el-col>
								<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-loading="state.loading">
                  <el-form-item
                      label=""
                      label-width="0"
                      prop="timeLimitUnit"
                      :rules="[{ required: true, message: '请选择办理时限单位', trigger: 'change' }]"
                  >
                    <el-select v-model="state.ruleForm.timeLimitUnit" placeholder="办理时限单位">
                      <el-option v-for="item in specialTimeType" :value="item.key" :key="item.key" :label="item.value" />
                    </el-select>
                  </el-form-item>
								</el-col>
							</el-row>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="" prop="alterTime">
							<el-checkbox v-model="state.ruleForm.alterTime" label="无需计算期满时间" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="审批意见" prop="reason" :rules="[{ required: true, message: '请填写特提审批意见', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.reason" type="textarea" :autosize="{ minRows: 6, maxRows: 10 }" placeholder="请填写特提审批意见" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
        <el-button type="primary" @click="onReject(ruleFormRef)" :loading="state.loading">驳回</el-button>
				<el-button type="primary" @click="onPass(ruleFormRef)" :loading="state.loading">通过</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script setup lang="ts" name="SpecialDialogAudit">
import { defineAsyncComponent, reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import { formatDate } from '/@/utils/formatTime';
import { specialApplyBase, specialApprove, specialDetail, specialTime } from '/@/api/business/special';
import { debounce } from '/@/utils/tools';
import dayjs from 'dayjs';

// 引入组件
const AnnexList = defineAsyncComponent(() => import('/@/components/AnnexList/index.vue'));

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 是否显示弹窗
	loading: false, // 是否显示加载
	ruleForm: {
		traceId: null, // 特提节点
    timeLimitUnit: 2, // 期满时间单位
    orgId: null, // 部门id
    orgName: null, // 部门名称
    alterTime: false, // 是否修改期满时间
	},
	detail: {}, // 详情信息
});
const ruleFormRef = ref<RefType>();
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息
const traces = ref<EmptyArrayType>([]); // 特提节点
const specialTimeType = ref<EmptyArrayType>([]); // 期满时间单位
// 打开弹窗
const openDialog = async (val: any) => {
	console.log(val, 'val');
	state.loading = true;
  state.dialogVisible = true;
	try {
		const [baseRes, detailRes] = await Promise.all([
			specialApplyBase(val.order?.workflowId),
			specialDetail(val.id)
		]);
		traces.value = baseRes.result.traces ?? [];
		specialTimeType.value = baseRes.result.specialTimeType ?? [];
		state.detail = detailRes.result;
	} catch (e) {
		console.log(e);
	} finally {
		state.loading = false;
	}
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
};

// 选择节点确定部门
const selectTrace = (val: any) => {
  const trace = traces.value.find((item) => item.id === val);
  state.ruleForm.orgId = trace?.acceptorOrgId;
  state.ruleForm.orgName = trace?.acceptorOrgName;
  queryHandleTime();
};
// 查询办理时限
const queryHandleTime = () => {
  if (state.ruleForm.alterTime) return;
  state.loading = true;
  specialTime({ OrderId: state.detail.orderId, TraceId: state.ruleForm.traceId })
      .then((res) => {
        state.ruleForm.timeLimit = res.result ?? 0;
      })
      .finally(() => {
        state.loading = false;
      });
};
// 通过
const annexListRef = ref<RefType>(); // 附件列表
const onPass = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		let request = {
      id:state.detail.id,
      orderId: state.detail.orderId,
      orgId: state.ruleForm.orgId,
      orgName: state.ruleForm.orgName,
      timeLimit: state.ruleForm.timeLimit,
      timeLimitUnit: state.ruleForm.timeLimitUnit,
      cause: state.detail.cause,
      opinion: state.detail.reason,
      files: annexListRef.value?.fileList,
      state:1, // 审核结果 0 待审核 1 审核通过 2 审核不通过
		};
		specialApprove(request)
			.then((res: any) => {
				state.loading = false;
				closeDialog();
				emit('updateList');
				ElMessage.success('操作成功');
			})
			.catch(() => {
				state.loading = false;
			});
	});
};
// 驳回
const onReject = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid: boolean) => {
    if (!valid) return;
    state.loading = true;
    let request = {
      id:state.detail.id,
      orderId: state.detail.orderId,
      orgId: state.ruleForm.orgId,
      orgName: state.ruleForm.orgName,
      timeLimit: state.ruleForm.timeLimit,
      timeLimitUnit: state.ruleForm.timeLimitUnit,
      cause: state.detail.cause,
      opinion: state.detail.reason,
      files: annexListRef.value?.fileList,
      state:2,
    };
    specialApprove(request)
        .then((res: any) => {
          state.loading = false;
          closeDialog();
          emit('updateList');
          ElMessage.success('操作成功');
        })
        .catch(() => {
          state.loading = false;
        });
  });
};
defineExpose({
	openDialog,
	closeDialog,
});
</script>
