<template>
    <hc-new-dialog is-table widths="90%" :show="isShow" :title="`变更令${dataId ? '修改' : '新增'}`" @save="addModalSave" @close="addModalClose">
        <div class="relative h-full flex">
            <div id="hc_add_dialog_tree_card">
                <hc-card-item title="工程部位" scrollbar>
                    <template #extra>
                        <el-link type="primary" @click="addChangeNode">添加</el-link>
                    </template>
                    <hc-lazy-tree show-checkbox tree-key="id" :h-props="treeProps" @load="treeLoadNode" @check="treeNodeCheck" />
                </hc-card-item>
            </div>
            <div id="hc_add_dialog_table_card">
                <el-scrollbar>
                    <!-- 基础表单 -->
                    <hc-card-item title="基础表单">
                        <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="变更令编号：" prop="changeNumber">
                                        <el-input v-model="baseForm.changeNumber" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="变更令名称：" prop="changeName">
                                        <el-input v-model="baseForm.changeName" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="变更发起单位：">
                                        <el-input v-model="baseForm.changeUnit" />
                                    </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-select v-model="baseForm.changeType" filterable block>
                                            <el-option v-for="item in typeData" :key="item.value" :label="item.label" :value="item.value" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="延长工期：">
                                        <el-input v-model="baseForm.lengthenDays" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="变更申请金额：">
                                        <el-input v-model="baseForm.changeMoney" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="设计完成时间：" prop="designDate">
                                        <el-date-picker v-model="baseForm.designDate" 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.realityChangeNumber" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="变更归类：">
                                        <el-select v-model="baseForm.changeClassify" filterable block>
                                            <el-option v-for="item in classifyData" :key="item.value" :label="item.label" :value="item.value" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="变更批复文号：">
                                        <el-input v-model="baseForm.changeApprovalNumber" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="变更批复日期：" prop="changeApprovalDate">
                                        <el-date-picker v-model="baseForm.changeApprovalDate" class="block" format="YYYY-MM-DD" type="date" value-format="YYYY-MM-DD" />
                                    </el-form-item>
                                </el-col>
                                <!-- el-col :span="24">
                                    <el-form-item class="input-link-item" label="引用预变更：">
                                        <el-input v-model="baseForm.key6" disabled />
                                        <el-link type="primary" @click="quoteClick">引用</el-link>
                                        <el-link type="danger">删除引用</el-link>
                                    </el-form-item>
                                </el-col -->
                                <el-col :span="24">
                                    <el-form-item label="变更原因：">
                                        <el-input v-model="baseForm.changeCause" :autosize="{ minRows: 4, maxRows: 8 }" type="textarea" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </hc-card-item>
                    <!-- 变更申请部位 -->
                    <hc-card-item title="变更申请部位" class="mt-3">
                        <hc-table :column="tableColumn" :datas="tableData" is-new is-current-row :index-style="{ width: 60 }" @row-click="rowChangeNodeClick">
                            <template #contractPicture="{ row }">
                                <hc-table-input v-model="row.contractPicture" />
                            </template>
                            <template #action="{ index }">
                                <el-link type="danger" @click="delChangeNode(index)">删除</el-link>
                            </template>
                        </hc-table>
                    </hc-card-item>
                    <!-- 变更申请清单 -->
                    <hc-card-item title="变更申请清单" class="mt-3">
                        <template #extra>
                            <el-link type="primary" @click="changeShowClick">添加</el-link>
                        </template>
                        <div class="hc-table-ref-box no-border">
                            <el-table class="w-full" :data="tableData[tableIndex]?.formList" row-key="id" height="100%" highlight-current-row border>
                                <el-table-column type="index" label="序号" />
                                <el-table-column prop="formNumber" label="清单编号" />
                                <el-table-column prop="formName" label="清单名称" />
                                <el-table-column prop="currentPrice" label="单价" />
                                <el-table-column label="数量" align="center">
                                    <el-table-column prop="contractTotal" label="变更前" />
                                    <el-table-column prop="currentChangeTotal" label="变更增减">
                                        <template #default="{ row }">
                                            <hc-table-input v-model="row.currentChangeTotal" @blur="currentChangeTotalBlur(row)" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="changeTotal" label="变更后" />
                                </el-table-column>
                                <el-table-column label="金额" align="center">
                                    <el-table-column prop="contractMoney" label="变更前" />
                                    <el-table-column prop="currentChangeMoney" label="变更增减" />
                                    <el-table-column prop="changeMoney" label="变更后" />
                                </el-table-column>
                                <el-table-column prop="action" label="操作" width="80" align="center">
                                    <template #default="scope">
                                        <el-link type="danger" @click="tableFormListDel(scope.$index)">删除</el-link>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </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>
                </el-scrollbar>
            </div>
        </div>

        <!-- 变更申请清单 -->
        <ChangeRequest v-model="isChangeShow" :ids="changeIds" :tree-id="changeNodeItem.id" :contract-id="contractId" @finish="changeNodeFinish" />

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

