<template>
    <hc-new-dialog
        v-model="isShow" widths="90%" :is-table="isTable" :padding="false" title="合同计量单元修改"
        :loading="addNodeLoading" @save="modalSave" @close="closeDialog"
    >
        <hc-body scrollbar :contents="!isTable">
            <el-form ref="formRef" label-position="left" label-width="auto" :model="formModel" :rules="formRules">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="工程名称：">
                            <el-input v-model="formModel.nodeName" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="工程编号：">
                            <el-input v-model="formModel.nodeCode" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="节点类型：">
                            <el-select v-model="formModel.nodeType" block>
                                <el-option
                                    v-for="item in nodeOptions" :key="item.id" :label="item.dictValue"
                                    :value="item.dictKey"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="工程类型：">
                            <el-input v-model="formModel.engineeringTypeName" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="桩号类型：">
                            <el-select v-model="formModel.stakeType" block placeholder=" ">
                                <el-option
                                    v-for="item in stakeOptions" :key="item.id" :label="item.dictValue"
                                    :value="item.dictKey"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="起始桩号：">
                            <el-input v-model="formModel.startStake" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="结束桩号：">
                            <el-input v-model="formModel.endStake" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="是否增补：">
                            <!-- <el-select v-model="formModel.isSupplement" disabled block placeholder=" ">
                                <el-option label="是" :value="1" />
                                <el-option label="否" :value="0" />
                            </el-select> -->
                            <el-input v-model="formModel.isSupplementNmae" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="施工图金额：">
                            <el-input v-model="formModel.buildPictureMoney" disabled class="w-100">
                                <template #suffix>元</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="变更后金额：">
                            <el-input v-model="formModel.changeMoney" disabled class="w-100">
                                <template #suffix>元</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="合同图号：">
                            <el-input v-model="formModel.contractPicture" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="变更合同图号：">
                            <el-input v-model="formModel.changePicture" />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="isTable" :span="6">
                        <el-form-item label="未关联质保资料中期最高支付比列(%):">
                            <el-input
                                v-model="formModel.upPayRatio" 
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="isTable ? 18 : 24">
                        <el-form-item label="备注：">
                            <el-input
                                v-model="formModel.remarks" :autosize="{ minRows: 4, maxRows: 8 }"
                                type="textarea"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template v-if="isTable">
                <el-divider border-style="dashed" content-position="left">分解清单列表</el-divider>
                <hc-title>
                    <span class="text-sm text-orange">温馨提示：累计分解量 > 合同变更后量，整行文字红色</span>
                    <template #extra>
                        <el-button hc-btn type="primary" @click="addCheckListShow = true">添加</el-button>
                    </template>
                </hc-title>
                <div style="height: 400px;">
                    <hc-table
                        :column="tableColumn" :datas="tableData" is-new :index-style="{ width: 60 }"
                        :row-style="tableRowStyle" :is-stripe="false"
                    >
                        <template #buildPictureTotal="{ row }">
                            <hc-table-input v-model="row.buildPictureTotal" :disabled="row.citeStatus === 1" @change="changeBuildPictureTotal(row)" />
                        </template>
                        <template #upPayRatio="{ row }">
                            <hc-table-input v-model="row.upPayRatio" :disabled="row.citeStatus === 1" />
                        </template>
                        <template #action="{ row, index }">
                            <el-link v-if="row.citeStatus === 1" type="info" @click="delNoRow(row)">删除</el-link>
                            <el-link v-else type="danger" @click="delRow(row, index)">删除</el-link>
                        </template>
                    </hc-table>
                </div>
                <div class="mt-4 text-orange">
                    温馨提示：进行过变更的分解清单不允许修改编辑，分解清单编辑后，请重新下达零号变更台账
                </div>
            </template>
        </hc-body>
    </hc-new-dialog>
    <!-- 添加合同工程清单 -->
    <AddCheckList v-model="addCheckListShow" :ids="curTreeData.id" @finish="addCheckFinish" />
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { isNumberReg } from '~uti/tools'
import AddCheckList from './addCheckList.vue'
import unitApi from '~api/project/debit/contract/unit.js'
import { getDictionary } from '~api/other'
import { getArrValue, getObjValue, isArrIndex, isNullES } from 'js-fast-way'
import { delMessageV2 } from '~com/message/index.js'
import BigNumber from 'bignumber.js'

