<template>
    <hc-new-dialog is-table widths="95%" :show="isShow" :title="`中间计量${dataId ? '修改' : '新增'}`" @save="addModalSave" @close="addModalClose">
        <div class="relative h-full flex">
            <div v-if="!dataId" :id="`hc_tree_card_${uuid}`" class="hc_tree_card_border relative">
                <hc-body scrollbar padding="0px">
                    <hc-lazy-tree :h-props="treeProps" tree-key="id" :auto-expand-keys="treeAutoExpandKeys" @load="treeLoadNode" @node-tap="treeNodeTap" />
                </hc-body>
            </div>
            <div :id="`hc_table_card_${uuid}`" class="relative flex-1">
                <hc-body scrollbar padding="0px">
                    <!-- 基础表单 -->
                    <hc-card-item>
                        <el-form ref="baseFormRef" :model="baseForm" :rules="baseFormRules" label-position="left" label-width="auto">
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="计量期：">
                                        <el-select v-model="baseForm.contractPeriodId" placeholder="选择计量期" filterable block @change="periodChange">
                                            <el-option v-for="item in period" :key="item.id" :label="item.periodNumber" :value="item.id" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="计量单编号：">
                                        <el-input v-model="baseForm.meterNumber" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <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-col>
                                <el-col :span="16">
                                    <el-form-item label="工程划分：">
                                        <el-input v-model="baseForm.engineerDivide" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="部位名称：">
                                        <el-input v-model="baseForm.partName" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="交工证书编号：">
                                        <el-input v-model="baseForm.certificateNumber" />
                                    </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="变更令：">
                                        <el-input v-model="baseForm.changeTokenNumber" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="收方单：">
                                        <el-input v-model="baseForm.debitFormId" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="16">
                                    <el-form-item label="草图文件：">
                                        <hc-form-upload :src="baseForm.pictureUrl" @upload="formUpload" @change="formUploadChange" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="24">
                                    <el-form-item label="计算式：">
                                        <el-input v-model="baseForm.calculateFormula" :autosize="{ minRows: 4, maxRows: 8 }" type="textarea" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </hc-card-item>
                    <!-- 收方清单列表 -->
                    <hc-card-item class="mt-3">
                        <template #header>
                            <span class="mr-3">计量清单列表</span>
                            <span class="text-orange font-400">温馨提示：超计,累计计量量> 变更后数量，分解清单超计整行红色</span>
                        </template>
                        <template #extra>
                            <el-button type="primary" text @click="addBillBaseModalClick">
                                <HcIcon name="add" />
                                <span>添加清单</span>
                            </el-button>
                        </template>
                        <hc-table is-new :index-style="{ width: 60 }" :is-stripe="false" :column="addTableColumn" :datas="addTableData" :row-style="addTableRowStyle">
                            <template #currentPrice="{ row }">
                                <hc-table-input v-model="row.currentPrice" disabled />
                            </template>
                            <template #changeTotal="{ row }">
                                <hc-table-input v-model="row.changeTotal" disabled />
                            </template>
                            <template #currentMeterTotal="{ row }">
                                <hc-table-input v-model="row.currentMeterTotal" @blur="currentMeterTotalBlur(row)" />
                            </template>
                            <template #containChangeTotal="{ row }">
                                <hc-table-input v-model="row.containChangeTotal" @blur="containChangeTotalBlur(row)" />
                            </template>
                            <template #currentMeterMoney="{ row }">
                                <hc-table-input v-model="row.currentMeterMoney" disabled />
                            </template>
                            <template #allMeterTotal="{ row }">
                                <hc-table-input v-model="row.allMeterTotal" disabled />
                            </template>
                            <template #action="{ index }">
                                <el-link type="danger" @click="delAddTableClick(index)">删除</el-link>
                            </template>
                        </hc-table>
                    </hc-card-item>
                    <!-- 附件列表 -->
                    <hc-card-item class="mt-3" title="附件列表">
                        <template #extra>
                            <span class="text-orange font-400">可上传 图片(png、jpg、jpeg)、Excel(xls、xlsx)、PDF、Word(doc、docx)文件</span>
                        </template>
                        <el-form :model="baseForm" label-position="left" label-width="auto">
                            <el-form-item label="上传附件">
                                <hc-form-upload type="list" :src="baseForm.fileList" :h-props="uploadFormProps" @upload="attachmentUpload" @change="attachmentUploadChange" />
                            </el-form-item>
                        </el-form>
                    </hc-card-item>
                </hc-body>
            </div>
        </div>
    </hc-new-dialog>

    <!-- 添加分解清单 -->
    <HcBillBaseModal v-model="addBillBaseModalShow" :ids="billBaseIds" :idn="nodeId" :period-id="baseForm.contractPeriodId" :contract-id="cid" @finish="finishChange" />

    <!-- 文件上传组件 -->
    <hc-upload-file
        ref="uploadFileRef"
        :echo-params="uploadFileParams"
        :options="uploadFileOptions"
        @success="uploadFileSuccess"
    />
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { getStoreValue } from '~src/utils/storage'
import { isNumberReg } from '~uti/tools'
import HcBillBaseModal from './addBillBaseModal.vue'
import { arrToId, deepClone, getArrValue, getObjValue, getRandom, isNullES } from 'js-fast-way'
import BigNumber from 'bignumber.js'
import { getHeader } from 'hc-vue3-ui'