<script setup>
import { nextTick, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { getDictionaryData, isNumberReg } from '~uti/tools'
import { arrIndex, arrToKey, formValidate, getArrValue, getObjValue, isArray, isNullES } from 'js-fast-way'
import ChangeRequest from './changeRequest.vue'
import unitApi from '~api/project/debit/contract/unit'
import mainApi from '~api/alter/admin/order'
import { getHeader } from 'hc-vue3-ui'
import BigNumber from 'bignumber.js'

const props = defineProps({
    ids: {
        type: [String, Number],
        default: '',
    },
})

//事件
const emit = defineEmits(['finish', 'close'])

const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId || '')
const contractId = ref(useAppState.getContractId || '')

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

//监听
const dataId = ref(props.ids)
watch(() => props.ids, (ids) => {
    dataId.value = ids
}, { immediate: true })

//监听
watch(isShow, (val) => {
    if (val) {
        setSplitRef()
        getMeterChangeClassify()
        getMeterChangeType()
        getTableDetail()
    }
})

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

//计量变更归类
const classifyData = ref([])
const getMeterChangeClassify = async () => {
    classifyData.value = await getDictionaryData('meter_change_classify')
}

//计量变更类型
const typeData = ref([])
const getMeterChangeType = async () => {
    typeData.value = await getDictionaryData('meter_change_type')
}

//获取详情
const getTableDetail = async () => {
    if (isNullES(dataId.value)) return
    const { data } = await mainApi.getDetail({ id: dataId.value })
    const info = getObjValue(data)
    baseForm.value = info
    tableData.value = getArrValue(info.nodeList)
}

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

//懒加载的数据
const treeLoadNode = async ({ item, level }, resolve) => {
    let id = 0
    if (level !== 0) {
        const nodeData = getObjValue(item)
        id = nodeData?.id || ''
    }
    //获取数据
    const { data } = await unitApi.lazyTree({
        contractId: contractId.value,
        id: id,
    })
    resolve(getArrValue(data))
}

//节点树被点击
const treeCheckKeys = ref('')
const treeNodeCheck = (_, { checkedKeys }) => {
    treeCheckKeys.value = checkedKeys?.join() ?? ''
}

//基础表单
const baseFormRef = ref(null)
const baseForm = ref({ fileList: [] })
const baseFormRules = {
    changeNumber: {
        required: true,
        trigger: 'blur',
        message: '请输入变更令编号',
    },
    changeName: {
        required: true,
        trigger: 'blur',
        message: '请输入变更令名称',
    },
    businessDate: {
        required: true,
        trigger: 'blur',
        message: '请选择业务日期',
    },
    designDate: {
        required: true,
        trigger: 'blur',
        message: '请选择设计完成时间',
    },
    changeApprovalDate: {
        required: true,
        trigger: 'blur',
        message: '请选择变更批复日期',
    },
}

//变更申请部位列表
const tableColumn = ref([
    { key: 'nodeName', name: '工程名称' },
    { key: 'nodeUrl', name: '节点路径' },
    { key: 'contractPicture', name: '合同图号' },
    { key: 'changeMoney', name: '变更后金额(元)' },
    { key: 'isSupplementName', name: '是否增补' },
    { key: 'action', name: '操作', width: 80, align: 'center' },
])
const tableData = ref([])
const addChangeNode = async () => {
    const nodeId = treeCheckKeys.value ?? ''
    if (isNullES(nodeId)) {
        window.$message.warning('请先选择节点')
        return
    }
    const { data } = await mainApi.getChangeNode({
        projectId: projectId.value,
        contractId: contractId.value,
        changeIds: tableData.value.map((item) => item.id).join(),
        ids: nodeId,
    })
    const newArr = getArrValue(data)
    tableData.value.push(...newArr)
}

