<template>
    <div class="edit-popup">
        <!-- <popup ref="popupRef" :title="popupTitle" :async="true" width="70%" @confirm="handleSubmit" @close="handleClose"> -->
        <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
            <div style="font-size: 1.2rem; margin: 10px 0">公司基本信息创建</div>
            <el-col :span="24" class="el-card pt-6">
                <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="organization_code">
                            <el-input
                                v-model="formData.organization_code"
                                placeholder="请输入社会代码"
                                clearable
                                :style="{ width: '100%' }"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="公司类型" prop="company_type">
                            <el-select
                                v-model="formData.company_type"
                                placeholder="请选择公司类型"
                                clearable
                                :style="{ width: '100%' }"
                            >
                                <el-option
                                    v-for="(item, index) in datas.dictTypeLists"
                                    :key="index"
                                    :label="item.name"
                                    :value="item.id"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="省" prop="province">
                            <el-select
                                v-model="formData.province"
                                placeholder="请选择省"
                                clearable
                                @change="province_change"
                                :style="{ width: '100%' }"
                            >
                                <el-option
                                    v-for="(item, index) in datas.provinceOptions"
                                    :key="index"
                                    :label="item.province_name"
                                    :value="item.province_code"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="市" prop="city">
                            <el-select
                                v-model="formData.city"
                                placeholder="请选择市"
                                clearable
                                @change="city_change"
                                :style="{ width: '100%' }"
                            >
                                <el-option
                                    v-for="(item, index) in datas.cityOptions"
                                    :key="index"
                                    :label="item.city_name"
                                    :value="item.city_code"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="区" prop="area">
                            <el-select
                                v-model="formData.area"
                                placeholder="请选择区"
                                clearable
                                @change="area_change"
                                :style="{ width: '100%' }"
                            >
                                <el-option
                                    v-for="(item, index) in datas.areaOptions"
                                    :key="index"
                                    :label="item.area_name"
                                    :value="item.area_code"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="镇" prop="street">
                            <el-select
                                v-model="formData.street"
                                placeholder="请选择镇"
                                clearable
                                @change="street_change"
                                :style="{ width: '100%' }"
                            >
                                <el-option
                                    v-for="(item, index) in datas.streetOptions"
                                    :key="index"
                                    :label="item.street_name"
                                    :value="item.street_code"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="地址" prop="address">
                            <el-input
                                v-model="formData.address"
                                placeholder="请输入地址"
                                clearable
                                :style="{ width: '100%' }"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-col>
            <div style="font-size: 1.2rem; margin: 10px 0">主要联系人</div>
            <el-col :span="24" class="el-card pt-6">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="master_name">
                            <el-input
                                v-model="formData.master_name"
                                placeholder="请输入姓名"
                                clearable
                                :style="{ width: '100%' }"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <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="12">
                        <el-form-item label="手机" prop="master_phone">
                            <el-input
                                v-model="formData.master_phone"
                                placeholder="请输入手机"
                                clearable
                                :style="{ width: '100%' }"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="master_email">
                            <el-input
                                v-model="formData.master_email"
                                placeholder="请输入邮箱"
                                clearable
                                :style="{ width: '100%' }"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-col>
            <div style="font-size: 1.2rem; margin: 10px 0">其他联系人</div>
            <el-col :span="24" class="el-card pt-6">
                <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
                                    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
                                    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">
                                <el-input
                                    v-model="item.phone"
                                    placeholder="请输入手机"
                                    clearable
                                    :style="{ width: '100%' }"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="邮箱" prop="field123">
                                <el-input
                                    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" size="medium" @click="other">
                                其他联系人
                            </el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-col>
            <div style="font-size: 1.2rem; margin: 10px 0">资质信息</div>
            <el-col :span="24" class="el-card pt-6">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="营业执照" required>
                            <el-upload
                                v-model="formData.qualification.business_license"
                                class="avatar-uploader"
                                :data="{ cid: 1 }"
                                action="https://worker-task.lihaink.cn/api/upload/image"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload"
                            >
                                <img
                                    v-if="formData.qualification.business_license"
                                    :src="formData.qualification.business_license"
                                    class="avatar"
                                />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="对公银行" required>
                            <el-upload
                                v-model="formData.qualification.bank_account"
                                class="avatar-uploader"
                                :data="{ cid: 1 }"
                                action="https://worker-task.lihaink.cn/api/upload/image"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess_two"
                                :before-upload="beforeAvatarUpload_two"
                            >
                                <img
                                    v-if="formData.qualification.bank_account"
                                    :src="formData.qualification.bank_account"
                                    class="avatar"
                                />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-col>
            <div style="font-size: 1.2rem; margin: 10px 0">电子合同</div>
            <el-col :span="24" class="el-card pt-6">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="签约方" prop="field130">
                            <el-input
                                v-model="formData.party_a_name"
                                placeholder="请选择签约方"
                                clearable
                                :style="{ width: '100%' }"
                                @click="openCompany"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label-width="100px" label="被签约公司" prop="field131">
                            <el-input
                                v-model="formData.company_name"
                                placeholder="请输入被签约公司"
                                clearable
                                :style="{ width: '100%' }"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label-width="100px" label="合同类型" prop="contract_type">
                            <el-select
                                v-model="formData.contract.contract_type"
                                placeholder="请选择合同类型"
                                clearable
                                :style="{ width: '100%' }"
                            >
                                <el-option
                                    v-for="(item, index) in datas.contract_type"
                                    :key="index"
                                    :label="item.name"
                                    :value="item.id"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label-width="100px" label="合同编号" prop="field133">
                            <el-input
                                placeholder="系统自动生成"
                                clearable
                                :style="{ width: '100%' }"
                                disabled="disabled"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-col>
            <el-col :span="24" class="el-card pt-6">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="合同文件" required>
                            <el-upload
                                class="avatar-uploader"
                                v-model="formData.contract.file"
                                action="https://worker-task.lihaink.cn/api/upload/image"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess_three"
                                :before-upload="beforeAvatarUpload_three"
                            >
                                <img
                                    v-if="formData.file_image"
                                    :src="formData.file_image"
                                    class="avatar"
                                />
                                <el-button size="small" type="primary">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-col>
            <el-col :span="24" class="el-card pt-6">
                <el-form-item label="" prop="field139">
                    <el-button type="primary" size="medium" @click="create"> 创建 </el-button>
                </el-form-item>
            </el-col>
        </el-form>
        <el-dialog v-model="isCompany" title="选择签约方" width="60%">
            <DialogIndex @customEvent="customEvent" />
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="companyEdit">
import type { FormInstance, UploadProps, ElMessage } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiCompanyAdd, apiCompanyEdit, apiCompanyDetail, apiCompanyLists } from '@/api/company'
import { apiCityList, apiAreaList, apiStreetList, apiProvinceList } from '@/api/common'
import { dictDataLists } from '@/api/setting/dict'
import { timeFormat } from '@/utils/util'
import DialogIndex from './dialog_index.vue'
import type { PropType } from 'vue'
import useMultipleTabs from '@/hooks/useMultipleTabs'

