<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="90px" :rules="formRules">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="客户名称" prop="custom_name" @click="showDialog = true">
                            <el-input v-model="formData.custom_name" readonly clearable placeholder="请选择客户" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="formData.name" clearable placeholder="请输入姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="职位" prop="position">
                            <el-input v-model="formData.position" 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="telephone">
                            <el-input v-model="formData.telephone" clearable placeholder="请输入电话" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <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="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="annex">
                            <material-picker v-model="formData.annex" type="file" />
                        </el-form-item> -->
                        <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 formData.annex" 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-dialog v-model="showDialog" title="选择客户" width="70%">
                    <customDialog @customEvent="customEvent"></customDialog>
                </el-dialog>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="customContactsEdit">
import { usePaging } from '@/hooks/usePaging'
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import customDialog from '@/components/custom-dialog/index.vue'
import { apiCustomContactsAdd, apiCustomContactsEdit, apiCustomContactsDetail } from '@/api/custom_contacts'
import { apiCustomLists } from '@/api/custom'
import useUserStore from "@/stores/modules/user";
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import configs from "@/config"
console.log(configs, 55)
const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
// 上传文件
const handleAvatarSuccess_four = (
    response: any
) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    formData.annex.push(
        { uri: response.data.uri, name: response.data.name }


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

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

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

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑客户联系人' : '新增客户联系人'
})


const popTableList = reactive([])
// 分页相关
const { pager, getLists, resetParams, resetPage } = usePaging({
    fetchFun: apiCustomLists,
})
getLists()
// 表单数据
const formData = reactive({
    id: '',
    custom_id: '',
    custom_name: '',
    name: '',
    position: '',
    phone: '',
    telephone: '',
    email: '',
    notes: '',
    annex: [],
    status: '',
})


// 表单验证
const formRules = reactive<any>({
    custom_name: [{
        required: true,
        message: '请输入',
        trigger: ['change']
    }]
})


// 获取详情
const setFormData = async (data: Record<any, any>) => {


    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 apiCustomContactsDetail({
        id: row.id
    })
    setFormData(data)
}
//验证
const checkPhone = (rule: any, value: any, callback: (arg0: Error) => any) => {

    if (value && !/^1[3|4|5|7|8][0-9]{9}$/.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)) {
        return callback(new Error('请输入正确的邮箱格式'))
    } else {
        callback()
    }
};
// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiCustomContactsEdit(data)
        : await apiCustomContactsAdd(data)
    popupRef.value?.close()
    emit('success')
}

// 选择客户
const handleCurrentChange = (e: any) => {
    formData.custom_name = e.name
    formData.custom_id = e.id
    console.log(e)

    showDialog.value = false
}

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

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



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