<template>
    <hc-new-dialog
        widths="500px" :show="isShow" :title="modalTitle" :loading="modalSaving" @save="modalSave"
        @close="modalClose"
    >
        <el-scrollbar>
            <hc-card-item>
                <el-form
                    ref="baseFormRef" :model="baseForm" :rules="baseFormRules" label-position="top"
                    label-width="auto"
                >
                    <el-form-item label="计量期：" prop="meterPeriodId">
                        <el-select v-model="baseForm.meterPeriodId" placeholder="选择计量期" disabled filterable clearable block>
                            <el-option v-for="item in key1Data" :key="item.id" :label="item.periodName" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务日期：">
                        <el-date-picker v-model="baseForm.businessDate" class="block" format="YYYY-MM-DD" type="date" value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="计量金额：">
                        <el-input v-model="baseForm.meterMoney" @change="changeMoney" />
                    </el-form-item>
                    <el-form-item label="开工预付款总额：">
                        <el-input v-model="baseForm.startPayAmount" disabled />
                    </el-form-item>
                    <el-form-item label="申请依据：">
                        <el-input v-model="baseForm.applyCause" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" />
                    </el-form-item>
                    <el-form-item v-if="Number(contractType) === 2" label="支付期限：">
                        <div class="w-full">
                            <hc-date-picker :dates="betweenTime1" format="YYYY年MM月DD日" clearable @change="betweenTimeUpdate1" />
                        </div>
                        <div class="mt-2 w-full">
                            <hc-date-picker :dates="betweenTime2" format="YYYY年MM月DD日" clearable @change="betweenTimeUpdate2" />
                        </div>
                    </el-form-item>
                    <el-form-item label="预付款计算式：">
                        <el-input v-model="baseForm.calculateFormula" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" />
                    </el-form-item>
                </el-form>
            </hc-card-item>
            <!-- 附件列表 -->
            <hc-card-item class="mt-3">
                <el-form :model="baseForm" label-position="top">
                    <el-form-item label="附件名称：">
                        <el-input v-model="baseForm.fileNames" type="textarea" />
                    </el-form-item>
                    <div class="hc-flex mb-10px" style="color: #1d4590;">
                        <div class="flex-1">附件列表</div>
                        <div>可上传:图片、Excel、PDF、Word文件</div>
                    </div>
                    <el-form-item label="">
                        <hc-form-upload
                            v-model="baseForm.fileList" is-res
                            :options="{ type: 'list', props: hProps, isArr: true, num: 0 }"
                            @success="uploadFileSuccess" @change="formItemChange"
                        />
                    </el-form-item>
                </el-form>
            </hc-card-item>
        </el-scrollbar>
    </hc-new-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { formValidate, getArrValue, getObjValue, isNullES } from 'js-fast-way'
import periodApi from '~api/debit-pay/material/periods.js'
import orderApi from '~api/debit-pay/start-work/order.js'
import { isNumberReg } from '~uti/tools'

const props = defineProps({
    ids: {
        type: [String, Number],
        default: '',
    },
    periodId: {
        type: [String, Number],
        default: '',
    },
    infoData: {
        type: Object,
        default: () => ({}),
    },
})
//事件
const emit = defineEmits(['finish', 'close'])
const useAppState = useAppStore()
const contractId = ref(useAppState.getContractId)
const projectId = ref(useAppState.getProjectId)
const infoData = ref(props.infoData)
const ids = ref(props.ids)
const fileName = ref([])
const hProps = ref({
    url: 'filePdfUrl',
    name: 'fileName',
})

//监听
const contractType = ref('')
const contractInfo = ref(useAppState.getContractInfo)
watch(() => useAppState.getContractInfo, (info) => {
    contractInfo.value = info
    contractType.value = info?.contractType
}, { immediate: true, deep: true })

const baseForm = ref({})
const modalTitle = ref('开工预付款计量单新增')
//获取开工预付款总额
const getStartAmountData = async () => {
    const { error, code, data } = await orderApi.getStartAmount({
        contractId: contractId.value,
    })
    if (!error && code === 200) {
        if (modalTitle.value === '开工预付款计量单新增') {
            baseForm.value.startPayAmount = Number(data)
        }
    } else {
        baseForm.value.startPayAmount = 0
    }
}
//监听
watch(() => [props.ids, props.infoData], ([Id, info]) => {
    ids.value = Id
    infoData.value = info
    if (!isNullES(Id)) {
        baseForm.value = info
        fileName.value = info?.fileList
        modalTitle.value = '开工预付款计量单修改'
    } else {
        baseForm.value = { fileList: [] }
        fileName.value = []
        modalTitle.value = '开工预付款计量单新增'
    }
}, { immediate: true, deep: true })
//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})

