<template>
    <div v-loading="isLoading" class="hc-task-form">
        <!-- 基础表单 -->
        <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-input v-model="baseForm.contractPeriodIdName" disabled />
                        </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" disabled />
                        </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" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="交工证书：">
                            <el-input v-model="baseForm.certificateNumber" disabled />
                        </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 v-if="baseForm.pictureUrl" :src="baseForm.pictureUrl" />
                            <div v-else class="form-item-div">暂无文件</div>
                        </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" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </hc-card-item>
        <!-- 收方清单列表 -->
        <hc-card-item class="mt-3">
            <template #header>
                <span class="mr-3 text-[13px]">计量清单</span>
                <span class="text-[13px] text-orange font-400">温馨提示：超计,累计计量量> 变更后数量，分解清单超计整行红色</span>
            </template>
            <template #extra>
                <el-link type="primary" :disabled="!isEdits || tableInfo.status === 2" @click="addBillModalClick">
                    <hc-icon name="add" />
                    <span>添加清单</span>
                </el-link>
            </template>
            <hc-table is-new :index-style="{ width: 60 }" :is-stripe="false" :column="tableColumn" :datas="tableData" :row-style="tableRowStyle">
                <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" :disabled="!isEdits || tableInfo.status === 2" @blur="currentMeterTotalBlur(row)" />
                </template>
                <template #containChangeTotal="{ row }">
                    <hc-table-input v-model="row.containChangeTotal" :disabled="!isEdits || tableInfo.status === 2" @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="{ row, index }">
                    <el-link type="danger" :disabled="!isEdits || tableInfo.status === 2" @click="delAddTableClick(row, index)">删除</el-link>
                </template>
            </hc-table>
        </hc-card-item>
        <!-- 附件列表 -->
        <hc-card-item class="mt-3" title="附件列表">
            <template #extra>
                <span class="text-[13px] 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" is-del @upload="attachmentUpload" @change="attachmentUploadChange" @del="attachmentUploadDel" />
                </el-form-item>
            </el-form>
        </hc-card-item>
        <!-- 添加分解清单 -->
        <HcBillBase v-model="addBillBaseShow" :info="taskInfo" :table="tableInfo" :ids="billBaseIds" :project-id="projectId" :contract-id="contractId" @finish="finishChange" />
        <!-- 文件上传组件 -->
        <hc-upload-file ref="uploadFileRef" :options="uploadFileOptions" @success="uploadFileSuccess" />
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import HcBillBase from './addBillBase.vue'
import mainApi from '~api/tasks/hc-data'
import BigNumber from 'bignumber.js'
import { getHeader } from 'hc-vue3-ui'
import { delMessage, isNumberReg } from '~uti/tools'
import { arrToId, getArrValue, getObjVal, getObjValue, isNullES } from 'js-fast-way'

const props = defineProps({
    isEdit: {
        type: Boolean,
        default: true,
    },
    info: {
        type: Object,
        default: () => ({}),
    },
    table: {
        type: Object,
        default: () => ({}),
    },
})

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

//监听可否编辑
const isEdits = ref(props.isEdit)
watch(() => props.isEdit, (val) => {
    isEdits.value = val
}, { immediate: true, deep: true })

//监听数据
watch(() => [
    props.table,
    props.info,
], ([table, row]) => {
    setTaskInfo(table, row)
}, { deep: true })

//渲染完成
onMounted(() => {
    setTaskInfo(props.table, props.info)
})

//设置任务信息
const taskInfo = ref({})
const tableInfo = ref({})
const setTaskInfo = (table, row) => {
    tableInfo.value = table
    taskInfo.value = row
    if (getObjVal(table) && getObjVal(row)) {
        getDataDetail()
    }
}

//获取任务数据信息详情
const isLoading = ref(false)
const getDataDetail = async () => {
    const id = taskInfo.value.id
    const dataId = tableInfo.value.id
    const { data } = await mainApi.getDataDetail({ id, dataId })
    //转换数据
    const { associatedDataInfoList, attachmentFormTask, basicsInfo } = getObjValue(data)
    tableData.value = getArrValue(associatedDataInfoList) //清单列表
    baseForm.value = getObjValue(basicsInfo) //表单信息
    baseForm.value.fileList = getArrValue(attachmentFormTask) //附件列表
}

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