import unitApi from '~api/project/debit/contract/unit'
import mainApi from '~api/debit-pay/admin/middlepay'

const props = defineProps({
    projectId: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
    allPeriods: {
        type: Array,
        default: () => ([]),
    },
    periodId: {
        type: [String, Number],
        default: '',
    },
    ids: {
        type: [String, Number],
        default: '',
    },
})

//事件
const emit = defineEmits(['finish', 'close'])
const uuid = getRandom(4)
const dataId = ref(props.ids)
const period = ref(props.allPeriods)
const period_id = ref(props.periodId)
const pid = ref(props.projectId)
const cid = ref(props.contractId)

//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})

//监听
watch(() => [
    props.projectId,
    props.contractId,
    props.allPeriods,
    props.periodId,
], ([projectId, contractId, periods, periodId]) => {
    period.value = periods
    pid.value = projectId
    cid.value = contractId
    period_id.value = periodId
    setBasePeriodForm(periodId)
}, { deep: true })

//监听
watch(() => props.ids, (id) => {
    dataId.value = id
}, { deep: true })

//监听
watch(isShow, (val) => {
    if (val) {
        if (dataId.value ) {
            getDataDetail()
        } else {
            setBasePeriodForm(period_id.value)
            setSplitRef()
        }
    } else {
        baseForm.value = { fileList: [], pictureUrl: '' }
    }
})

//初始化设置拖动分割线
const setSplitRef = () => {
    //配置参考： https://split.js.org/#/?direction=vertical&snapOffset=0
    nextTick(() => {
        window.$split(['#hc_tree_card_' + uuid, '#hc_table_card_' + uuid], {
            sizes: [20, 80],
            snapOffset: 0,
            minSize: [50, 500],
        })
    })
}

//基础表单
const baseFormRef = ref(null)
const baseForm = ref({ fileList: [], pictureUrl: '' })
const baseFormRules = {}

//获取数据详情
const getDataDetail = async () => {
    if (!dataId.value) return
    const { data } = await mainApi.getDetail({ id: dataId.value })
    const res = getObjValue(data)
    res.pictureUrl = res.pictureUrl ?? ''
    nodeId.value = res.contractUnitId ?? ''
    baseForm.value = res
    const formList = getArrValue(res.formList)
    for (let i = 0; i < formList.length; i++) {
        formList[i].webAllMeterTotal = deepClone(formList[i].allMeterTotal)
        formList[i].webCurrentMeterTotal = deepClone(formList[i].currentMeterTotal)
    }
    addTableData.value = formList
}

//数据格式
const treeProps = {
    label: 'nodeName',
    children: 'children',
    isLeaf: 'notExsitChild',
}

