<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="120px" :rules="formRules">


                <el-row>

                    <el-col :span="8">
                        <el-form-item label="供应商" prop="supplier_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]" @click="showDialog = true">
                            <el-input v-model="supplier_name" readonly clearable placeholder="选择供应商" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <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="8">
                        <el-form-item label="性别" prop="sex">
                            <el-select v-model="formData.sex" clearable placeholder="请选择性别" class="flex-1">
                                <el-option v-for="(item, index) in dictData.sex" :key="index" :label="item.name"
                                    :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item></el-col>
                    <el-col :span="8">
                        <el-form-item label="出生日期" prop="birthday">
                            <el-date-picker v-model="formData.birthday" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                                placeholder="请输入出生日期" clearable class="flex-1 !flex"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系人分类" prop="contacts_type">
                            <el-select class="flex-1" v-model="formData.contacts_type" clearable placeholder="请选择联系人分类">
                                <el-option v-for="(item, index) in dictData.contacts_type" :key="index" :label="item.name"
                                    :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="负责业务" prop="responsible">
                            <el-input v-model="formData.responsible" clearable placeholder="请输入负责业务" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="称谓" prop="title">
                            <el-input v-model="formData.title" clearable placeholder="请输入称谓" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="联系人类型" prop="contacts_cate">
                            <el-select class="flex-1" v-model="formData.contacts_cate" clearable placeholder="请选择联系人类型">
                                <el-option v-for="(item, index) in dictData.contacts_cate" :key="index" :label="item.name"
                                    :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="部门" prop="department">
                            <el-input v-model="formData.department" clearable placeholder="请输入部门" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="职务" prop="duties">
                            <el-input v-model="formData.duties" clearable placeholder="请输入职务" />
                        </el-form-item>
                    </el-col>


                    <el-col :span="8">
                        <el-form-item label="工作电话" prop="work_phone" :rules="[{ validator: checkPhone, trigger: 'blur' }]">
                            <el-input v-model="formData.work_phone" clearable placeholder="请输入工作电话" />
                        </el-form-item></el-col>
                    <el-col :span="8">
                        <el-form-item label="移动电话" prop="mobile">
                            <el-input v-model="formData.mobile" clearable placeholder="请输入移动电话" />
                        </el-form-item></el-col>

                    <el-col :span="8">
                        <el-form-item label="邮件地址" prop="email" :rules="[{ validator: userEmail, trigger: 'blur' }]">
                            <el-input v-model="formData.email" clearable placeholder="请输入邮件地址" />
                        </el-form-item></el-col>

                    <el-col :span="8">
                        <el-form-item label="传真" prop="fax">
                            <el-input v-model="formData.fax" clearable placeholder="请输入传真" />
                        </el-form-item></el-col>

                    <el-col :span="8">
                        <el-form-item label="邮编" prop="zip_code">
                            <el-input v-model="formData.zip_code" clearable placeholder="请输入邮编" />
                        </el-form-item></el-col>

                    <el-col :span="8">
                        <el-form-item label="家庭住址" prop="family_address">
                            <el-input v-model="formData.family_address" clearable placeholder="请输入家庭住址" />
                        </el-form-item></el-col>


                    <el-col :span="8">
                        <el-form-item label="证件类型" prop="id_type">
                            <el-select class="flex-1" v-model="formData.id_type" clearable placeholder="请选择证件类型">
                                <el-option v-for="(item, index) in dictData.id_type" :key="index" :label="item.name"
                                    :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="证件号码" prop="idcard" :rules="[{ validator: IDcard, trigger: 'blur' }]">
                            <el-input v-model="formData.idcard" clearable placeholder="请输入证件号码" />
                        </el-form-item></el-col>
                    <el-col :span="8">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" clearable placeholder="请输入备注" />
                        </el-form-item></el-col>
                    <el-col :span="24">
                        <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>

        </popup>
        <el-dialog v-model="showDialog" title="选择供应商" width="70%">
            <supplierTable @customEvent="customEvent"></supplierTable>

        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="bidBiddingDecisionEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'

import supplierTable from "@/components/supplier/index.vue"

import { suppliercontactsAdd, suppliercontactsEdit, suppliercontactsDetail } from '@/api/suppler_contact'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const supplier_name = ref('')
const supplier_code = ref('')
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const showDialog = ref(false)

import configs from "@/config"
const base_url = configs.baseUrl + configs.urlPrefix
import useUserStore from "@/stores/modules/user";
const userStore = useUserStore();
const formDataannex = reactive([])
// 上传文件
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)
}
//获取值
const customEvent = (e: any) => {
    formData.supplier_id = e.id;
    supplier_name.value = e.supplier_name
    supplier_code.value = e.supplier_code
    showDialog.value = false;
};
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑供应商联系人表' : '新增供应商联系人表'
})



// 表单数据
const formData = reactive({
    id: '',
    supplier_id: '',
    name: "",
    sex: '',
    birthday: "",
    contacts_type: '',
    responsible: "",
    title: "",
    contacts_cate: '',
    department: "",
    duties: "",
    work_phone: "",
    mobile: "",
    email: "",
    fax: "",
    zip_code: "",
    family_address: "",
    id_type: '',
    idcard: "",
    remark: "",
    annex: []
})


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

})
//验证
const checkPhone = (rule: any, value: any, callback: (arg0: Error) => any) => {

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

}
const userEmail = (rule: any, value: string, callback: (arg0: Error | undefined) => void) => {
    const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
    if (value && !mailReg.test(value)) {
        callback(new Error('请输入正确的邮箱格式'))
    } else {
        callback()
    }

};
const IDcard = (rule: any, value: string, callback: (arg0: Error | undefined) => void) => {
    const cardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    if (value && !cardReg.test(value)) {
        callback(new Error('请输入正确的身份证号码'))
    } else {
        callback()
    }

};
// 获取详情
const setFormData = async (data: Record<any, any>) => {
    supplier_name.value = data.supplier_name
    supplier_code.value = data.supplier_code
    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)
    }

    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }


}

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


// 提交按钮
const handleSubmit = async () => {

    formData.annex = formDataannex.map((item: any) => item.uri)
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await suppliercontactsEdit(data)
        : await suppliercontactsAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

}

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



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