<template>
    <hc-new-dialog is-table widths="1200px" :show="isShow" :title="modalTitle" @save="modalSave" @close="modalClose">
        <div class="relative h-full flex">
            <div id="hc_modal_tree">
                <hc-card-item scrollbar>
                    <!-- <hc-lazy-tree :h-props="treeProps" @load="treeLoadNode" /> -->
                    <HcDataTree :h-props="treeProps" :datas="treeLoadNode" @node-tap="treeClick" />
                </hc-card-item>
            </div>
            <div id="hc_modal_form">
                <hc-card-item>
                    <el-form ref="baseFormRef" :model="baseForm" :rules="baseFormRules" label-position="top" label-width="auto">
                        <el-row :gutter="20">
                            <el-col :span="8">
                                <el-form-item label="材料到场编号：" prop="materialArriveNumber">
                                    <el-input v-model="baseForm.materialArriveNumber" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="合同材料：" prop="contractMaterialName">
                                    <el-input v-model="baseForm.contractMaterialName" disabled />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <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-col>
                            <el-col :span="8">
                                <el-form-item label="单价：" prop="price">
                                    <el-input v-model="baseForm.price" @change="calculatePrice" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="数量：" prop="meterAmount">
                                    <el-input v-model="baseForm.meterAmount" @change="calculateMount" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="计量金额：">
                                    <el-input v-model="baseForm.meterMoney" disabled />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="业务日期：" prop="businessDate">
                                    <el-date-picker v-model="baseForm.businessDate" class="block" format="YYYY-MM-DD" type="date" value-format="YYYY-MM-DD" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="材料来源：">
                                    <el-input v-model="baseForm.materialSource" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="材料是否符合要求：">
                                    <el-select v-model="baseForm.materialConform" block>
                                        <el-option label="是" :value="1" />
                                        <el-option label="否" :value="0" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="备料堆放地点：">
                                    <el-input v-model="baseForm.storagePlace" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="存储情况：">
                                    <el-input v-model="baseForm.storageStatus" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="存储方法是否符合要求：">
                                    <el-select v-model="baseForm.storageConform" block>
                                        <el-option label="是" :value="1" />
                                        <el-option label="否" :value="0" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="合格证号：">
                                    <el-input v-model="baseForm.certificate" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="16">
                                <el-form-item label="备注：">
                                    <el-input v-model="baseForm.remark" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <!-- 附件列表 -->
                    <div class="hc-flex my-5">
                        <div class="flex-1 text-[16px] text-blue">附件列表</div>
                        <div class="text-orange font-400">可上传 图片(png、jpg、jpeg)、Excel(xls、xlsx)、PDF、Word(doc、docx)文件</div>
                    </div>
                    <el-form :model="baseForm" label-position="top" style="overflow-y: auto;height: 150px;">
                        <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>
            </div>
        </div>
        <HcUploadFile ref="HcUploadFileRef" @finish="HcUploadFileFinish" @success="uploadFileSuccess" />
    </hc-new-dialog>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import contractApi from '~api/debit-pay/material/contract.js'
import periodApi from '~api/debit-pay/material/periods.js'
import orderApi from '~api/debit-pay/material/order.js'
import { formValidate, getArrValue, isNullES } from 'js-fast-way'
import { isNumberReg } from '~uti/tools'
import BigNumber from 'bignumber.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)

//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})
const baseForm = ref({})
const fileName = ref([])
const modalTitle = ref('材料计量单新增')
const hProps = ref({
    url: 'filePdfUrl',
    name: 'fileName',
})
//监听
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 })

//监听
watch(isShow, (val) => {
    if (val) {
        detailsModalShow()
    }
})
//计算计量金额
// const calculate = ()=>{
//     baseForm.value.meterMoney = baseForm.value?.meterAmount * baseForm.value?.price
// }
//数量改变计算计量数量
const calculateMount = (val)=>{
       //如果为空
    let mount = val
    const isMeter = isNumberReg(mount)
    if (isNullES(mount) || !isMeter) {
        mount = 0
        baseForm.value.meterAmount = mount
    }
    //计算计量金额
    baseForm.value.meterMoney = (BigNumber(baseForm.value?.price).multipliedBy(mount)).toString()
}
//单价改变计算计量金额
const calculatePrice = (val)=>{
       //如果为空
    let price = val
    const isMeter = isNumberReg(price)
    if (isNullES(price) || !isMeter) {
        price = 0
        baseForm.value.price = price
    }
    //计算计量金额
    baseForm.value.meterMoney = (BigNumber(baseForm.value?.meterAmount).multipliedBy(price)).toString()
}
const detailsModalShow = () => {
    nextTick(() => {
        window.$split(['#hc_modal_tree', '#hc_modal_form'], {
            sizes: [30, 70],
            snapOffset: 0,
            minSize: [170, 500],
        })
    })
    getKey1Data()
    getTreeData()
}
//计量期
const key1Data = ref([])
const getKey1Data = async ()=>{
    const { error, code, data } = await periodApi.allPeriod({
       contractId:contractId.value,
       type:1,
    })
    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 treeProps = {
    label: 'nodeName',
    children: 'children',
    isLeaf: 'hasChild',
}

//懒加载的数据
const treeLoadNode = ref([])
const getTreeData = async ()=>{
    const { error, code, data } = await contractApi.materialTree({
       contractId:contractId.value,
    })
    if (!error && code === 200) {
        treeLoadNode.value = getArrValue(data)
   
    } else {
        treeLoadNode.value = []
    }
}
const treeItem = ref({})
const treeClick = ({ node, data, keys })=>{
    treeItem.value = data
    baseForm.value.contractMaterialName = data.materialName
    baseForm.value.price = data.price
 
}



//基础表单
const baseFormRef = ref(null)
// const baseForm = ref({})
const baseFormRules = {
    materialArriveNumber: {
        required: true,
        trigger: 'blur',
        message: '请输入材料到场编号',
    },
    meterAmount: {
        required: true,
        trigger: 'blur',
        message: '请输入数量',
    },
    price: {
        required: true,
        trigger: 'blur',
        message: '请输入单价',
    },
    businessDate: {
        required: true,
        trigger: 'blur',
        message: '请输入业务日期',
    },
    meterPeriodId:{
        required: true,
        trigger: 'blur',
        message: '请选择材料计量期',
    },
    contractMaterialName:{
        required: true,
        trigger: 'blur',
        message: '请选择合同材料',
    },

}
const modalSaving = ref(false)
const modalSave = async () => {
    if (!treeItem.value?.id && ids.value.length < 1) {
        window.$message.warning('请先选择左侧节点')
        return
    }
    const res = await formValidate(baseFormRef.value)
    if (res) {
        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,
            contractMaterialId:treeItem.value?.id,
            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,
            contractMaterialId:treeItem.value?.id,
            projectId:projectId.value,
            })
            //判断状态
            modalSaving.value = false
            if (!error && code === 200) {
                window?.$message?.success(msg)
                
            
            }
        }
        modalClose()
    }
    
   
   
}
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
    }

}
//上传
const formItemUpload = () => {
    HcUploadFileRef.value?.selectFile()
}
const formItemChange = (src, index, list)=>{
    baseForm.value.fileList = list
}

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

<style scoped lang="scss">

</style>