//清单表格
const tableColumn = 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 tableData = ref([])

//清单样式
const isCanSave = ref(false)
const tableRowStyle = ({ 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 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.otherMeterTotal)).toString()
        //计算总计量金额
        let meterMoney = 0, table = tableData.value
        for (let i = 0; i < table.length; i++) {
            meterMoney = (BigNumber(meterMoney).plus(table[i].currentMeterMoney)).toString()
        }
        baseForm.value.meterMoney = meterMoney

        //计算是否超计
        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) {
            console.log('超计了')
        } else {
            meterTableUpdate(row)
        }
    })
}

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

//清单数据修改
const meterTableUpdate = async (form) => {
    const { error, msg, code } = await mainApi.tableUpdate({
        ...form,
        taskId: taskInfo.value.id,
    })
    if (!error && code === 200) {
        window.$message.success('更新成功')
    } else {
        window.$message.error(msg ?? '更新失败')
    }
}

//删除清单
const delAddTableClick = (row, index) => {
    delMessage(async () => {
        const { code, msg } = await mainApi.tableRemove({
            projectId: projectId.value,
            contractId: contractId.value,
            dataId: tableInfo.value.id,
            taskId: taskInfo.value.id,
            middleMeterInventoryFormId: row.taskDetailId,
            changeFormId: '',
            changeNodeId: '',
            type: '',
        })
        if (code === 200) {
            window.$message.success('删除成功')
            tableData.value.splice(index, 1)
        } else {
            window.$message.error(msg ?? '删除失败')
        }
    })
}

//添加计量清单
const addBillBaseShow = ref(false)
const billBaseIds = ref('')
const addBillModalClick = () => {
    addBillBaseShow.value = true
    billBaseIds.value = arrToId(tableData.value)
}

//添加计量清单完成
const finishChange = () => {
    getDataDetail()
}

//文件上传
const uploadFileRef = ref(null)
const uploadFileOptions = ref({
    headers: getHeader(),
    multiple: false,
})
const uploadFormProps = {
    url: 'filePdfUrl',
    name: 'fileName',
}

const attachmentUpload = () => {
    if (isEdits.value || tableInfo.value.status !== 2) {
        uploadFileRef.value?.selectFile()
    } else {
        window.$message.error('当前状态不可上传')
    }
}
const attachmentUploadChange = (a, b, fileList) => {
    baseForm.value.fileList = getArrValue(fileList)
}

// 文件上传成功的回调
const uploadFileSuccess = async ({ resData }) => {
    const { pdfUrl } = resData
    if (isNullES(pdfUrl)) {
        window.$message.warning('该文件不能生成pdf,请更换文件上传')
        uploadFileRef.value?.setModalShow(false)
        return
    }
    baseForm.value.fileList.push({
        contractId: contractId.value,
        fileName: resData.originalName ?? '',
        filePdfUrl: resData.pdfUrl ?? '',
        fileUrl: resData.link ?? '',
        taskId: taskInfo.value.id,
    })
    uploadFileRef.value?.setModalShow(false)
    //发起请求
    const dataId = tableInfo.value.id
    const { error, code, msg } = await mainApi.taskUploadFile({
        projectId: projectId.value,
        contractId: contractId.value,
        fileList: baseForm.value.fileList,
        taskId: taskInfo.value.id,
        dataId,
    })
    if (!error && code === 200) {
        window.$message.success('上传成功')
    } else {
        window.$message.error(msg ?? '上传失败')
    }
}

//删除文件
const attachmentUploadDel = ({ file }, resolve) => {
    if (!isEdits.value) {
        window.$message.error('当前状态不可删除')
        return
    }
    delMessage(async () => {
        const { error, code, msg } = await mainApi.removeFile({
            id: file.id,
            taskId: taskInfo.value.id,
        })
        if (!error && code === 200) {
            resolve(true)
        } else {
            window.$message.error(msg ?? '删除失败')
            resolve(false)
        }
    })
}
</script>

<style lang="scss" scoped>
.hc-task-form {
    position: relative;
}
</style>
