<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">
                <div style="display: flex; flex-direction: row-reverse; justify-content: flex-start;margin-bottom: 30px;">

                    <el-select class="w-[180px]" v-model="formData.dept_id" clearable placeholder="请选择部门">
                        <el-option v-for="(item, index) in list2" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
                    <el-select class="w-[180px]" v-model="formData.org_id" clearable placeholder="请选择组织" @change="deptrmt">
                        <el-option v-for="(item, index) in list1" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
                </div>

                <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="project_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="custom_name" disabled clearable placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="合同号" prop="contract_id" @click="showDialog2 = true">
                            <el-input v-model="contract_id" clearable readonly placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
                        <el-form-item label="审批id" prop="approve_id">
                            <el-input v-model="formData.approve_id" clearable placeholder="请输入审批id" />
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="12">

                        <el-form-item label="联系人" prop="contacts">
                            <el-input v-model="formData.contacts" clearable placeholder="请输入联系人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">

                        <el-form-item label="联系电话" prop="phone" :rules="[{ validator: checkPhone, trigger: 'blur' }]">
                            <el-input v-model="formData.phone" 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 type="datetime"
                                value-format="YYYY-MM-DD HH:mm:ss" 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_admin_id" @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">

                        <!-- <material-picker v-model="formData.annex" /> -->
                        <el-form-item label="附件" prop="field127">
                            <el-upload
                                accept="doc, docx, xls, xlsx, ppt, pptx, pdf, txt, zip, rar, tar, jpg, png, gif, jpeg, webp, wmv, avi, mpg, mpeg, 3gp, mov, mp4, flv, f4v, rmvb, mkv"
                                class="upload-demo" :show-file-list="false" aria-hidden="true"
                                :headers="{ Token: userStore.token }" :action="base_url + '/upload/file'"
                                :on-success="handleAvatarSuccess_four" ref="upload">
                                <el-button type="primary">
                                    上传
                                </el-button>
                            </el-upload>

                            <div>
                                <div v-for="(item, index) in formDataannex" style="margin-left: 5px;display: block;">
                                    <a style="margin-left: 10px; color: #4a5dff; align-self: flex-start" :href="item.uri"
                                        target="_blank">{{ item.name }}</a>
                                    <span style="cursor: pointer;margin-left: 5px;" @click="delFileFn(index)">x</span>
                                </div>
                            </div>



                        </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>
        <el-dialog v-model="showDialog1" title="选择客户" width="70%">
            <customDialog @customEvent="customEvent1"></customDialog>
        </el-dialog>
        <el-dialog v-model="showDialog2" title="选择销售合同" width="70%">
            <salescontractDialog @customEvent="customEvent2" contract_type="2"></salescontractDialog>
        </el-dialog>
        <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'
const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
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) => {
    // console.log(e)
    formData.project_id = e.id
    custom_name.value = e.name
    project_name.value = e.custom_name
    project_code.value = e.project_code
    showDialog.value = false;


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


};
const customEvent2 = (e: any) => {
    console.log(e)

    showDialog2.value = false;


};

// 上传文件
const handleAvatarSuccess_four = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    formDataannex.push(
        { uri: response.data.uri, name: response.data.name }

    );
};
// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}

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 = () => {
    // console.log(personnel.value, '1111111')
    personnel.value.open()

}
//确认
const submituser = (e: any) => {
    formData.processed_admin_id = 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: '',
    dept_id: '',
    org_id: '',
    project_id: '',
    contacts: '',
    phone: '',
    date: '',
    classification: '',
    urgency: '',
    receiver: '',
    processed_admin_id: '',
    name: '',
    description: '',
    notes: '',
    annex: [],
    status: '',
})


// 表单验证
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 hh:MM:ss')
}

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, }
    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>
