<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="24" :md="12" :lg="12" :xl="12">
						<el-form-item label="特提节点" prop="nextStepCode" :rules="[{ required: true, message: '请选择特提节点', trigger: 'change' }]">
							<el-select v-model="state.ruleForm.nextStepCode" placeholder="请选择特提节点" class="w100" @change="selectTrace">
								<el-option v-for="item in steps" :value="item.key" :key="item.key" :label="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
          <template v-if="state.ruleForm.nextStepCode">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" >
              <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">
                    <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="24" :md="12" :lg="12" :xl="12">

              <el-form-item label="办理对象" prop="nextHandlers" :rules="[{ required: true, message: '请选择办理对象', trigger: 'change' }]">
                <el-select-v2
                    v-model="state.ruleForm.nextHandlers"
                    :options="stepsItems"
                    placeholder="请选择办理对象"
                    class="w100"
                    multiple
                    clearable
                    collapse-tags
                    collapse-tags-tooltip
                    filterable
                    value-key="key"
                />
              </el-form-item>
            </el-col>
          </template>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<el-form-item label="特提原因" prop="cause" :rules="[{ required: true, message: '请选择特提原因', trigger: 'change' }]">
							<el-select v-model="state.ruleForm.cause" placeholder="请选择特提原因" class="w100">
								<el-option v-for="item in specialReason" :value="item.dicDataName" :key="item.dicDataName" :label="item.dicDataName" />
							</el-select>
						</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-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="附件" prop="files" :rules="[{ required: false, message: '请选择附件', trigger: 'change' }]">
              <annex-list name="特提附件" v-model:format="filesFormat" :businessId="state.orderDetail.id" classify="特提附件" />
						</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="onSubmit(ruleFormRef)" :loading="state.loading">提交</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script setup lang="ts" name="SpecialDialog">
import { defineAsyncComponent, reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { specialApplyBase, specialApply } from '@/api/business/special';
import {orderTimeConfig} from "@/api/business/order";

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

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 是否显示弹窗
	loading: false, // 是否显示加载
	ruleForm: {
    nextStepCode: null, // 特提节点
		timeLimitUnit: 2, // 期满时间单位
		alterTime: false, // 是否修改期满时间
    nextHandlers: [], // 办理对象
	},
	orderDetail: {}, // 工单详情
  workflowId: null, // 工作流id
});
const ruleFormRef = ref<RefType>();
const specialReason = ref<EmptyArrayType>([]); // 特提理由
const steps = ref<EmptyArrayType>([]); // 特提节点
const stepsItems = ref<EmptyArrayType>([]); // 特提部门
const specialTimeType = ref<EmptyArrayType>([]); // 期满时间单位
/**
 * @description 打开弹窗
 * @param {object} val 工单详情
 */
const openDialog = async (val: any) => {
	state.orderDetail = val;
  state.workflowId = val.workflowId;
	state.loading = true;
	state.dialogVisible = true;
	try {
		const [baseRes] = await Promise.all([specialApplyBase(val.workflowId)]);
    steps.value = baseRes.result?.step?.steps ?? [];
		specialReason.value = baseRes.result.specialReason ?? [];
		specialTimeType.value = baseRes.result.specialTimeType ?? [];
	} catch (e) {
		console.log(e);
	} finally {
		state.loading = false;
	}
	state.dialogVisible = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
  steps.value = [];
  stepsItems.value = [];
};
// 选择节点确定处理对象
const selectTrace = (val: any) => {
	const step = steps.value.find((item) => item.key === val);
  state.ruleForm.nextStepName = step?.value;
  ruleFormRef.value?.resetFields('nextHandlers');
  stepsItems.value = step?.items ?? [];
  stepsItems.value = stepsItems.value.map((item: any) => {
    return {
      value: {
        ...item,
      },
      label: item.value,
    };
  })
  state.ruleForm.flowDirection = step?.flowDirection;
	queryHandleTime();
};
// 查询办理时限
const queryHandleTime = () => {
	if (state.ruleForm.alterTime) return;
	state.loading = true;
  orderTimeConfig({ acceptTypeCode: state.orderDetail.acceptTypeCode, FlowDirection: state.ruleForm.flowDirection })
		.then((res) => {
			state.ruleForm.timeLimit = res.result.count ?? 0;  // 办理时限
      state.ruleForm.timeLimitUnit = res.result.timeType ?? ''; // 办理时限单位
		})
		.finally(() => {
			state.loading = false;
		});
};
// 提交
const filesFormat = ref<EmptyArrayType>([]); // 附件列表
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		let request = {
			...state.ruleForm,
      workflowId: state.workflowId,
			orderId: state.orderDetail.id,
			files: filesFormat.value,
			audit: false,
		};
		specialApply(request)
			.then((res: any) => {
				state.loading = false;
				closeDialog();
				emit('updateList');
				ElMessage.success('操作成功');
			})
			.catch(() => {
				state.loading = false;
			});
	});
};
defineExpose({
	openDialog,
	closeDialog,
});
</script>