const props = defineProps({
    ids: {
        type: [String, Number],
        default: '',
    },
    isTable: {
        type: Boolean,
        default: false,
    },
    curTreeData: {
        default: () => ({}),
    },
})
//事件
const emit = defineEmits(['finish', 'close', 'getDetail'])

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

const ids = ref(props.ids)
const curTreeData = ref(props.curTreeData)
const isTable = ref(props.isTable)
const formModel = ref({})
const tableData = ref([])

//设置某一行的样式
const isCanSave = ref(false)
const tableRowStyle = ({ row }) => {
    let residueNum = new BigNumber(row.residueNum) //a
    let contract = new BigNumber('0') //b
    //a 大于 b = 1，a 等于 b = 0，a 小于 b = -1， a 或 b 的值异常时 = null
    const isCompared = residueNum.comparedTo(contract)
    if (isCompared === -1 || isCompared === null) {
        row.isCanSave = true
        return '--el-table-tr-bg-color: #fe0000; --el-table-row-hover-bg-color: #fe0000; color: white;'
    } else {
        row.isCanSave = false
    }
}

//获节点类型
const nodeOptions = ref([])
const getNodeType = async (id) => {
    const { data } = await unitApi.getNodeTypeListUpdate({
        id,
    })
    nodeOptions.value = getArrValue(data)
    nodeOptions.value.forEach((ele) => {
        ele.dictKey = Number(ele.dictKey)
    })
}
//获取桩号类型
const stakeOptions = ref([])
const getStakeype = async () => {
    const { data } = await getDictionary({
        code: 'meter_stake_type',
    })
    stakeOptions.value = getArrValue(data)
    stakeOptions.value.forEach((ele) => {
        ele.dictKey = Number(ele.dictKey)
    })
}
//监听
watch(() => [
    props.ids,
    props.isTable,
], ([Ids, tabs]) => {
    ids.value = Ids
    isTable.value = tabs
}, { immediate: true })

//监听
watch(() => props.curTreeData, (cur) => {
    curTreeData.value = cur
    formModel.value = cur
    formModel.value .isSupplementNmae = cur.isSupplement === 1 ? '是' : '否'
    
    // tableData.value = cur.decompositionList
    if (cur.id) {
        getNodeType(cur.id)
    }
}, {
    immediate: true,
    deep: true,
})
watch(() => props.ids, (id) => {
    tableData.value = getArrValue(props.curTreeData.decompositionList)
}, {
    immediate: true,
    deep: true,
})

/*watch(tableData, (val) => {
    if (val) {
        //计算变更后金额
        let sum1 = tableData.value.reduce((accumulator, current) => {
            if (current.changeTotal && current.currentPrice) {
                return accumulator + (current.changeTotal * current.currentPrice)
            }
            return accumulator
        }, 0)
        formModel.value.changeMoney = sum1
    }
}, { deep: true })*/

watch(isShow, (val) => {
    if (val) {
        // getNodeType()
        getStakeype()
        tableData.value = getArrValue(props.curTreeData.decompositionList)
    }
})

//弹窗表单
const formRef = ref(null)
// const formModel = ref({})
const formRules = ref({})

//列表
const addNodeLoading = ref(false)
const tableColumn = ref([
    { key: 'formNumber', name: '清单编号' },
    { key: 'formName', name: '清单名称' },
    { key: 'currentPrice', name: '单价(元)' },
    { key: 'contractTotal', name: '合同数量' },
    { key: 'changeTotal', name: '合同变更后数量' },
    { key: 'poseNum', name: '已分解量' },
    { key: 'residueNum', name: '分解剩余量' },
    { key: 'buildPictureTotal', name: '施工图数量' },
    { key: 'changeBuildPictureTotal', name: '施工图变更后数量' },
    { key: 'upPayRatio', name: '资料未齐全的最高支付比例（%）' },
    { key: 'action', name: '操作', width: 80, align: 'center' },
])

