<template>
	<!-- 工单详情发起特提 -->
	<el-dialog
		v-model="state.dialogVisible"
		draggable
		title="特提申请"
		width="50%"
		append-to-body
		destroy-on-close
		@close="close"
		@mouseup="mouseup"
		:style="'transform: ' + state.transform + ';'"
		ref="dialogRef"
	>
		<div class="collapse-container">
			<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="12" :lg="12" :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" v-if="['YiBin'].includes(themeConfig.appScope)">
							<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"
									:multiple-limit="1"
								/>
							</el-form-item>
						</el-col>
					</template>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="['YiBin'].includes(themeConfig.appScope)">
						<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="24" :md="12" :lg="12" :xl="12" v-if="['ZiGong'].includes(themeConfig.appScope) && state.ruleForm.nextStepCode">
						<el-form-item label="特提次数" prop="cause">
							{{ state.orderDetail.specialNum }}次
						</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' }]">
							<common-advice
								@chooseAdvice="chooseAdvice"
								v-model="state.ruleForm.reason"
								placeholder="请填写特提理由"
								:loading="state.loading"
								:commonEnum="commonEnum.Teti"
							/>
						</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">
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';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '@/stores/userInfo';
import { useThemeConfig } from '@/stores/themeConfig';
import { commonEnum } from '@/utils/constants';

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

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 是否显示弹窗
	loading: false, // 是否显示加载
	ruleForm: {
		nextStepCode: null, // 特提节点
		timeLimitUnit: 2, // 期满时间单位
		alterTime: true, // 是否修改期满时间
		nextHandlers: [], // 办理对象
		stepType: null,
		reason: '',
	},
	orderDetail: {}, // 工单详情
	workflowId: null, // 工作流id
	transform: 'translate(0px, 0px)', // 滚动条位置
});
const ruleFormRef = ref<RefType>();
const specialReason = ref<EmptyArrayType>([]); // 特提理由
const steps = ref<EmptyArrayType>([]); // 特提节点
const stepsItems = ref<EmptyArrayType>([]); // 特提部门
const specialTimeType = ref<EmptyArrayType>([]); // 期满时间单位
const baseTypeId = ref<string>(''); // 默认选中的特提节点ID
/**
 * @description 打开弹窗
 * @param {object} val 工单详情
 */
const isTerminate = ref(false); //  终止需要提示
const openDialog = async (val: any) => {
	state.orderDetail = val;
	state.workflowId = val.workflowId;
	state.loading = true;
	state.dialogVisible = true;
	try {
		const { result } = await specialApplyBase(val.workflowId);
		baseTypeId.value = result?.baseTypeId ?? '';
		steps.value = result?.step?.steps ?? [];
		specialReason.value = result.specialReason ?? [];
		specialTimeType.value = result.specialTimeType ?? [];
		if (result?.baseTypeId) selectTrace(result?.baseTypeId, true);
		isTerminate.value = result?.isTerminate; // 终止需要提示
	} 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 chooseAdvice = (item: any) => {
	state.ruleForm.reason += item.content;
};
// 设置抽屉
const dialogRef = ref<RefType>();
const mouseup = () => {
	state.transform = dialogRef.value.dialogContentRef.$el.style.transform;
};
// 选择节点确定处理对象
const stores = useUserInfo();
const { userInfos } = storeToRefs(stores);
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const selectTrace = (val: any, choose?: boolean) => {
	const next = steps.value.find((item) => item.key === val);
	if (choose) state.ruleForm.nextStepCode = val;
	state.ruleForm.nextStepName = next?.value;
	state.ruleForm.businessType = next.businessType;
	state.ruleForm.flowDirection = next.flowDirection;
	state.ruleForm.handlerType = next.handlerType;
	ruleFormRef.value?.resetFields('nextHandlers');
	stepsItems.value = next?.items ?? [];
	state.ruleForm.stepType = next.stepType;
	stepsItems.value = stepsItems.value.map((item: any) => {
		return {
			value: {
				...item,
			},
			label: item.value,
		};
	});
	if (baseTypeId.value === val) {
		//如果默认选中节点  判断选择的对象是否有当前用户 如果有 默认选中当前用户
		const user = stepsItems.value.find((item: any) => item.value.key === userInfos.value?.id);
		if (user) {
			state.ruleForm.nextHandlers = [user.value];
		}
	}
	state.ruleForm.flowDirection = next?.flowDirection;
	const isBanzhang = userInfos.value?.monitor; // 判断当前用户是否是班长
	const withHandler = stepsItems.value.find((item) => item.value.key === next.handler?.key); // 判断当前节点是否有之前选择的用户
	if (isBanzhang && withHandler) {
		state.ruleForm.nextHandlers = [next.handler];
	}
	queryHandleTime();
	// 若终止申请已同意的工单再次被特提后是无法重新派单给承办部门，若选择了派给承办部门则提示：“该工单已终止办理。”若派给非承办部门则是允许的
	if(isTerminate.value && [2,3].includes(next.businessType)){
		ElMessage.warning('该工单已终止办理！');
		ruleFormRef.value?.resetFields('nextStepCode');
	}
};
// 查询办理时限
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 ?? ''; // 办理时限单位
			state.loading = false;
		})
		.catch(() => {
			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,
			stepCode: state.orderDetail.actualHandleStepCode,
			stepName: state.orderDetail.actualHandleStepName,
		};
		specialApply(request)
			.then(() => {
				state.loading = false;
				closeDialog();
				emit('updateList');
				ElMessage.success('特提申请成功');
			})
			.catch(() => {
				state.loading = false;
			});
	});
};
defineExpose({
	openDialog,
	closeDialog,
});
</script>
