<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="单价：">
                                    <el-input v-model="baseForm.price" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="数量：">
                                    <el-input v-model="baseForm.meterAmount" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="计量金额：">
                                    <el-input v-model="baseForm.meterMoney" />
                                </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
                                v-model="baseForm.fileList"
                                is-res
                                :options="{
                                    type: 'list',
                                    props: hProps,
                                    isArr: true,
                                    num: 0,
                                }"
                                @success="uploadFileSuccess"
                                @change="HcUploadFileFinish"
                            />
                        </el-form-item>
                    </el-form>
                </hc-card-item>
            </div>
        </div>
    </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, getObjValue, 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: () => ({}),
    },
    meterPeriodId: {
        type: [String, Number],
        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',
})
//监听
const dataPid = ref(props.meterPeriodId)
watch(() => [props.ids, props.infoData, props.meterPeriodId], ([Id, info, pid]) => {
    ids.value = Id
    dataPid.value = pid
    infoData.value = info
    if (!isNullES(Id)) {
        baseForm.value = info
        fileName.value = info?.fileList
        modalTitle.value = '材料计量单编辑'
    } else {
        baseForm.value = { fileList:[], meterPeriodId: pid }
        fileName.value = []
        modalTitle.value = '材料计量单新增'
    }
}, { immediate: true })

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

const detailsModalShow = () => {
    nextTick(() => {
        window.$split(['#hc_modal_tree', '#hc_modal_form'], {
            sizes: [30, 70],
            snapOffset: 0,
            minSize: [170, 500],
        })
    })
    baseForm.value.meterPeriodId = dataPid.value
    getKey1Data()
    getTreeData()
}
//计量期
const key1Data = ref([])
const getKey1Data = async ()=>{
    const { error, code, data } = await periodApi.allPeriod({
       contractId:contractId.value,
       type:1,
    })
    key1Data.value = getArrValue(data)
}

//数据格式
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 {
                window.$message.error(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)


            } else {
                window.$message.error(msg ?? '操作失败')
            }
        }
        modalClose()
    }
}

// 文件全部上传完成
const HcUploadFileFinish = async (data) => {
    fileName.value = data
}

// 文件上传成功的回调
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 ?? '',
        })
    }
}

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

<style scoped lang="scss">

</style>
