<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"
                                :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                                <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="companyname" placeholder="请输入上级公司" @click="showDialog = true"
                                    @change="companyname.length == 0 ? formData.parent_company = '' : ''" clearable
                                    :style="{ width: '100%' }">
                                    <template #append>
                                        <el-button @click="showDialog = true">选择</el-button>
                                    </template>
                                </el-input>
                            </el-form-item> -->
                        <!-- </el-col> -->
                        <el-col :span="8">
                            <el-form-item label="电话" prop="phone"
                                :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                                <el-input v-model="formData.phone" placeholder="请输入电话" clearable :style="{ width: '100%' }">
                                </el-input>
                            </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="6">
                            <el-form-item label="地址" prop="address">
                                <el-input v-model="formData.address" clearable placeholder="请输入地址" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="信用度" prop="credit_rating"
                                :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                                <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="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" v-if="mode == 'add'">
                    <div class="tit">其他联系人</div>

                    <el-row>
                        <el-table :data="otherList">
                            <el-table-column label="序号">
                                <template #default="{ row }">
                                    <el-button @click="handleAdd(row)">+</el-button>
                                    <el-button @click="handleDelete(row)">-</el-button>
                                </template>
                            </el-table-column>

                            <el-table-column label="姓名" prop="name">
                                <template #default="{ row }">
                                    <el-input v-model="row.name" />
                                </template></el-table-column>
                            <el-table-column label="职位" prop="position">
                                <template #default="{ row }">
                                    <el-input v-model="row.position" />
                                </template></el-table-column>
                            <el-table-column label="手机" prop="phone">
                                <template #default="{ row, $index }">

                                    <el-input v-model="row.phone" @blur="tablePhone(row, $index)" />

                                </template></el-table-column>

                            <el-table-column label="邮箱" prop="email">
                                <template #default="{ row, $index }">
                                    <el-input v-model="row.email" @blur="tableEmail(row, $index)" />
                                </template></el-table-column>

                            <el-table-column label="电话" prop="telephone">
                                <template #default="{ row }">
                                    <el-input v-model="row.telephone" /> </template>
                            </el-table-column>

                            <el-table-column label="备注" prop="notes">
                                <template #default="{ row }">
                                    <el-input v-model="row.notes" /> </template>
                            </el-table-column>
                            <el-table-column label="附件" prop="annex">
                                <template #default="{ row, $index }">
                                    <!-- <el-input v-model="row.annex" /> -->
                                    <div>
                                        <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="(response, file, fileList) => { return handleAvatarSuccess_four1($index, response, file, fileList) }"
                                            ref="upload">
                                            <el-button type="primary">
                                                上传
                                            </el-button>
                                        </el-upload>
                                        <div v-if="row.annex">
                                            <div v-for="(item, index) in row.annex"
                                                style="margin-left: 5px;display: block;">

                                                <a style="margin-left: 10px; color: #4a5dff; align-self: flex-start"
                                                    :href="item" target="_blank">文件{{ index + 1 }}</a>
                                                <span style="cursor: pointer;margin-left: 5px;"
                                                    @click="delFileFn1(row, index)">x</span>
                                            </div>
                                        </div>
                                    </div>

                                </template>
                            </el-table-column>



                        </el-table>
                        <!-- <template v-for="(item, index) inotherList" :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="otherList.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'
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import feedback from "@/utils/feedback";
import configs from "@/config"
import useUserStore from "@/stores/modules/user";
const userStore = useUserStore();
const base_url = configs.baseUrl + configs.urlPrefix


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 companyname = ref('')
const list1 = reactive([])
const showDialog = ref(false);
const list2 = reactive([])
const otherList = reactive([{}])
const datas = reactive({
    provinceOptions: [],
    cityOptions: [],
    areaOptions: [],
});

// const customEvent = (e: any) => {
//     formData.parent_company = e.id;
//     companyname.value = e.name;
//     showDialog.value = false;
// };

const handleAdd = (row: any) => {
    // 在 row 后面插入一行数据
    const index = otherList.indexOf(row);
    otherList.splice(index + 1, 0, {});
};

const handleDelete = (row: any) => {
    // 删除 row
    const index = otherList.indexOf(row);
    otherList.splice(index, 1);
};
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑客户表' : '新增客户表'
})
//验证
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 tablePhone = (row, index) => {
    console.log(row, index)
    if (row.phone && !/^1[3|4|5|7|8][0-9]{9}$/.test(row.phone)) {
        feedback.msgError('请输入正确的手机号码')
        row.phone = ''
    }
}
const tableEmail = (row, index) => {
    const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
    if (row.email && !mailReg.test(row.email)) {
        feedback.msgError('请输入正确的手机号码')
        row.email = ''
    }



    // console.log(row, index)
}
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 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: '',
    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 handleAvatarSuccess_four1 = (index, response, file, fileList) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    if (!otherList[index].annex) {
        otherList[index].annex = [];  // 如果 annex 不存在，先创建一个空数组
    }
    // console.log(otherList[index], index, tablist2)
    // console.log(index, response)
    otherList[index].annex.push({ uri: response.data.uri, name: response.data.name });




    // console.log(response.data.uri, index, tablist2)
    // formDataannex1.push(
    //     { uri: response.data.uri, name: response.data.name }
    // );
};

// 删除上传的文件
const delFileFn1 = (index: number) => {
    // 删除附件文件
    row.annex.splice(index, 1);
}
// 获取详情
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.org_id)
    }

    if (formData.company_name) {
        companyname.value = data.company_name

    }





}

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


// 提交按钮
const handleSubmit = async () => {
    console.log()
    if (mode.value == 'add' && otherList.length > 0 && Object.keys(otherList[0]).length > 0) {
        formData.other_contacts = otherList
    }

    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;

};


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

:deep(.my-label) {
    width: 150px;
}
</style>
