<template>
    <hc-new-card :title="rowItem.id ? '编辑证书' : '新增证书'" scrollbar>
        <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" label-width="auto">
            <el-row :gutter="20">
                <el-col :span="formModel.certificateType !== 1 && Number(formModel.company) === 3 ? 24 : 16 ">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="证书类型：" prop="certificateType">
                                <div class="form-item-div">
                                    <el-radio-group v-model="formModel.certificateType" @change="certificateTypeChange">
                                        <el-radio :value="1">个人证书</el-radio>
                                        <el-radio :value="2">企业证书</el-radio>
                                    </el-radio-group>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col v-if="formModel.certificateType === 2" :span="12">
                            <el-form-item label="签字公司：" prop="company">
                                <el-select v-model="formModel.company" filterable clearable block>
                                    <el-option v-for="item in companyData" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col v-if="formModel.certificateType === 1" :span="12">
                            <el-form-item label="关联用户：" prop="certificateUserId">
                                <el-select-v2 v-model="formModel.certificateUserId" :options="users" placeholder="选择关联用户" filterable block @change="usersChange" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="证书所有者：" prop="certificateUserName">
                                <el-input v-model="formModel.certificateUserName" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col v-if="formModel.certificateType === 1 && Number(formModel.company) !== 3" :span="12">
                            <el-form-item label="所持证书者身份证号码：" prop="certificateId">
                                <el-input v-model="formModel.certificateId" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col v-if="formModel.certificateType === 2 && Number(formModel.company) !== 3" :span="12">
                            <el-form-item label="企业统一社会信用代码：" prop="enterpriseUnifiedCode">
                                <el-input v-model="formModel.enterpriseUnifiedCode" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="证书编号：" prop="certificateNumber">
                                <el-input v-model="formModel.certificateNumber" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col v-if="Number(formModel.company) !== 3" :span="12">
                            <el-form-item label="证书密码：" prop="certificatePassword">
                                <el-input v-model="formModel.certificatePassword" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col v-else :span="12">
                            <el-form-item label="签章类型：" prop="pfxType">
                                <el-select v-model="formModel.pfxType" filterable clearable block>
                                    <el-option v-for="item in pfxTypeData" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-col>
                <el-col v-if="formModel.certificateType === 1 || (formModel.certificateType === 2 && Number(formModel.company) === 2)" :span="8">
                    <el-form-item prop="certificateFileUrl">
                        <template #label>
                            <div class="hc-form-item-label">
                                <div class="title-content">
                                    <span class="title">证书文件：</span>
                                    <span content="text">(支持上传文件格式为pfx文件)</span>
                                </div>
                                <div class="right-content">
                                    <el-link type="warning" @click="formModel.certificateFileUrl = ''">清除</el-link>
                                </div>
                            </div>
                        </template>
                        <hc-form-upload num="1" :src="formModel.certificateFileUrl" @upload="certificateFileUpload" @change="certificateFileChange" />
                    </el-form-item>
                    <el-form-item label="签名体文件：" prop="signatureFileUrl">
                        <template #label>
                            <div class="hc-form-item-label">
                                <div class="title-content">
                                    <span class="title">签名体文件：</span>
                                    <span content="text">(支持上传文件格式为JPG/PNG)</span>
                                </div>
                                <div class="right-content">
                                    <el-link type="warning" @click="formModel.signatureFileUrl = ''">清除</el-link>
                                </div>
                            </div>
                        </template>
                        <hc-form-upload type="preview" num="1" :src="formModel.signatureFileUrl" @upload="signatureFileUpload" @change="signatureFileChange" />
                    </el-form-item>
                </el-col>
                <el-col v-if="formModel.certificateType === 2" :span="24">
                    <el-form-item label="关联项目：" prop="projectContractRole">
                        <hc-related-project v-model="formModel.projectContractRole" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #action>
            <div class="hc-flex-center">
                <el-button hc-btn class="mr-4" @click="cancelClick">取消</el-button>
                <el-button hc-btn type="primary" :loading="submitLoading" @click="submitClick">提交</el-button>
            </div>
        </template>

        <!-- 上传文件 -->
        <hc-upload-file ref="uploadRef" :echo-params="uploadParams" :options="uploadOptions" @success="uploadSuccess" />
    </hc-new-card>
</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue'
import { getHeader } from 'hc-vue3-ui'
import { deepClone, formValidate, getArrValue, getObjValue, isNullES } from 'js-fast-way'
import { getDictionaryData, reloadPage } from '~uti/tools'
import mainApi from '~api/certificate/list'

const props = defineProps({
    info: {
        type: Object,
        default: () => ({}),
    },
})

const emit = defineEmits(['close'])

//监听内容
const rowItem = ref(props.info)

//渲染完成
onMounted(() => {
    getDataApi()
})

//获取数据 旧
const getDataApi = () => {
    const { id } = rowItem.value
    if (!isNullES(id)) {
        getDetailData(id)
    }
    findUserByName()
    getCompanyData()
    getPfxTypeData()
}

//获取数据详情
const getDetailData = async (id) => {
    const { data } = await mainApi.detail(id)
    const res = getObjValue(data)
    if (res.certificateType !== 1) {
        res.company = res.certificateType === 2 ? 2 : res.certificateType === 3 ? 3 : 2
        res.certificateType = 2
    }
    formModel.value = res
}