//懒加载的数据
const treeAutoExpandKeys = ref(getStoreValue('middlepay-tree-auto-expand-keys') || [])
const treeLoadNode = async ({ item, level }, resolve) => {
    let id = 0
    if (level !== 0) {
        const nodeData = getObjValue(item)
        id = nodeData?.id || ''
    }
    //获取数据
    const { data } = await unitApi.lazyTree({
        id: id,
        contractId: cid.value,
        contractPeriodId: period_id.value,
    })
    resolve(getArrValue(data))
}
const nodeId = ref('')
const treeNodeTap = ({ data }) => {
    nodeId.value = data.id
    baseForm.value.contractUnitId = data.id
    getNodeDivide(data.id)
    getNodeToken(data.id)
}

//获取工程划分
const getNodeDivide = async (nodeId) => {
    const { data } = await mainApi.getNodeDivide({ nodeId: nodeId })
    baseForm.value.engineerDivide = data ?? ''
}

//获取变更令
const getNodeToken = async (nodeId) => {
    const { data } = await mainApi.getNodeToken({ nodeId: nodeId })
    baseForm.value.changeTokenNumber = data ?? ''
}

//计量期被改变
const periodChange = () => {
    setBasePeriodForm(baseForm.value.contractPeriodId)
}

//计量期相关的数据
const setBasePeriodForm = (periodId) => {
    if (dataId.value) return
    treeAutoExpandKeys.value = getStoreValue('middlepay-tree-auto-expand-keys') || []
    const periods = period.value
    baseForm.value.contractPeriodId = periodId
    const periodData = periods.find((item) => item.id === periodId)
    baseForm.value.periodNumber = periodData.periodNumber
    baseForm.value.businessDate = periodData.endDate ?? null
    getMeterNumber(periodId)
}

//获取计量单编号
const getMeterNumber = async (periodId) => {
    const { data } = await mainApi.getMeterNumber({
        projectId: pid.value,
        contractId: cid.value,
        contractPeriodId: periodId,
    })
    baseForm.value.meterNumber = data ?? ''
}


//草图文件上传
const formUpload = () => {
    uploadFileParams.value = { type: '草图文件' }
    uploadFileOptions.value.accept = 'image/png,image/jpg,image/jpeg'
    uploadFileOptions.value.accept_tip = '图片(png、jpg、jpeg)'
    uploadFileOptions.value.size = 50
    uploadFileRef.value?.selectFile()
}
const formUploadChange = (url) => {
    baseForm.value.pictureUrl = url
}

//收方清单列表
const addTableColumn = ref([
    { key: 'formNumber', name: '清单编号', width: '120' },
    { key: 'formName', name: '清单名称', minWidth: '280' },
    { key: 'currentPrice', name: '单价(元)', width: '100' },
    { key: 'resolveTotal', name: '分解数量', width: '100' },
    { key: 'changeTotal', name: '变更后数量', width: '100' },
    { key: 'currentMeterTotal', name: '本期计量数量', width: '140' },
    { key: 'containChangeTotal', name: '含变更数量', width: '100' },
    { key: 'currentMeterMoney', name: '本期计量金额', width: '120' },
    { key: 'allMeterTotal', name: '累计计量量', width: '100' },
    { key: 'action', name: '操作', fixed: 'right', width: 80, align: 'center' },
])
const addTableData = ref([])

//计算本期计量金额
const currentMeterTotalBlur = (row) => {
    //如果为空
    let currentMeterTotal = row.currentMeterTotal
    const isMeter = isNumberReg(currentMeterTotal)
    if (isNullES(currentMeterTotal) || !isMeter) {
        currentMeterTotal = 0
    }
    //计算本期计量金额
    nextTick(() => {
        row.currentMeterTotal = currentMeterTotal
        row.currentMeterMoney = (BigNumber(currentMeterTotal).multipliedBy(row.currentPrice)).toString()
        row.allMeterTotal = (BigNumber(currentMeterTotal).plus(row.webCurrentMeterTotal)).toString()

        //计算总计量金额
        let meterMoney = 0
        for (let i = 0; i < addTableData.value.length; i++) {
            meterMoney = (BigNumber(meterMoney).plus(addTableData.value[i].currentMeterMoney)).toString()
        }
        baseForm.value.meterMoney = meterMoney
    })
}

