<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="计量期：">
                        <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-number v-model="baseForm.meterMoney" :controls="false" :min="0" :precision="2" style="width: 100%;" />
                    </el-form-item>
                    <el-form-item label="开工预付款总额：">
                        <el-input-number v-model="baseForm.startPayAmount" :controls="false" :min="0" :precision="2" style="width: 100%;" 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" />
    </hc-new-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { arrToKey, getArrValue, getObjValue } from 'js-fast-way'
import periodApi from '~api/debit-pay/material/periods.js'
import orderApi from '~api/debit-pay/start-work/order.js'
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 = {}
        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 = {}
const modalSaving = ref(false)
const modalSave = async () => {
console.log(baseForm.value, 'baseForm.value')
    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 formItemUpload = () => {
    HcUploadFileRef.value?.selectFile()
}
const formItemChange = (src, index, list)=>{
    baseForm.value.fileList = list
}
const HcUploadFileRef = ref(null)

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

  HcUploadFileRef?.value.setModalShow(false)
}
</script>

<style scoped lang="scss">

</style>
