<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="84px" :rules="formRules">
                <div style="font-size: 1.2rem; margin: 10px 0">基本信息创建</div>
                <el-col :span="24" class="pt-6 !border-none">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="姓名" prop="name">
                                <el-input
                                    v-model="formData.name"
                                    placeholder="请输入姓名"
                                    clearable
                                    :style="{ width: '100%' }"
                                >
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="性别" prop="sex">
                                <el-input
                                    v-model="formData.sex"
                                    placeholder="请输入性别"
                                    clearable
                                    :style="{ width: '100%' }"
                                >
                                </el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="身份证号" prop="id_card">
                                <el-input
                                    v-model="formData.id_card"
                                    placeholder="请输入身份证号"
                                    clearable
                                    :style="{ width: '100%' }"
                                >
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="联系电话" prop="phone">
                                <el-input
                                    v-model="formData.phone"
                                    placeholder="请输入联系电话"
                                    clearable
                                    :style="{ width: '100%' }"
                                >
                                </el-input>
                            </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>

                <!-- 管理员状态 -->
                <el-form-item label="管理员状态" v-if="formData.root != 1">
                    <el-switch v-model="formData.disable" :active-value="0" :inactive-value="1" />
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance, UploadProps } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { useDictOptions } from '@/hooks/useDictOptions'
import { adminAdd, adminDetail, adminEdit } from '@/api/perms/admin'
import { roleAll } from '@/api/perms/role'
import { jobsAll } from '@/api/org/post'
import { deptAll } from '@/api/org/department'
import { apiCityList, apiAreaList, apiStreetList, apiProvinceList } from '@/api/common'

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑管理员' : '新增管理员'
})
const formData = reactive({
    id: '',
    account: '',
    sex: 1,
    id_card: '',
    name: '',
    province: '',
    city: '',
    area: '',
    street: '',
    address: '',
    phone: '',
    qualification: {
        id_card: '',
        car_card: '',
        bank_account: ''
    },
    is_contract: 0,
    dept_id: [],
    jobs_id: [],
    role_id: [],
    avatar: '',
    password: '',
    password_confirm: '',
    disable: 0,
    multipoint_login: 1,
    root: 0
})
const datas = reactive({
    provinceOptions: [],
    cityOptions: [],
    areaOptions: [],
    streetOptions: [],
    dictTypeLists: [],
    contract_type: []
})
const passwordConfirmValidator = (rule: object, value: string, callback: any) => {
    if (formData.password) {
        if (!value) callback(new Error('请再次输入密码'))
        if (value !== formData.password) callback(new Error('两次输入密码不一致!'))
    }
    callback()
}
const formRules = reactive({
    account: [
        {
            required: true,
            message: '请输入账号',
            trigger: ['blur']
        }
    ],
    name: [
        {
            required: true,
            message: '请输入名称',
            trigger: ['blur']
        }
    ],
    role_id: [
        {
            type: 'array',
            required: true,
            message: '请选择角色',
            trigger: ['blur']
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: ['blur']
        }
    ] as any[],
    password_confirm: [
        {
            required: true,
            message: '请输入确认密码',
            trigger: ['blur']
        },
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ] as any[]
})
const { optionsData } = useDictOptions<{
    role: any[]
    jobs: any[]
    dept: any[]
}>({
    role: {
        api: roleAll
    },
    jobs: {
        api: jobsAll
    },
    dept: {
        api: deptAll
    }
})

const handleSubmit = async () => {
    await formRef.value?.validate()
    mode.value == 'edit' ? await adminEdit(formData) : await adminAdd(formData)
    popupRef.value?.close()
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}
//获取省份
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 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 handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    formData.qualification.id_card = response.data.uri
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    return true
}
const handleAvatarSuccess_two: UploadProps['onSuccess'] = (response, uploadFile) => {
    formData.qualification.car_card = response.data.uri
}

const beforeAvatarUpload_two: UploadProps['beforeUpload'] = (rawFile) => {
    return true
}
const handleAvatarSuccess_three: UploadProps['onSuccess'] = (response, uploadFile) => {
    formData.qualification.bank_account = response.data.uri
}

const beforeAvatarUpload_three: UploadProps['beforeUpload'] = (rawFile) => {
    return true
}

const setFormData = async (row: any) => {
    formRules.password = []
    formRules.password_confirm = [
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ]
    const data = await adminDetail({
        id: row.id
    })
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const handleClose = () => {
    emit('close')
}

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