const { removeTab } = useMultipleTabs()
const router = useRouter()
const route = useRoute()

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()

// 弹窗标题
// const popupTitle = computed(() => {
//     return mode.value == 'edit' ? '编辑公司' : '新增公司'
// })

// 表单数据
const formData = reactive({
    id: '',
    // level_two: '',
    // level_one: '',
    company_name: '',
    organization_code: '',
    province: '',
    city: '',
    area: '',
    street: '',
    address: '',
    company_type: '',
    master_name: '',
    master_position: '',
    master_phone: '',
    master_email: '',
    other_contacts: [
        {
            name: '',
            position: '',
            phone: '',
            email: ''
        }
    ],
    // area_manager: '',
    // is_contract: '',
    // account: '',
    // password: '',
    // deposit: '',
    // deposit_time: '',
    qualification: {
        business_license: '',
        bank_account: ''
    },
    contract: {
        contract_type: '',
        party_a: '',
        file: ''
    },
    party_a_name: '',
    file_image: ''
    // status: ''
})
const datas = reactive({
    provinceOptions: [],
    cityOptions: [],
    areaOptions: [],
    streetOptions: [],
    dictTypeLists: [],
    contract_type: []
})
// 表单验证
const formRules = reactive<any>({
    company_name: [
        {
            required: true,
            message: '请输入公司名称',
            trigger: ['blur']
        }
    ],
    organization_code: [
        {
            required: true,
            message: '请输入组织机构代码',
            trigger: ['blur']
        }
    ],
    master_name: [
        {
            required: true,
            message: '请输入主联系人姓名',
            trigger: ['blur']
        }
    ],
    master_position: [
        {
            required: true,
            message: '请输入主联系人职务',
            trigger: ['blur']
        }
    ],
    master_phone: [
        {
            required: true,
            message: '请输入主联系人手机',
            trigger: ['blur']
        }
    ],
    master_email: [
        {
            required: true,
            message: '请输入主联系人邮箱',
            trigger: ['blur']
        }
    ],
    account: [
        {
            required: true,
            message: '请输入账号',
            trigger: ['blur']
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: ['blur']
        }
    ]
})
const isCompany = ref(false)