//监听
watch(() => props.periodId, (pid) => {
    baseForm.value.meterPeriodId = pid
}, { immediate: true, deep: true })

//监听
watch(isShow, (val) => {
    if (val) {
        setDataApi()
    }
})

const setDataApi = () => {
    getKey1Data()
    getStartAmountData()
    contractType.value = contractInfo.value?.contractType
    baseForm.value.meterPeriodId = props.periodId
    const { payDate } = baseForm.value
    if (isNullES(payDate)) return
    const dates = payDate.split(' \n ')
    if (dates.length >= 2) {
        payDate1.value = dates[0]
        payDate2.value = dates[1]
    } else {
        payDate1.value = dates[0]
    }
    if (!isNullES(payDate1.value)) {
        betweenTime1.value = payDate1.value.split(' 至 ')
    }
    if (!isNullES(payDate2.value)) {
        betweenTime2.value = payDate2.value.split(' 至 ')
    }
}

//计量期
const key1Data = ref([])
const getKey1Data = async () => {
    const { data } = await periodApi.allPeriod({
        contractId: contractId.value,
        type: 2,
    })
    key1Data.value = getArrValue(data)
}

//基础表单
const baseFormRef = ref(null)
// const baseForm = ref({})
const baseFormRules = {
    meterPeriodId: {
        required: true,
        trigger: 'blur',
        message: '请选择材料计量期',
    },
}

//日期范围选择
const payDate1 = ref('')
const betweenTime1 = ref(null)
const betweenTimeUpdate1 = ({ val, arr }) => {
    betweenTime1.value = arr
    if (arr.length > 0) {
        payDate1.value = `${val['start']} 至 ${val['end']}`
    } else {
        payDate1.value = null
    }
}

//日期范围选择
const payDate2 = ref('')
const betweenTime2 = ref(null)
const betweenTimeUpdate2 = ({ val, arr }) => {
    betweenTime2.value = arr
    if (arr.length > 0) {
        payDate2.value = `${val['start']} 至 ${val['end']}`
    } else {
        payDate2.value = null
    }
}

const modalSaving = ref(false)
const modalSave = async () => {
    const res = await formValidate(baseFormRef.value)
    if (!res) {
        return false
    }
    modalSaving.value = true
    const form = baseForm.value
    if (!isNullES(payDate1.value) && !isNullES(payDate2.value)) {
        form.payDate = payDate1.value + ' \n ' + payDate2.value
    } else if (!isNullES(payDate1.value) && isNullES(payDate2.value)) {
        form.payDate = payDate1.value
    } else if (isNullES(payDate1.value) && !isNullES(payDate2.value)) {
        form.payDate = payDate2.value
    } else {
        form.payDate = ''
    }
    key1Data.value.forEach((ele) => {
        if (ele.id === form.meterPeriodId) {
            baseForm.value.periodName = ele.periodName
            baseForm.value.periodNumber = ele.periodNumber
        }
    })
    if (ids.value.length < 1) {
        const { error, code, msg } = await orderApi.add({
            ...form,
            contractId: contractId.value,
            projectId: projectId.value,
        })
        //判断状态
        modalSaving.value = false
        if (!error && code === 200) {
            window?.$message?.success(msg)
            modalClose()
            emit('finish')
        } else {
            window.$message.error(msg ?? '操作失败')
        }
    } else if (ids.value.length > 0) {
        const { error, code, msg } = await orderApi.update({
            ...form,
            contractId: contractId.value,
            projectId: projectId.value,
        })
        //判断状态
        modalSaving.value = false
        if (!error && code === 200) {
            window?.$message?.success(msg)
            modalClose()
            emit('finish')
        } else {
            window.$message.error(msg ?? '操作失败')
        }
    }
}

const modalClose = () => {
    isShow.value = false
    payDate1.value = ''
    payDate2.value = ''
    betweenTime1.value = null
    betweenTime2.value = null
    emit('close')
}

//改变计量金额
const changeMoney = (val) => {
    //如果为空
    let momey = val
    const isMeter = isNumberReg(momey)
    if (isNullES(momey) || !isMeter) {
        momey = 0
        baseForm.value.meterMoney = momey
    }
}

// 文件上传成功的回调
const uploadFileSuccess = ({ res }, resolve) => {
    const { link, pdfUrl, originalName } = getObjValue(res.data)
    if (isNullES(pdfUrl)) {
        window.$message.warning('该文件不能生成pdf,请更换文件上传')
        resolve()
    } else {
        resolve({
            fileName: originalName ?? '',
            filePdfUrl: pdfUrl ?? '',
            fileUrl: link ?? '',
            pdfUrl: pdfUrl ?? '',
        })
    }
}

const formItemChange = (data) => {
    fileName.value = data
}
</script>

<style scoped lang="scss">

</style>
