<template>
    <div class="hc-contract-info-data relative">
        <el-form ref="formRef" :model="contractForm" :rules="formRules" label-position="top" label-width="auto">
            <hc-card-item title="基础信息">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="项目名称：">
                            <el-input v-model="projectInfo.projectName" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="合同段名称：" prop="contractName">
                            <el-input v-model="contractForm.contractName" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="合同段类型：" prop="contractType">
                            <el-select v-model="contractForm.contractType" placeholder="选择所属系统" clearable filterable block :disabled="!!contractForm.id" @change="treeAllConstruction">
                                <el-option v-for="item in contractTypeList" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="合同段编号：" prop="contractNumber">
                            <el-input v-model="contractForm.contractNumber" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="参与方进场日期：">
                            <el-date-picker v-model="contractForm.contractorJoinTime" class="block" format="YYYY 年 MM 月 DD 日" type="date" value-format="YYYY-MM-DD" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="合同金额：">
                            <el-input v-model="contractForm.contractAmount" clearable>
                                <template #append>万元</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="contractForm.isTestModule === 1 ? 4 : 6">
                        <el-form-item label="是否开启电签：" prop="isElectronicSignature">
                            <div class="form-item-div">
                                <el-radio-group v-model="contractForm.isElectronicSignature">
                                    <el-radio :value="0">关闭</el-radio>
                                    <el-radio :value="1">开启</el-radio>
                                </el-radio-group>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="contractForm.isTestModule === 1 ? 4 : 6">
                        <el-form-item label="是否开启试验模块：" prop="isTestModule">
                            <div class="form-item-div">
                                <el-radio-group v-model="contractForm.isTestModule">
                                    <el-radio :value="0">关闭</el-radio>
                                    <el-radio :value="1">开启</el-radio>
                                </el-radio-group>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col v-if="contractForm.isTestModule === 1" :span="4">
                        <el-form-item label="是否强制引用记录/报告编号：" prop="isTestRecord">
                            <div class="form-item-div">
                                <el-radio-group v-model="contractForm.isTestRecord">
                                    <el-radio :value="0">关闭</el-radio>
                                    <el-radio :value="1">开启</el-radio>
                                </el-radio-group>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="contractForm.isTestModule === 1 ? 4 : 6">
                        <el-form-item label="是否引用编号：" prop="isReferenceNumber">
                            <div class="form-item-div">
                                <el-radio-group v-model="contractForm.isReferenceNumber">
                                    <el-radio :value="0">否</el-radio>
                                    <el-radio :value="1">是</el-radio>
                                </el-radio-group>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="contractForm.isTestModule === 1 ? 4 : 6">
                        <el-form-item label="是否允许超计：" prop="isOverMeter">
                            <div class="form-item-div">
                                <el-radio-group v-model="contractForm.isOverMeter">
                                    <el-radio :value="0">否</el-radio>
                                    <el-radio :value="1">是</el-radio>
                                </el-radio-group>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="计划开工日期：" prop="planStartTime">
                            <el-date-picker v-model="contractForm.planStartTime" class="block" format="YYYY 年 MM 月 DD 日" type="date" value-format="YYYY-MM-DD" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="计划完工日期：" prop="planEndTime">
                            <el-date-picker v-model="contractForm.planEndTime" class="block" format="YYYY 年 MM 月 DD 日" type="date" value-format="YYYY-MM-DD" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="实际开工日期：" prop="actualStartTime">
                            <el-date-picker v-model="contractForm.actualStartTime" class="block" format="YYYY 年 MM 月 DD 日" type="date" value-format="YYYY-MM-DD" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="实际完工日期：" prop="actualEndTime">
                            <el-date-picker v-model="contractForm.actualEndTime" class="block" format="YYYY 年 MM 月 DD 日" type="date" value-format="YYYY-MM-DD" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="contractForm.contractType === 1" :span="6">
                        <el-form-item label="业主单位名称：" prop="contractorUnitName">
                            <el-input v-model="contractForm.contractorUnitName" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="[1, 2].includes(contractForm.contractType)" :span="6">
                        <el-form-item label="监理单位名称：" prop="supervisionUnitName">
                            <el-input v-model="contractForm.supervisionUnitName" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="contractForm.contractType === 3" :span="6">
                        <el-form-item label="建设单位名称：" prop="contractorUnitName">
                            <el-input v-model="contractForm.contractorUnitName" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="contractForm.contractType === 1" :span="6">
                        <el-form-item label="施工单位名称：" prop="constructionUnitName">
                            <el-input v-model="contractForm.constructionUnitName" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="[1, 2, 3].includes(contractForm.contractType)" :span="6">
                        <el-form-item label="试验室名称：" prop="laboratoryName">
                            <el-input v-model="contractForm.laboratoryName" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item>
                            <template #label>
                                <div class="hc-form-item-label">
                                    <div class="title-content">
                                        <span class="title">上传开工令：</span>
                                    </div>
                                    <div class="right-content">
                                        <el-link type="warning" @click="startFileDel">清除</el-link>
                                    </div>
                                </div>
                            </template>
                            <hc-form-upload v-model="contractForm.startFileUrl" :upload="{ options: fileUpload }" @success="startFileSuccess" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </hc-card-item>
            <hc-card-item v-if="contractForm.contractType !== 1" class="mt-14px" title="合同段权限配置">
                <el-form-item>
                    <el-checkbox-group v-model="contractCheckIds">
                        <el-checkbox v-for="item in contractCheckList" :key="item.contractId" :label="item.contractName" :value="item.contractId" />
                    </el-checkbox-group>
                </el-form-item>
            </hc-card-item>
            <hc-card-item class="mt-14px" title="组卷归档默认信息">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-form-item label="立卷人：">
                            <el-input v-model="contractForm.filer" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="审核人：">
                            <el-input v-model="contractForm.reviewer" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="档案前缀：">
                            <el-input v-model="contractForm.prefix" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="保管期限：">
                            <el-select v-model="contractForm.storagePeriod" filterable clearable block>
                                <el-option v-for="item in storagePeriods" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="保管密级：">
                            <el-select v-model="contractForm.securityLevel" filterable clearable block>
                                <el-option v-for="item in securityLevels" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </hc-card-item>
            <hc-card-item v-if="contractForm.contractType === 1" class="mt-14px" title="附加信息">
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="项目地址：" prop="projectPlace">
                            <el-input v-model="contractForm.projectPlace" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="起始桩号：" prop="startStation">
                            <el-input v-model="contractForm.startStation" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="结束桩号：" prop="endStation">
                            <el-input v-model="contractForm.endStation" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="里程：">
                            <el-input v-model="contractForm.projectMileage" clearable>
                                <template #append>公里（KM）</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </hc-card-item>
            <hc-card-item class="mb-70px mt-14px" title="计量信息">
                <HcMeterTable v-model="contractForm.meterContractInfo" />
            </hc-card-item>
        </el-form>
        <div class="action">
            <el-button hc-btn class="mr-4" :loading="submitLoading" @click="saveAndExit">保存并退出</el-button>
            <el-button hc-btn type="primary" :loading="submitLoading" @click="saveAndNextStep">保存并进入下一步</el-button>
        </div>
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { deepClone, formValidate, getArrValue, getObjValue, isNullES } from 'js-fast-way'
import { getDictionaryData } from '~uti/tools'
import HcMeterTable from './table.vue'