//计算数据
const changeBuildPictureTotal = (row) => {
    //如果为空
    let buildPictureTotal = row.buildPictureTotal
    const isMeter = isNumberReg(buildPictureTotal)
    if (isNullES(buildPictureTotal) || !isMeter) {
        buildPictureTotal = 0
    }
    //计算相关数量和金额
    nextTick(() => {
        //更新值
        row.buildPictureTotal = buildPictureTotal
        row.changeBuildPictureTotal = buildPictureTotal

        //计算数量
        // poseNum 已分解量, otherPoseNum 其他节点分解量, buildPictureTotal 施工图数量
        // poseNum = otherPoseNum + buildPictureTotal
        row.poseNum = (BigNumber(row.otherPoseNum).plus(buildPictureTotal)).toString()

        // residueNum 分解剩余量, changeTotal 变更后合同数量
        // residueNum = changeTotal - poseNum
        row.residueNum = (BigNumber(row.changeTotal).minus(row.poseNum)).toString()

        // buildPictureMoney 施工图金额
        // buildPictureMoney = buildPictureTotal * currentPrice（单价）
        row.buildPictureMoney = (BigNumber(buildPictureTotal).multipliedBy(row.currentPrice)).toString()

        // changeBuildPictureMoney 变更后施工图金额, changeBuildPictureTotal 变更后施工图数量
        // changeBuildPictureMoney = changeBuildPictureTotal * currentPrice（单价）
        row.changeBuildPictureMoney = (BigNumber(row.changeBuildPictureTotal).multipliedBy(row.currentPrice)).toString()

        //计算表单上的总金额
        let buildPictureMoney = 0, changeMoney = 0
        for (let i = 0; i < tableData.value.length; i++) {
            const item = tableData.value[i]
            buildPictureMoney = (BigNumber(buildPictureMoney).plus(item.buildPictureMoney)).toString()
            changeMoney = (BigNumber(changeMoney).plus(item.changeBuildPictureMoney)).toString()
        }
        formModel.value.buildPictureMoney = buildPictureMoney
        formModel.value.changeMoney = changeMoney
    })
}

const modalSave = async () => {
    isCanSave.value = isArrIndex(tableData.value, 'isCanSave', true)
    // if (isCanSave.value) {
    //     window.$message.warning('累计分解量 > 合同变更后量,不允许修改')
    //     return
    // }
    addNodeLoading.value = true
    formModel.value.decompositionList = tableData.value
    const { error, code, msg } = await unitApi.updateForm({
        ...formModel.value,
    })
    //判断状态
    addNodeLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success(msg)
    }
    emit('finish')
}
const closeDialog = () => {
    emit('close')
    isCanSave.value = false
}
const addCheckListShow = ref(false)
const addCheckFinish = async (val) => {
    addCheckListShow.value = false
    // emit('getDetail', { id: ids.value })
    await getTreeNodeDetail({ id: ids.value })
    for (let i = 0; i < nowTableData.value.length; i++) {
     for (let index = 0; index < tableData.value.length; index++) {
        const element = nowTableData.value[i]
        const element1 = tableData.value[index]
        if (element.id === element1.id) {
            nowTableData.value[i] = tableData.value[index]
        }
        
     }
    }
    tableData.value = nowTableData.value
  
}
const nowTableData = ref([])
const getTreeNodeDetail = async ({ id }) => {
    const { error, code, data } = await unitApi.getNodeDetail({ id })
    if (!error && code === 200) {
        curTreeData.value = getObjValue(data)
        nowTableData.value = curTreeData.value['decompositionList']
        
    } else {
     
        nowTableData.value = []
    }
}
//删除
const delRow = async (row, index) => {
    delMessageV2(async (action, instance, done) => {
        if (action === 'confirm') {
            instance.confirmButtonLoading = true
            await removeCon(row.id, index)
            instance.confirmButtonLoading = false
            done()
        } else {
            done()
        }
    })
}

//禁止删除
const delNoRow = () => {
    window.$messageBox({
        title: '提示',
        message: '该清单已被引用，不允许删除',
        type: 'warning',
    })
}

const removeCon = async (id, index) => {
    const { error, code } = await unitApi.removeInfo({
        formIds: id,
        meterId: ids.value,
    })
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
        tableData.value.splice(index, 1)
    }
}
</script>
