<template>
    <hc-new-dialog widths="30rem" :show="isShow" title="新增中期支付证书" is-footer-center @close="addModalClose">
        <el-form ref="formRef" class="p-2" label-position="top" :model="formModel" :rules="formRules" size="large">
            <el-form-item label="计量期：" prop="contractPeriodId">
                <el-select v-model="formModel.contractPeriodId" block @change="changePeriod">
                    <el-option v-for="item in allPeriodData" :key="item.id" :label="item.periodNumber" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="证书编号：" prop="certificateNumber">
                <el-input v-model="formModel.certificateNumber" />
            </el-form-item>
            <el-form-item label="材料计量期：" prop="materialPeriodIds">
                <el-select v-if="meterPeriodData.length > 0" v-model="materialPeriodIds" multiple block>
                    <template v-for="item in meterPeriodData" :key="item.id">
                        <el-option v-if="item.periodNumber" :label="item.periodName" :value="item.periodNumber" />
                    </template>
                </el-select>
                <div v-else class="form-item-div text-orange">无材料计量期可进行关联</div>
            </el-form-item>
            <el-form-item label="开工预付计量期：" prop="startPeriodIds">
                <el-select v-if="startPeriodData.length > 0" v-model="startPeriodIds" multiple block>
                    <template v-for="item in startPeriodData" :key="item.id">
                        <el-option v-if="item.periodNumber" :label="item.periodName" :value="item.periodNumber" />
                    </template>
                </el-select>
                <div v-else class="form-item-div text-orange">无开工计量期可进行关联</div>
            </el-form-item>
            <el-form-item label="打印日期：">
                <el-date-picker v-model="formModel.printDate" class="block" format="YYYY-MM-DD" type="date" value-format="YYYY-MM-DD" disabled />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button hc-btn @click="addModalClose">取消</el-button>
            <el-button hc-btn type="primary" :loading="submitLoading" @click="addModalSave">提交</el-button>
            <el-button hc-btn type="primary" :loading="submitLoading" @click="submitClose">提交并关闭</el-button>
        </template>
    </hc-new-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { formValidate, getArrValue, getObjValue } from 'js-fast-way'
import mainApi from '~api/debit-pay/admin/certificate'

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

//变量
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId || '')
const contractId = ref(useAppState.getContractId || '')

//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})

//获取合同计量期
const allPeriodData = ref([])
const getAllPeriod = async () => {
    const { data } = await mainApi.getConditionPeriod({
        projectId: projectId.value,
        contractId: contractId.value,
    })
    const res = getArrValue(data)
    allPeriodData.value = res
    if (res.length > 0) {
        const info = getObjValue(res[ res.length - 1])
        formModel.value.contractPeriodId = info.id
        formModel.value.printDate = info.formPrintDate
    }
}

//获取材料计量期
const meterPeriodData = ref([])
const materialPeriodIds = ref([])
const getMeterPeriod = async () => {
    const { data } = await mainApi.getMeterPeriod({
        projectId: projectId.value,
        contractId: contractId.value,
        type: 1,
    })
    meterPeriodData.value = getArrValue(data)
}
const changePeriod = (val)=>{
    allPeriodData.value.forEach((ele)=>{
        if (ele.id === val) {
            formModel.value.printDate = ele.formPrintDate
        }
    })
}


//获取开工计量期
const startPeriodData = ref([])
const startPeriodIds = ref([])
const getStartPeriod = async () => {
    const { data } = await mainApi.getMeterPeriod({
        projectId: projectId.value,
        contractId: contractId.value,
        type: 2,
    })
    startPeriodData.value = getArrValue(data)
}

//监听
watch(isShow, (val) => {
    if (val) {
        formModel.value = {}
        getAllPeriod()
        getMeterPeriod()
        getStartPeriod()
    }
})

//表单数据
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    contractPeriodId: {
        required: true,
        trigger: 'blur',
        message: '请选择计量期',
    },
}

//提交保存
const submitLoading = ref(false)
const submitData = async () => {
    submitLoading.value = true
    const isValidate = await formValidate(formRef.value)
    if (!isValidate) return false
    const form = formModel.value
    form.projectId = projectId.value
    form.contractId = contractId.value
    form.materialPeriodIds = materialPeriodIds.value.join(',')
    form.startPeriodIds = startPeriodIds.value.join(',')
    const { error, code, msg } = await mainApi.add(form)
    if (!error && code === 200) {
        window.$message.success('保存成功')
        return true
    } else {
        submitLoading.value = false
        window.$message.error(msg ?? '保存失败')
        return false
    }
}

//保存
const isSubmit = ref(false)
const addModalSave = async () => {
    const isValidate = await submitData()
    if (isValidate) {
        isSubmit.value = true
        formModel.value = {}
        await getAllPeriod()
        await getMeterPeriod()
        await getStartPeriod()
        submitLoading.value = false
    }
}

//提交并关闭
const submitClose = async () => {
    const isValidate = await submitData()
    if (isValidate) {
        submitLoading.value = false
        addModalClose()
        emit('finish')
    }
}

//关闭弹窗
const addModalClose = () => {
    isShow.value = false
    emit('close')
    if (isSubmit.value) {
        emit('finish')
    }
}
</script>