//请求接口
import mainApi from '~api/project/contract'
import projectApi from '~api/project/project'

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

//事件
const emit = defineEmits(['close', 'next'])

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

//监听数据
const dataInfo = ref(props.data)
watch(() => props.data, (data) => {
    dataInfo.value = data
    getDataApi()
}, { deep: true })

//获取数据
const getDataApi = async () => {
    const { cid, type } = getObjValue(dataInfo.value)
    await getContractTypeList()
    if (!isNullES(cid)) {
        if ([1, 4, 8].includes(type)) {
            await getContractInfo()
        } else if ([2, 3].includes(type)) {
            await getContractInfo2()
            await getContractRelation()
        }
    }
    await getProjectDeatil()
    await treeAllConstruction()
    getStoragePeriodList().then()
    getSecurityLevelList().then()
}

//获取项目详情
const projectInfo = ref({})
const getProjectDeatil = async () => {
    const { pid } = getObjValue(dataInfo.value)
    projectInfo.value = {}
    if (isNullES(pid)) return
    const { data } = await projectApi.detail(pid)
    projectInfo.value = getObjValue(data)
}

//获取合同类型
const contractTypeList = ref([])
const getContractTypeList = async () => {
    contractTypeList.value = await getDictionaryData('contract_type')
}

//获取合同段基本信息
const contractForm = ref({})
const getContractInfo = async () => {
    const { cid } = getObjValue(dataInfo.value)
    contractForm.value = {}
    if (isNullES(cid)) return
    const { data } = await mainApi.detail(cid)
    const res = getObjValue(data)
    const info = getObjValue(res.meterContractInfo)
    res.meterContractInfo = info
    contractForm.value = res
}

