<template>
    <div class="w-[100%] space-y-6">
        <div class="bg-white rounded-lg p-6 shadow-sm">
            <!-- <h2 class="text-xl font-medium mb-6">工单信息</h2> -->
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="客户姓名" required prop="name">
                            <el-input v-model="form.name" placeholder="请输入客户姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" required prop="phone">
                            <el-input v-model="form.phone" placeholder="请输入联系电话" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="工单类型" required prop="type">
                    <el-cascader ref="typeCascaderRef" class="w-full" v-model="form.type" :props="{ value: 'id', }"
                        placeholder="请选择工单类型" :options="ticketTypes" filterable clearable @change="handleTypeChange" />
                </el-form-item>
                <el-form-item v-if="form.typeCode === 'complain'" label="投诉部门" required prop="department">
                    <el-cascader ref="deptCascaderRef" class="w-full" v-model="form.department"
                        :props="{ checkStrictly: true }" placeholder="请选择投诉科室" :options="departments" filterable
                        @change="deptChange" />
                </el-form-item>
                <el-form-item label="问题描述" required prop="description">
                    <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请详细描述问题" />
                </el-form-item>
                <el-form-item label="处理方式" required prop="handleMethod">
                    <el-select v-model="form.handleMethod" placeholder="请选择处理方式" class="w-full" :disabled="props.getDefaultInfo.workorderId">
                        <el-option v-for="item in handleMethods" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <!-- 悬浮提交按钮 -->
                <div class="bottom-0 left-0 right-0 p-4 bg-white border-t flex justify-end">
                    <el-button type="primary" class="w-32 !rounded-button whitespace-nowrap"
                        @click="submit">提交工单</el-button>
                </div>
            </el-form>

        </div>

    </div>
</template>

<script lang="ts" setup>
import { shallowRef, reactive, ref, onMounted, watch } from 'vue'
import consult from './src/form/consult';
import complain from './src/form/complain';
import transport from './src/form/transport';
import useSelectStore from '@/store/commonSelect/common';
import { ElMessage } from 'element-plus';
import { getPageListData, editPageData, createPageData } from '@/api/main/system/system';
import { getUnprefixNuber} from '@/utils/index';

const formRef: any = ref(null);
let form = ref({
    id: 0,
    name: '',
    phone: '',
    type: [],
    typeCode: '',
    description: '',
    handleMethod: '1',
    department: '',
});

const props = defineProps({
    getDefaultInfo: {
        type: Object,
        default: () => ({}),
    },
    propRecordData: {
        type: Object,
        default: () => ({}),
    }
});
watch(props, (nweProps) => {
    initMethod(props);
});

onMounted(() => {
    initMethod(props);
});

const initMethod = (props) => {
    if (props.getDefaultInfo.workorderId) {
        form.value = {
            id: props.getDefaultInfo.workorderId,
            name: props.getDefaultInfo.caller || '',
            phone: props.getDefaultInfo.callnum || '',
            type: props.getDefaultInfo.workordercate,
            typeCode: '',
            description: props.getDefaultInfo.content,
            handleMethod: props.getDefaultInfo.isend.toString(),
            department: '',
        }
    }
    console.log(props.propRecordData)
    if (props.propRecordData.id) {
        form.value = {
            callId: props.propRecordData.id,
            phone: getUnprefixNuber(props.propRecordData.phone),
            handleMethod:'1'
        }
    }
}

const emit = defineEmits(["refreshOrder", "orderTypeChange"]);


const rules = {
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择工单类型', trigger: 'change' }
    ],
    description: [
        { required: true, message: '请输入问题描述', trigger: 'blur' },
        { min: 5, max: 100, message: '问题描述5-100个字符', trigger: 'blur' },
    ],
    handleMethod: [
        { required: true, message: '请选择处理方式', trigger: 'change' }
    ],
};

const ticketTypes = useSelectStore().dictOrderTypeList;
const departments = useSelectStore().deptListData;
const handleMethods = [
    { label: '立即完结', value: '1' },
    { label: '待交办', value: '0' },
];

const typeCascaderRef: any = ref(null);

const handleTypeChange = (value) => {
    if (typeCascaderRef.value) {
        const selectNode = typeCascaderRef.value.getCheckedNodes();
        form.value.typeCode = selectNode[selectNode.length - 1].data.code;
    }
}

// 投诉部门切换
const deptCascaderRef: any = ref(null);
const deptChange = (value) => {
    // if (deptCascaderRef.value) {
    //     const selectNode = deptCascaderRef.value.getCheckedNodes()[0];
    //     form.value.department = selectNode.data.label;
    // }
}

const submit = async () => {
    console.log(form.value, 'submit');
    // 验证表单必填项
    formRef.value.validate(async (valid) => {
        if (valid) {
            const params: any = {
                caller: form.value.name,
                callnum: form.value.phone,
                content: form.value.description,
                customerno: form.value.phone,
                firsttype: 1000,
                isend: +form.value.handleMethod,
                workordercate: form.value.type[form.value.type.length - 1],
            };
            if (form.value.callId) {
                params.callId = form.value.callId
            }
            // 提交表单
            if (form.value.id) {
                params.workorderId = form.value.id;
                editPageData('/order/workorder', params).then((data) => {
                    console.log(data, 'submit');
                    if (data.state === 'success') {
                        ElMessage.success('提交成功');
                        // resetForm()
                        emit("refreshOrder");
                    } else {
                        ElMessage.error(data.message || '提交失败');
                    }

                })
            } else {
                createPageData('/order/workorder', params).then((data) => {
                    console.log(data, 'submit');
                    if (data.state === 'success') {
                        ElMessage.success('提交成功');
                        // resetForm()
                        emit("refreshOrder");
                    } else {
                        ElMessage.error(data.message || '提交失败');
                    }

                })
            }


        } else {
            ElMessage.error('请填写完整信息');
        }

    });
}

</script>


<style lang="scss" scoped>
.order-main {
    width: 100%;
}

.order-layout {
    display: flex;
    margin-top: 10px;
}
</style>