//删除变更申请部位
const delChangeNode = (index) => {
    tableData.value.splice(index, 1)
    tableIndex.value = -1
}

//变更申请部位 行被点击
const changeNodeItem = ref({})
const tableIndex = ref(-1)
const rowChangeNodeClick = ({ row }) => {
    const index = arrIndex(tableData.value, 'id', row.id)
    if (!isArray(row.formList)) {
        tableData.value[index].formList = []
    }
    // tableIndex.value = index
    tableIndex.value = index
    changeNodeItem.value = row
}

//删除变更申请清单
const tableFormListDel = (index) => {
    tableData.value[tableIndex.value].formList.splice(index, 1)
    getFormList()
}

//变更清单的添加弹窗
const isChangeShow = ref(false)
const changeIds = ref('')
const changeShowClick = () => {
    if (isNullES(changeNodeItem.value['id'])) {
        window.$message.warning('请先选择变更申请部位')
        return false
    }
    changeIds.value = arrToKey(tableData.value[tableIndex.value].formList, 'id')
    isChangeShow.value = true
}

//确认选择完成
const changeNodeFinish = (data) => {
    tableData.value[tableIndex.value].formList.push(...data)
    getFormList()
}

//变更清单增减
const currentChangeTotalBlur = (row) => {
    //如果为空
    let val = row.currentChangeTotal
    const isMeter = isNumberReg(val)
    if (isNullES(val) || !isMeter) {
        val = 0
    }
    const changeNum = (BigNumber(row.contractTotal).plus(val)).toString()
    if (changeNum < 0) {
        window.$message.warning('变更增减数量不能小于变更前数量')
        const contract = '-' + row.contractTotal
        nextTick(() => {
            //设置数量
            row.currentChangeTotal = contract
            row.changeTotal = 0
            //计算金额
            row.currentChangeMoney = (BigNumber(contract).multipliedBy(row.currentPrice)).toString()
            row.changeMoney = 0
            getFormList()
        })
    } else {
        nextTick(() => {
            //设置数量
            row.changeTotal = changeNum
            row.currentChangeTotal = val
            //计算金额
            row.currentChangeMoney = (BigNumber(val).multipliedBy(row.currentPrice)).toString()
            row.changeMoney = (BigNumber(changeNum).multipliedBy(row.currentPrice)).toString()
            getFormList()
        })
    }
}

//获取变更清单总额
const getFormList = () => {
    let total = 0, table = tableData.value
    for (let i = 0; i < table.length; i++) {
        const item = table[i]
        if (!isArray(item.formList)) {
            item.formList = []
        }
        let changeMoney = 0
        for (let j = 0; j < item.formList.length; j++) {
            const form = item.formList[j]
            total = (BigNumber(total).plus(form.currentChangeMoney)).toString()
            //变更后的金额统计
            changeMoney = (BigNumber(changeMoney).plus(form.changeMoney)).toString()
        }
        item.changeMoney = changeMoney
    }
    //更新数据
    nextTick(() => {
        tableData.value = table
        baseForm.value.changeMoney = total
    })
}


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

const attachmentUpload = () => {
    uploadFileRef.value?.selectFile()
}
const attachmentUploadChange = (a, b, fileList) => {
    baseForm.value.fileList = getArrValue(fileList)
}

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

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

//保存
const addModalSave = async () => {
    const isValidate = await formValidate(baseFormRef.value)
    if (!isValidate) return false
    const form = baseForm.value, table = tableData.value
    if (table.length <= 0) {
        window.$message.warning('请先添加变更申请部位')
        return false
    }
    form.nodeList = table
    form.projectId = projectId.value
    form.contractId = contractId.value
    //发起请求
    let res = {}
    if (isNullES(dataId.value)) {
        //新增
        res = await mainApi.add(form)
    } else {
        //修改
        res = await mainApi.edit(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: [] }
    tableData.value = []
    dataId.value = ''
    emit('close')
}
</script>