//获取合同段基本信息
const getContractInfo2 = async () => {
    const { cid, type } = getObjValue(dataInfo.value)
    contractForm.value = {}
    if (isNullES(cid)) return
    const { data } = await mainApi.detail2({
        id: cid,
        contractType: type,
    })
    const res = getObjValue(data)
    const info = getObjValue(res.meterContractInfo)
    res.meterContractInfo = info
    contractForm.value = res
}

//获取业务字典
const storagePeriods = ref([])
const getStoragePeriodList = async () => {
    storagePeriods.value = await getDictionaryData('storage_period', true)
}

//获取安全等级
const securityLevels = ref([])
const getSecurityLevelList = async () => {
    securityLevels.value = await getDictionaryData('security_level', true)
}

//菜单表单
const formRef = ref(null)
const formRules = {
    contractName: { required: true, trigger: 'blur', message: '请输入合同段名称' },
    contractType: { required: true, trigger: 'blur', message: '请选择合同段类型' },
    contractNumber: { required: true, trigger: 'blur', message: '请输入合同段编号' },
    isElectronicSignature: { required: true, trigger: 'blur', message: '请选择是否开启电签' },
    isTestModule: { required: true, trigger: 'blur', message: '请选择是否开启试验模块' },
    isReferenceNumber: { required: true, trigger: 'blur', message: '请选择是否引用编号' },
    isOverMeter: { required: true, trigger: 'blur', message: '请选择是否允许超计' },
    contractorUnitName: { required: true, trigger: 'blur', message: '请输入单位名称' },
    supervisionUnitName: { required: true, trigger: 'blur', message: '请输入单位名称' },
    constructionUnitName: { required: true, trigger: 'blur', message: '请输入单位名称' },
    projectPlace: { required: true, trigger: 'blur', message: '请输入项目地址' },
    startStation: { required: true, trigger: 'blur', message: '请输入起始桩号' },
    endStation: { required: true, trigger: 'blur', message: '请输入结束桩号' },
}

//文件上传
const fileUpload = {
    url: '/api/blade-resource/oss/endpoint/put-file-attach',
    multiple: false,
    size: 100,
}

//上传文件完成
const startFileSuccess = ({ res }) => {
    const { link } = getObjValue(res.data)
    contractForm.value.startFileUrl = link
}

//删除文件
const startFileDel = () => {
    contractForm.value.startFileUrl = ''
}

//合同段信息
const contractCheckList = ref([])
const treeAllConstruction = async () => {
    const { pid } = getObjValue(dataInfo.value)
    const { contractType } = contractForm.value
    if (isNullES(pid) || isNullES(contractType)) {
        contractCheckList.value = []
        return
    }
    //发起请求
    const { data } = await projectApi.treeAllConstruction({
        projectId: pid,
        contractType: contractType,
    })
    contractCheckList.value = getArrValue(data)
}

//监理、业主关联施工
const contractCheckIds = ref([])
const getContractRelation = async () => {
    const { cid } = getObjValue(dataInfo.value)
    if (isNullES(cid)) return
    const { data } = await projectApi.getContractRelation(cid)
    const res = getArrValue(data)
    contractCheckIds.value = res.map(({ id }) => {
        return id
    })
}

//保存并退出
const saveAndExit = async () => {
    const isRes = await saveDataApi()
    if (!isRes) return
    emit('close', dataInfo.value)
}

//保存并进入下一步
const saveAndNextStep = async () => {
    const isRes = await saveDataApi()
    if (!isRes) return
    emit('next', dataInfo.value)
}

//保存数据
const submitLoading = ref(false)
const saveDataApi = async () => {
    const isForm = await formValidate(formRef.value)
    if (!isForm) return false
    submitLoading.value = true
    const obj = deepClone(contractForm.value)
    if (obj.contractType !== 1) {
        const checkIds = contractCheckIds.value
        delete obj.startStation
        delete obj.endStation
        delete obj.projectPlace
        let idList = []
        checkIds.forEach(val => {
            idList.push({ contractId: val })
        })
        obj.idList = idList
    }
    const { code, data } = await mainApi.submit(obj)
    if (code === 200) {
        const { id, contractType } = getObjValue(data)
        const { cid, type } = getObjValue(dataInfo.value)
        dataInfo.value.cid = isNullES(id) ? cid : id
        dataInfo.value.type = isNullES(contractType) ? type : contractType
        window?.$message?.success('保存成功')
        getDataApi().then()
        submitLoading.value = false
    }
    submitLoading.value = false
    return code === 200
}
</script>

<style scoped lang="scss">
.hc-contract-info-data .action {
    position: fixed;
    bottom: 14px;
    width: calc(100% - 240px);
    text-align: center;
    background: #fff;
    padding: 14px;
}
</style>
