<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">
                <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-card class="mb-2">
                    <div class="tit">客户基本资料</div>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="客户姓名" prop="name" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                                <el-input v-model="formData.name" placeholder="请输入本文行单客户姓名" clearable :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="客户属性" prop="custom_type">
                                <el-select class="flex-1" v-model="formData.custom_type" clearable placeholder="请选择客户属性">
                                    <el-option v-for="(item, index) in dictData.custom_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="parent_company">
                                <el-input v-model="formData.parent_company" type="number" placeholder="请输入上级公司" clearable :style="{ width: '100%' }">
                                    <template #append>
                                        <el-button>选择</el-button>
                                    </template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="电话" prop="phone" :rules="[{ validator: checkPhone, trigger: 'blur' }]">
                                <el-input v-model="formData.phone" placeholder="请输入电话" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16">
                            <el-form-item label="信用度" prop="credit_rating">
                                <el-radio-group v-model="formData.credit_rating" placeholder="请选择信用度">
                                    <el-radio v-for="(item, index) in dictData.credit_rating" :key="index" :label="parseInt(item.value)">
                                        {{ item.name }}
                                    </el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="省" prop="province" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                                <el-select v-model="formData.province" clearable placeholder="请选择省" @change="province_change">
                                    <el-option v-for="(item, index) in datas.provinceOptions" :key="index" :label="item.province_name" :value="parseInt(item.province_code)" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="市" prop="city" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                                <el-select v-model="formData.city" clearable placeholder="请选择市" @change="city_change">
                                    <el-option v-for="(item, index) in datas.cityOptions" :key="index" :label="item.city_name" :value="parseInt(item.city_code)" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="区" prop="area" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                                <el-select v-model="formData.area" clearable placeholder="请选择区" @change="area_change">
                                    <el-option v-for="(item, index) in datas.areaOptions" :key="index" :label="item.area_name" :value="parseInt(item.area_code)" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="地址" prop="address">
                                <el-input v-model="formData.address" clearable placeholder="请输入地址" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="备注" prop="notes">
                                <el-input v-model="formData.notes" type="textarea" placeholder="请输入备注" :autosize="{ minRows: 4, maxRows: 4 }" :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>


                <el-card class="mb-2">
                    <div class="tit">主要负责人</div>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="姓名" prop="master_name" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                                <el-input v-model="formData.master_name" placeholder="请输入姓名" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="职位" prop="master_position">
                                <el-input v-model="formData.master_position" placeholder="请输入职位" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="手机" prop="master_phone" :rules="[{ validator: checkPhone, trigger: 'blur' }]">
                                <el-input v-model="formData.master_phone" placeholder="请输入手机" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="邮箱" prop="master_email" :rules="[{ validator: userEmail, trigger: 'blur' }]">
                                <el-input v-model="formData.master_email" placeholder="请输入邮箱" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="电话" prop="master_telephone">
                                <el-input v-model="formData.master_telephone" placeholder="请输入电话" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="备注" prop="master_notes">
                                <el-input v-model="formData.master_notes" placeholder="请输入备注" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
                <el-card class="mb-2">
                    <div class="tit">其他联系人</div>
                    <el-row>
                        <template v-for="(item, index) in formData.other_contacts" :key="index">
                            <el-col :span="12">
                                <el-form-item label="姓名" prop="field120">
                                    <el-input :disabled="isDisabled" v-model="item.name" placeholder="请输入姓名" clearable :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="职务" prop="field121">
                                    <el-input :disabled="isDisabled" v-model="item.position" placeholder="请输入职务" clearable :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="手机" prop="field122" :rules="[{ validator: checkPhone, trigger: 'blur' }]">
                                    <el-input :disabled="isDisabled" v-model="item.phone" placeholder="请输入手机" clearable :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="邮箱" :rules="[{ validator: userEmail, trigger: 'blur' }]">
                                    <el-input :disabled="isDisabled" v-model="item.email" placeholder="请输入邮箱" clearable :style="{ width: '100%' }"></el-input>
                                </el-form-item>
                            </el-col>
                        </template>

                        <el-col :span="24">
                            <el-form-item label prop="field126">
                                <el-button type="primary" :disabled="isDisabled" size="medium" @click="other">添加联系人</el-button>
                                <el-button v-if="formData.other_contacts.length" type="primary" :disabled="isDisabled" size="medium" @click="otherdelete">删除</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>

                </el-card>
                <el-card class="mb-2">
                    <div class="tit">开票信息</div>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="开票公司" prop="company_name">
                                <el-input v-model="formData.company_name" placeholder="请输入开票公司" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="纳税人识别" prop="company_tin">
                                <el-input v-model="formData.company_tin" placeholder="请输入纳税人识别" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="开户地址" prop="bank_open_address">
                                <el-input v-model="formData.bank_open_address" placeholder="请输入开户地址" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="公司电话" prop="company_telephone">
                                <el-input v-model="formData.company_telephone" placeholder="请输入公司电话" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="开户银行" prop="bank_name">
                                <el-input v-model="formData.bank_name" placeholder="请输入开户银行" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="银行账号" prop="bank_account">
                                <el-input v-model="formData.bank_account" placeholder="请输入银行账号" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </el-form>
        </popup>
        <el-dialog v-model="showDialog" title="选择客户" width="70%">
            <customDialog @customEvent="customEvent"></customDialog>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="customEdit">