function customEvent(data: any) {
    isCompany.value = false
    formData.contract.party_a = data.id
    formData.party_a_name = data.company_name
}

function openCompany() {
    isCompany.value = true
    console.log(isCompany)
}

// 获取详情
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 apiCompanyDetail({
        id: row.id
    })
    setFormData(data)
}

//上传图片1
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    formData.qualification.business_license = response.data.uri
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // if (rawFile.type !== 'image/jpeg') {
    //     ElMessage.error('Avatar picture must be JPG format!')
    //     return false
    // } else if (rawFile.size / 1024 / 1024 > 2) {
    //     ElMessage.error('Avatar picture size can not exceed 2MB!')
    //     return false
    // }
    return true
}
//上传图片2
const handleAvatarSuccess_two: UploadProps['onSuccess'] = (response, uploadFile) => {
    formData.qualification.bank_account = response.data.uri
}

const beforeAvatarUpload_two: UploadProps['beforeUpload'] = (rawFile) => {
    // if (rawFile.type !== 'image/jpeg') {
    //     ElMessage.error('Avatar picture must be JPG format!')
    //     return false
    // } else if (rawFile.size / 1024 / 1024 > 2) {
    //     ElMessage.error('Avatar picture size can not exceed 2MB!')
    //     return false
    // }
    return true
}
//上传文件3
const handleAvatarSuccess_three: UploadProps['onSuccess'] = (response, uploadFile) => {
    formData.file_image = response.data.uri
    formData.contract.file = response.data.uri
}

const beforeAvatarUpload_three: UploadProps['beforeUpload'] = (rawFile) => {
    // if (rawFile.type !== 'application/msword') {
    //     ElMessage.error('请选择word格式的文件!')
    //     return false
    // }
    //  else if (rawFile.size / 1024 / 1024 > 2) {
    //     ElMessage.error('Avatar picture size can not exceed 2MB!')
    //     return false
    // }
    return true
}
//增加其他联系人
function other() {
    formData.other_contacts.push({
        name: '',
        position: '',
        phone: '',
        email: ''
    })
}
//获取省份
function province_change(value: string) {
    formData.province = value
    getCityList(value)
}
function city_change(value: string) {
    formData.city = value
    getAreaList(value)
}
function area_change(value: string) {
    formData.area = value
    getStreetList(value)
}
function street_change(value: string) {
    formData.street = value
}

const getcontract_type = async () => {
    const data = await dictDataLists({ type_id: 7 })
    datas['contract_type'] = data['lists']
}
const getdictTypeLists = async () => {
    const data = await dictDataLists({ type_id: 6 })
    datas['dictTypeLists'] = data['lists']
}
const getProvinceList = async () => {
    const data = await apiProvinceList({})
    datas['provinceOptions'] = data
}
const getCityList = async (id: any) => {
    const data = await apiCityList({ city: id })
    datas['cityOptions'] = data
}
const getAreaList = async (id: any) => {
    const data = await apiAreaList({ area: id })
    datas['areaOptions'] = data
}
const getStreetList = async (id: any) => {
    const data = await apiStreetList({ street: id })
    datas['streetOptions'] = data
}
const getDetails = async () => {
    const data = await apiCompanyDetail({
        id: route.query.id
    })
    if (route.query.id == 0 || undefined) {
        return false
    }
    Object.keys(formData).forEach((key) => {
        //@ts-ignore
        formData[key] = data[key]
    })
    formData['party_a_name'] = data['contract']['party_a_name']
    formData['file_image'] = data['contract']['file']
}
getProvinceList()
getdictTypeLists()
getcontract_type()
getDetails()

const create = async () => {
    await formRef.value?.validate()
    const data = { ...formData }
    route.query.id != 0 ? await apiCompanyEdit(data) : await apiCompanyAdd(data)
    removeTab()
    router.back()
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
