<template>
    <el-dialog title="发起工单" v-model="visible" width="850px" append-to-body>
		<el-form ref="orderFormRef" :model="form" :rules="rules" label-width="125px">
            <CorrelationSelect v-model="form.customerId" v-model:liaisonId="form.liaisonId" @custChange="custChange" />
			<el-form-item label="关联订单：" prop="orderFormId">
				<el-select v-model="form.orderFormId" placeholder="请选择订单">
                    <el-option v-for="item in orderFormData" :label="item.label" :value="item.value"></el-option>
                </el-select>
			</el-form-item>
            <el-form-item label="工单类型：" prop="workOrderCategoryId">
				<SelectDict v-model="form.workOrderCategoryId" placeholder="工单类型" dictCode="work_order_category_id"></SelectDict>
			</el-form-item>
			<el-form-item label="工单标题：" prop="title">
				<el-input v-model="form.title" placeholder="请输入工单标题" />
			</el-form-item>
            <el-form-item label="工单内容：" prop="content">
				<el-input
                    v-model="form.content"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入工单内容"
                    :maxlength="300"
                    resize="none"
                    show-word-limit
                />
			</el-form-item>
            <el-form-item label="紧急状态：" prop="urgentStatus">
				<SelectDict v-model="form.urgentStatus" placeholder="紧急状态" dictCode="urgent_status"></SelectDict>
			</el-form-item>
            <el-form-item label="上传附件：" class="form-item">
                <Upload v-model="form.resourceIdList" />
			</el-form-item>
            <el-form-item label="处理人员：" prop="ownerBy" class="form-item">
				<SelectUser v-model="form.ownerBy"></SelectUser>
			</el-form-item>
            <el-form-item label="通知人员：" prop="remindUserIds" class="form-item">
				<SelectUser multiple v-model="form.remindUserIds"></SelectUser>
                <p>注：处理完成后，将自动通知到所选人员。</p>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button :loading="buttonLoading" type="primary" @click="submitForm">提交</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
    import { getOrder, addOrder } from '@/api/order';
    import { OrderQuery, OrderForm } from '@/api/order/types';
    import { listOrderForm } from '@/api/orderForm';
    import CorrelationSelect from '@/components/common/correlationSelect.vue'
    import Upload from '@/components/FileUpload/upload.vue'
    import { useDictCache } from '@/hooks/web/useDict'

    const { queryDictDetailByCodes } = useDictCache(['work_order_category_id', 'urgent_status'])
    queryDictDetailByCodes()

    const emits = defineEmits(['refresh'])

    const buttonLoading = ref(false);
    const orderFormRef = ref<ElFormInstance>();

    const orderFormData = ref<{ label: string; value: string }[]>([])
    const getOrderFormData = () => {
        listOrderForm({ pageIndex: 1, pageSize: 999999, customerId: form.value.customerId }).then(res => {
            if(res.success) {
                orderFormData.value = res.result.records.map((item: any) => {
                    let obj = { label: item.title, value: item.id }
                    return obj
                })
            }
        })
    }

    const visible = ref(false)
    const addType = ref('')
    const open = (obj: { type: string, id: number, customerId?: string | number, orderFormId?: string | number }) => {
        addType.value == obj.type
        if(obj.type == 'edit') {
            getOrder(obj.id).then(res => {
                if(res.success) {
                    res.result.remindUserIds = typeof(res.result.remindUserIds) == 'string' ? res.result.remindUserIds.split(",") : ''
                    res.result.workOrderCategoryId = String(res.result.workOrderCategoryId)
                    res.result.urgentStatus = String(res.result.urgentStatus)
                    nextTick(() => {
                        Object.assign(form.value, res.result)
                    })
                }
            })
        }
        if(obj.customerId) {
            form.value.customerId = obj.customerId
            getOrderFormData()
        }
        if(obj.orderFormId) {
            form.value.orderFormId = obj.orderFormId
        }
        visible.value = true
    }

    const custChange = () => {
        form.value.orderFormId = ""
        getOrderFormData()
    }

    const initFormData: OrderForm = {
        id: undefined,
        customerId: undefined,
        orderFormId: undefined,
        title: undefined,
        expectTime: undefined,
        actualTime: undefined,
        remindUserIds: undefined,
        currentUserId: undefined,
        currentUserName: undefined,
        workOrderCategoryId: undefined,
        urgentStatus: undefined,
        orderStatus: undefined,
        orderCount: undefined,
        remark: undefined,
        commitTime: undefined,
        revokeTime: undefined,
        orderFrom: undefined,
        orderAgain: undefined,
        isDelete: undefined,
        enabled: undefined,
        ownerBy: undefined,
        sort: undefined,
        resourceIdList: undefined
    }
    const data = reactive<PageData<OrderForm, OrderQuery>>({
        form: { ...initFormData },
        rules: {
            customerId: [
                { required: true, message: "关联客户不能为空", trigger: "change" }
            ],
            workOrderCategoryId: [
                { required: true, message: "工单类型不能为空", trigger: "change" }
            ],
            title: [
                { required: true, message: "工单标题不能为空", trigger: "blur" }
            ],
            content: [
                { required: true, message: "工单内容不能为空", trigger: "blur" }
            ],
            urgentStatus: [
                { required: true, message: "紧急状态不能为空", trigger: "blur" }
            ],
            ownerBy: [
                { required: true, message: "处理人员不能为空", trigger: "blur" }
            ],
            remindUserIds: [
                { type: 'array', required: true, message: "通知人员不能为空", trigger: "blur" }
            ]
        }
    });

    const { form, rules } = toRefs(data);

    /** 取消按钮 */
    const cancel = () => {
        reset();
        visible.value = false;
    }

    /** 表单重置 */
    const reset = () => {
        form.value = { ...initFormData };
        orderFormRef.value?.resetFields();
    }

    /** 提交按钮 */
    const submitForm = () => {
        orderFormRef.value?.validate(async (valid: boolean) => {
            if (valid) {
                let params = JSON.parse(JSON.stringify(form.value))
                params.remindUserIds = params.remindUserIds?.join(",")
            	buttonLoading.value = true;
                await addOrder(params).finally(() => buttonLoading.value = false);
            	ElMessage.success((addType.value == 'add' ? '新增' : '编辑') + "成功");
                reset()
                visible.value = false
                emits('refresh')
            }
        });
    }

    onBeforeMount(() => {
        getOrderFormData()
    })

    defineExpose({
        open
    })
</script>

<style lang="scss" scoped>
    .form-item{
        :deep(.el-form-item__content){
            flex-direction: column;
            align-items: flex-start;
            .el-row{
                width: 100%;
            }
        }
    }
</style>