import {
    apiCityList,
    apiAreaList,
    apiProvinceList,
} from "@/api/common";
import customDialog from '@/components/custom-dialog/index.vue'
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiCustomAdd, apiCustomEdit, apiCustomDetail } from '@/api/custom'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
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 list1 = reactive([])
const showDialog = ref(false);
const list2 = reactive([])
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
const datas = reactive({
    provinceOptions: [],
    cityOptions: [],
    areaOptions: [],
});

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 checkPhone = (rule: any, value: any, callback: (arg0: Error) => any) => {
    const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
    // if (!value) {
    //     return callback(new Error('电话号码不能为空'))
    // }
    // setTimeout(() => {
    //     if (phoneReg.test(value)) {
    //         callback()
    //     } else {
    //         callback(new Error('电话号码格式不正确'))
    //     }

    // }, 100)

    if (value && phoneReg.test(value)) {
        return 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) {
    //     return callback(new Error('邮箱不能为空'))
    // }
    // setTimeout(() => {
    //     if (mailReg.test(value)) {
    //         callback()
    //     } else {
    //         callback(new Error('请输入正确的邮箱格式'))
    //     }
    // }, 100)
    if (value && mailReg.test(value)) {
        return callback(new Error('请输入正确的邮箱格式'))
    } else {
        callback()
    }
};
//获取所有组织
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: '',
    name: '',
    custom_type: '',
    parent_company: 5565665,
    phone: '',
    credit_rating: '',
    province: '',
    city: '',
    street: '',
    address: '',
    notes: '',
    master_name: '',
    master_position: '',
    master_phone: '',
    master_email: '',
    master_telephone: '',
    master_notes: '',
    company_name: '',
    company_tin: '',
    bank_open_address: '',
    company_telephone: '',
    bank_name: '',
    bank_account: '',
    status: '',
    other_contacts: [],
    area: ""

})


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

})


// 获取详情
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]

            if (key == 'province') {
                await getCityList()
            }
            if (key == 'city') {
                await getAreaList()
            }

        }

    }
    if (data.dept_id) {
        getlist1(data.dept_id)
    }
    formData.other_contacts = JSON.parse(data.other_contacts)

    console.log(formData, '2222222222')


}

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


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiCustomEdit(data)
        : await apiCustomAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

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


//获取省份
function province_change(value: string) {
    getCityList();
}
function city_change(value: string) {
    getAreaList();
}

// function brigade_change(value: string) {
//     formData.brigade = value
// }
const getProvinceList = async () => {
    const data = await apiProvinceList({});
    datas["provinceOptions"] = data;
};
const getCityList = async () => {
    const data = await apiCityList({ province_code: formData.province });
    datas["cityOptions"] = data;
};
const getAreaList = async () => {
    const data = await apiAreaList({ city_code: formData.city });
    datas["areaOptions"] = data;

};
//增加其他联系人
function other() {
    formData.other_contacts.push({
        name: "",
        position: "",
        phone: "",
        email: "",
    });
}
//删除其他联系人
function otherdelete() {
    formData.other_contacts.pop({
        name: "",
        position: "",
        phone: "",
        email: "",
    });
}

getProvinceList();


defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
<style lang="scss">
.tit {
    font-size: 1.2em;
    margin-bottom: 10px;
}
</style>
