<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="选择计量期" 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>
            </hc-card-item>
            <!-- 附件列表 -->
            <hc-card-item class="mt-3" title="附件列表" extra-text="可上传:图片、Excel、PDF、Word文件">
                <el-form :model="baseForm" label-position="top">
                    <el-form-item label="">
                        <hc-form-upload type="list" :src="fileName" :h-props="hProps" @upload="formItemUpload" @change="formItemChange" />
                    </el-form-item>
                </el-form>
            </hc-card-item>
        </el-scrollbar>
        <HcUploadFile ref="HcUploadFileRef" @finish="HcUploadFileFinish" @success="uploadFileSuccess" />
    </hc-new-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { formValidate, getArrValue, 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: '',
    },
    infoData:{
        type: Object,
        default: () => ({}),
    },
})
//事件
const emit = defineEmits(['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 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 (Id.length > 0) {
        baseForm.value = info
        fileName.value = info?.fileList
        modalTitle.value = '开工预付款计量单修改'
    } else {
      
        baseForm.value = { fileList:[] }
        fileName.value = []
        modalTitle.value = '开工预付款计量单新增'
    }
}, { immediate: true })
//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})

//监听
watch(() => [
    props.ids,
], ([ids]) => {
    console.log('ids', ids)
}, { immediate: true })

//监听
watch(isShow, (val) => {
    if (val) {
        console.log('isShow', val)
        getKey1Data()
        getStartAmountData()
    }
})

//计量期
const key1Data = ref([])
const getKey1Data = async ()=>{
    const { error, code, data } = await periodApi.allPeriod({
       contractId:contractId.value,
       type:2,
    })
    if (!error && code === 200) {
        key1Data.value = getArrValue(data)
        if (key1Data.value.length > 0) {
            baseForm.value.meterPeriodId = key1Data.value[ key1Data.value.length - 1].id
        }
    } else {
        key1Data.value = []
    }
}

//基础表单
const baseFormRef = ref(null)
// const baseForm = ref({})
const baseFormRules = {
    meterPeriodId:{
        required: true,
        trigger: 'blur',
        message: '请选择材料计量期',
    },
}
const modalSaving = ref(false)
const modalSave = async () => {
 const res = await formValidate(baseFormRef.value)
 if (!res) {
    return false
 }
key1Data.value.forEach((ele)=>{
        if (ele.id === baseForm.value.meterPeriodId) {
            baseForm.value.periodName = ele.periodName
            baseForm.value.periodNumber = ele.periodNumber
        }
    })
    modalSaving.value = true
    if (ids.value.length < 1) {
        const { error, code, msg } = await orderApi.add({
        ...baseForm.value,
        contractId:contractId.value,
        projectId:projectId.value,
        })
        //判断状态
        modalSaving.value = false
        if (!error && code === 200) {
            window?.$message?.success(msg)
            
         
        }
    } else if (ids.value.length > 0) {
        const { error, code, msg } = await orderApi.update({
        ...baseForm.value,
        contractId:contractId.value,
        projectId:projectId.value,
        })
        //判断状态
        modalSaving.value = false
        if (!error && code === 200) {
            window?.$message?.success(msg)
            
         
        }
    }
   
    modalClose()
}

const modalClose = () => {
    isShow.value = false
    emit('close')
}

//改变计量金额
const changeMoney = (val)=>{
    //如果为空
    let momey = val
    const isMeter = isNumberReg(momey)
    if (isNullES(momey) || !isMeter) {
        momey = 0
        baseForm.value.meterMoney = momey
    }
}
//上传
const formItemUpload = () => {
    HcUploadFileRef.value?.selectFile()
}
const formItemChange = (src, index, list)=>{
    baseForm.value.fileList = list
}
const HcUploadFileRef = ref(null)

// 文件全部上传完成
// 文件全部上传完成
const HcUploadFileFinish = async (res) => {
 let arr = []
 res.forEach((ele)=>{
    const { pdfUrl } = ele.resData
    if (pdfUrl) {
        arr.push(ele.resData)
    }
  
 })
 arr.forEach((ele)=>{
    ele.fileName = ele.originalName
    ele.fileUrl = ele.link
    ele.filePdfUrl = ele.pdfUrl
    baseForm.value.fileList.push(ele)
 })

fileName.value = baseForm.value.fileList

  HcUploadFileRef?.value.setModalShow(false)
}

// 文件上传成功的回调
const uploadFileSuccess = ({ resData }) => {
    const { pdfUrl } = resData
    if (isNullES(pdfUrl)) {
        window.$message.warning('该文件不能生成pdf,请更换文件上传')
        HcUploadFileRef?.value.setModalShow(false)
        return
    }

}
</script>

<style scoped lang="scss">

</style>