//计算含变更数量
const containChangeTotalBlur = (row) => {
    let val = row.containChangeTotal
    const isMeter = isNumberReg(val)
    if (isNullES(val) || !isMeter) {
        val = 0
    }
    nextTick(() => {
        row.containChangeTotal = val
    })
}

//判断是否红色
const isCanSave = ref(false)
const addTableRowStyle = ({ row }) => {
    let allMeterTotal = new BigNumber(row.allMeterTotal) //a 累计计量量
    let changeTotal = new BigNumber(row.changeTotal) //b 变更后数量
    //a 大于 b = 1，a 等于 b = 0，a 小于 b = -1， a 或 b 的值异常时 = null
    const isCompared = allMeterTotal.comparedTo(changeTotal)
    if (isCompared === 1 || isCompared === null) {
        isCanSave.value = true
        return '--el-table-tr-bg-color: #fe0000; --el-table-row-hover-bg-color: #fe0000; color: white;'
    } else {
        isCanSave.value = false
    }
}

//删除清单
const delAddTableClick = (index) => {
    addTableData.value.splice(index, 1)
}

//添加分解单
const addBillBaseModalShow = ref(false)
const billBaseIds = ref('')
const addBillBaseModalClick = () => {
    addBillBaseModalShow.value = true
    billBaseIds.value = arrToId(addTableData.value)
}
//添加完成
const finishChange = (data) => {
    for (let i = 0; i < data.length; i++) {
        data[i].webAllMeterTotal = deepClone(data[i].allMeterTotal)
        data[i].webCurrentMeterTotal = deepClone(data[i].currentMeterTotal)
        addTableData.value.push(data[i])
    }
}

//附件上传
const uploadFormProps = {
    url: 'fileUrl',
    name: 'fileName',
}

const attachmentUpload = () => {
    uploadFileParams.value = { type: '附件文件' }
    uploadFileOptions.value.accept = ''
    uploadFileOptions.value.accept_tip = ''
    uploadFileOptions.value.size = null
    uploadFileRef.value?.selectFile()
}
const attachmentUploadChange = (a, b, fileList) => {
    baseForm.value.fileList = getArrValue(fileList)
}


//文件上传
const uploadFileRef = ref(null)
const uploadFileParams = ref({})
const uploadFileOptions = ref({
    headers: getHeader(),
    multiple: false,
})

// 文件上传成功的回调
const uploadFileSuccess = ({ echoParams, resData }) => {
    if (echoParams.type === '草图文件') {
        baseForm.value.pictureUrl = resData.link ?? ''
        uploadFileRef.value?.setModalShow(false)
    } else if (echoParams.type === '附件文件') {
        baseForm.value.fileList.push({
            contractId: cid.value,
            fileName: resData.originalName ?? '',
            filePdfUrl: resData.pdfUrl ?? '',
            fileUrl: resData.link ?? '',
        })
        uploadFileRef.value?.setModalShow(false)
    }
}

//保存
const addModalSave = async () => {
    // if (isCanSave.value) {
    //     window.$message.warning('累计计量量 > 变更后数量,不允许修改')
    //     return
    // }
    const form = baseForm.value
    form.formList = addTableData.value
    form.projectId = pid.value
    form.contractId = cid.value
    let res = {}
    if (dataId.value) {
        res = await mainApi.edit(form)
    } else {
        res = await mainApi.add(form)
    }
    //处理数据
    const { code, msg } = res
    if (code === 200) {
        window.$message.success('保存成功')
        addModalClose()
        emit('finish')
    } else {
        window.$message.error(msg ?? '保存失败')
    }
}

//关闭弹窗
const addModalClose = () => {
    isShow.value = false
    baseForm.value = { fileList: [], pictureUrl: '' }
    addTableData.value = []
    emit('close')
}
</script>