//获取当前系统下所有用户
const users = ref([])
const findUserByName = async () => {
    const { data } = await mainApi.findUserByName()
    const res = getArrValue(data)
    let newArr = []
    for (let i = 0; i < res.length; i++) {
        newArr.push({
            value: res[i].id,
            label: res[i].name,
            idNumber: res[i].idNumber,
            plaintextPassword: res[i].plaintextPassword,
        })
    }
    users.value = newArr
}
//获取用户数据
const usersChange = (val) => {
    const item = users.value.find((item) => item.value === val)
    console.log('item:', item)
    formModel.value.certificateUserName = item.label
    formModel.value.certificateId = item.idNumber
    formModel.value.certificatePassword = item.plaintextPassword
}

//签字公司
const companyData = ref([])
const getCompanyData = async () => {
    companyData.value = await getDictionaryData('es_type_name', true)
}


//签章类型
const pfxTypeData = ref([])
const getPfxTypeData = async () => {
    const { data } = await mainApi.findPfxType({
        typeOrStatus: 'pfx_type',
    })
    pfxTypeData.value = getArrValue(data)
}

//菜单表单
const formRef = ref(null)
const formModel = ref({
    certificateType: 1,
})
const formRules = {
    certificateType: {
        required: true,
        trigger: 'blur',
        message: '请选择证书类型',
    },
    certificateUserId: {
        required: true,
        trigger: 'blur',
        message: '请选择关联用户',
    },
    certificateUserName: {
        required: true,
        trigger: 'blur',
        message: '请输入证书所有者',
    },
    certificateId: {
        required: true,
        trigger: 'blur',
        message: '请输入所持证书者身份证号码',
    },
    certificatePassword: {
        required: true,
        trigger: 'blur',
        message: '请输入证书密码',
    },
    certificateFileUrl: {
        required: true,
        trigger: 'blur',
        message: '请上传证书文件',
    },
    signatureFileUrl: {
        required: true,
        trigger: 'blur',
        message: '请上传签名体文件',
    },
    company: {
        required: true,
        trigger: 'blur',
        message: '请选择签字公司',
    },
    enterpriseUnifiedCode: {
        required: true,
        trigger: 'blur',
        message: '请输入企业统一社会信用代码',
    },
    pfxType: {
        required: true,
        trigger: 'blur',
        message: '请选择签章类型',
    },
    projectContractRole: {
        required: true,
        trigger: 'blur',
        message: '请选择关联项目',
    },
}

//切换类型
const certificateTypeChange = () => {
    const { certificateType, company } = formModel.value
    if (certificateType === 2) {
        formModel.value.company = company ?? 2
    }
}

//上传文件
const uploadRef = ref(null)
const uploadParams = ref({})
const uploadOptions = ref({
    url: '/api/blade-resource/client/addFileInfo',
    headers: getHeader(),
    multiple: false,
})

//上传证书文件
const certificateFileUpload = () => {
    uploadParams.value = { type: '证书文件' }
    uploadOptions.value.accept = '.pfx'
    uploadOptions.value.accept_tip = '支持上传文件格式为pfx文件'
    uploadOptions.value.size = 200
    nextTick(() => {
        uploadRef.value?.selectFile()
    })
}
const certificateFileChange = (val) => {
    formModel.value.certificateFileUrl = val
}

//上传签名体文件
const signatureFileUpload = () => {
    uploadParams.value = { type: '签名体文件' }
    uploadOptions.value.accept = '.jpg,.png'
    uploadOptions.value.accept_tip = '支持上传文件格式为JPG/PNG'
    uploadOptions.value.size = 200
    nextTick(() => {
        uploadRef.value?.selectFile()
    })
}
const signatureFileChange = (val) => {
    formModel.value.signatureFileUrl = val
}

// 文件上传成功的回调
const uploadSuccess = ({ echoParams, resData }) => {
    const { link, originalName } = getObjValue(resData)
    if (echoParams.type === '证书文件') {
        formModel.value.certificateFileUrl = link
        formModel.value.certificateFileName = originalName
    } else if (echoParams.type === '签名体文件') {
        formModel.value.signatureFileUrl = link
        formModel.value.signatureFileName = originalName
    }
    //关闭弹窗
    uploadRef.value?.setModalShow(false)
}

//提交数据
const submitLoading = ref(false)
const submitClick = async () => {
    const formRes = await formValidate(formRef.value)
    if (!formRes) return false
    submitLoading.value = true
    //处理数据
    const form = deepClone(formModel.value)
    form.enterpriseUnifiedCode = ''
    if (form.certificateType === 2 && Number(form.company) === 3) {
         form.certificateType = 3
    }
    //id不存在，则新增
    let res = {}
    if (isNullES(form.id)) {
        res = await mainApi.add(form)
    } else {
        res = await mainApi.update(form)
    }
    const { error, code, msg } = res
    submitLoading.value = false
    if (!error && code === 200) {
        cancelClick()
        window?.$message?.success('操作成功')
    } else {
        window?.$message?.error(msg ?? '操作失败')
    }
}

//取消关闭
const cancelClick = () => {
    emit('close')
}
</script>
