<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="80%" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="auto" :rules="formRules">
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="项目名称" prop="project_id" @click="showDialog = true">
                            <el-input v-model="project_name" readonly clearable placeholder="请选择项目" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目编码" prop="project_id">
                            <el-input v-model="project_code" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="客户名称" prop="custom_name"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.custom_name" readonly clearable placeholder="系统自动填写" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="合同号" prop="contract_id" @click="showDialog2 = true">
                            <el-input v-model="formData.contract_code" clearable readonly placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系人" prop="custom_master_name">
                            <el-input v-model="formData.custom_master_name" disabled clearable placeholder="请输入联系人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">

                        <el-form-item label="联系电话" prop="custom_master_phone"
                            :rules="[{ validator: checkPhone, trigger: 'blur' }]">
                            <el-input v-model="formData.custom_master_phone" disabled clearable placeholder="请输入联系电话" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="日期" prop="date"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-date-picker class="flex-1 !flex" v-model="formData.date" clearable
                                value-format="YYYY-MM-DD " placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="分类" prop="classification"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-select class="flex-1" v-model="formData.classification" clearable placeholder="请选择分类">
                                <el-option v-for="(item, index) in dictData.classification" :key="index" :label="item.name"
                                    :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="紧急程度" prop="urgency"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-radio-group v-model="formData.urgency" placeholder="请选择紧急程度">
                                <el-radio v-for="(item, index) in dictData.urgency" :key="index"
                                    :label="parseInt(item.value)">
                                    {{ item.name }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="接待人" prop="receiver"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.receiver" clearable placeholder="请输入接待人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="指定处理人" prop="processed_user" @click="userclick"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="processed_admin_name" clearable readonly placeholder="请输入指定处理人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="投诉主题" prop="name"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.name" clearable placeholder="请输入投诉主题" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="问题描述" prop="description">
                            <el-input v-model="formData.description" clearable placeholder="请输入问题描述" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="备注" prop="notes">
                            <el-input v-model="formData.notes" clearable placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="附件" prop="field127">
                            <annexUpload :annex="formData.annex" @handleAvatarSuccess="handleAvatarSuccess_four"
                                @delFile="delFileFn" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <!-- <reviewprocess :list="list" /> -->
        </popup>

        <el-dialog v-model="showDialog" title="选择项目" width="70%">
            <peojectDialog @customEvent="customEvent"></peojectDialog>
        </el-dialog>
        <div v-if="showDialog1">
            <el-dialog v-model="showDialog1" title="选择客户" width="70%">
                <customDialog @customEvent="customEvent1"></customDialog>
            </el-dialog>
        </div>
        <div v-if="showDialog2">
            <el-dialog v-model="showDialog2" title="选择项目合同" width="70%">
                <salescontractDialog @customEvent="customEvent2" :project_id="formData.project_id">
                </salescontractDialog>
            </el-dialog>
        </div>

        <personnelselector ref="personnel" @confirm="submituser" type="1"></personnelselector>
    </div>
</template>

<script lang="ts" setup name="customServiceEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import customDialog from '@/components/custom-dialog/index.vue'
import salescontractDialog from '@/components/salescontract/index.vue'
import { apiCustomServiceAdd, apiCustomServiceDetail } from '@/api/custom_service'
import personnelselector from '@/components/personnelselector/index.vue'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import useUserStore from "@/stores/modules/user";
import configs from "@/config"
const list1 = reactive([])
const list2 = reactive([])
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import reviewprocess from '@/components/reviewprocess/index.vue'
import costDialog from '@/components/budget/index.vue'
import peojectDialog from '@/components/project/index.vue'


// 上传文件
import annexUpload from "@/components/annexUpload/index.vue"
const handleAvatarSuccess_four = (response: any) => {
    // @ts-ignore
    response.code != 0 ? formData.annex.push({ uri: response.data.uri, name: response.data.name }) : ElMessage.error(response.msg);
};
// 删除上传的文件
const delFileFn = (index: number) => { formData.annex.splice(index, 1) }
// <annexUpload :annex="formData.annex" @handleAvatarSuccess="handleAvatarSuccess_four"
//                                 @delFile="delFileFn" />

const list = reactive([])
const showDialog = ref(false)
const showDialog1 = ref(false)
const showDialog2 = ref(false)
const custom_name = ref('')
const project_name = ref('')
const project_code = ref('')
const contract_id = ref('')
const processed_admin_name = ref('')
const personnel = ref<any>()
const formDataannex = reactive([])

const customEvent = (e: any) => {
    formData.project_id = e.id
    formData.custom_name = e.custom_name
    formData.custom_master_phone = e.custom_master_phone
    formData.custom_master_name = e.custom_master_name
    project_name.value = e.name
    project_code.value = e.project_code
    showDialog.value = false;
};

const customEvent1 = (e: any) => {
    formData.custom_id = e.id
    formData.custom_name = e.name
    showDialog1.value = false;
};

const customEvent2 = (e: any) => {
    formData.contract_id = e.id
    formData.contract_code = e.contract_code
    showDialog2.value = false;
};

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')

//打开弹窗

const userclick = () => {
    personnel.value.open()

}
//确认
const submituser = (e: any) => {
    formData.processed_user = e.id;
    processed_admin_name.value = e.name;
}
//验证
const checkPhone = (rule: any, value: any, callback: (arg0: Error) => any) => {

    if (value && !/^1\d{10}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
    } else {
        callback()
    }

}
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑客户售后' : '新增客户售后'
})
//获取所有组织
const getlist = () => {
    getAll().then((res) => {
        Object.assign(list1, res)
        if (res.length > 0 && !formData.org_id) {
            formData.org_id = res[0].id
            deptAll({ 'org_id': res[0].id }).then((res) => {
                if (res.length > 0) {
                    Object.assign(list2, res)
                    formData.dept_id = res[0].id
                }

            })
        }
    })
}
//获取部门
const deptrmt = (e: any) => {
    formData.dept_id = ''
    getlist1(e)

}
//获取所有部门
const getlist1 = (id: any) => {
    deptAll({ 'org_id': id }).then((res) => {
        list2.splice(0, list2.length, ...res)
    })
}
// 表单数据
const formData = reactive({
    id: '',
    project_id: '',
    contacts: '',
    custom_master_name: "",
    custom_master_phone: "",
    phone: '',
    date: '',
    classification: '',
    urgency: '',
    receiver: '',
    processed_user: '',
    name: '',
    description: '',
    notes: '',
    annex: [],
    status: '',
    contract_code: "",
    contract_id: "",
    custom_name: "",
    custom_id: ""
})


// 表单验证
const formRules = reactive<any>({

})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    custom_name.value = data.custom.name
    project_name.value = data.project.name
    if (data.annex && data.annex.length > 0) {
        const arry1 = data.annex.map((item: any, index: any) => {
            return {
                name: `文件${index + 1}`,
                uri: item
            };
        });
        Object.assign(formDataannex, arry1)
    }
    if (data.dept_id) {
        getlist1(data.org_id)
    }
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }

    //@ts-ignore
    formData.date = timeFormat(formData.date, 'YYYY-MM-DD ')
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiCustomServiceDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item) => item.uri)
    }
    await formRef.value?.validate()
    const data = { ...formData, }
    data.date = data.date.substring(0, 10)
    await apiCustomServiceAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
    getlist()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}



defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
