<template>
    <div 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="变更令编号：" prop="changeNumber">
                            <el-input
                                v-model="baseForm.changeNumber" :disabled="!isEdits || tableInfo.status === 2"
                                @blur="currentInputBlur('changeNumber')" @focus="currentInputFocus('changeNumber')"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="变更令名称：" prop="changeName">
                            <el-input
                                v-model="baseForm.changeName" :disabled="!isEdits || tableInfo.status === 2"
                                @blur="currentInputBlur('changeName')" @focus="currentInputFocus('changeName')"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="变更发起单位：">
                            <el-input
                                v-model="baseForm.changeUnit" :disabled="!isEdits || tableInfo.status === 2"
                                @blur="currentInputBlur('changeUnit')" @focus="currentInputFocus('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" :disabled="!isEdits || tableInfo.status === 2"
                                @blur="currentInputBlur('businessDate')" @focus="currentInputFocus('businessDate')"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="变更类型：">
                            <el-select
                                v-model="baseForm.changeType" filterable block :disabled="!isEdits || tableInfo.status === 2"
                                @blur="currentInputBlur('changeType')" @focus="currentInputFocus('changeType')"
                            >
                                <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" :disabled="!isEdits || tableInfo.status === 2"
                                @blur="currentInputBlur('lengthenDays')" @focus="currentInputFocus('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" :disabled="!isEdits || tableInfo.status === 2"
                                @blur="currentInputBlur('designDate')" @focus="currentInputFocus('designDate')"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="实际变更桩号：">
                            <el-input
                                v-model="baseForm.realityChangeNumber" :disabled="!isEdits || tableInfo.status === 2"
                                @blur="currentInputBlur('realityChangeNumber')" @focus="currentInputFocus('realityChangeNumber')"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="变更归类：">
                            <el-select
                                v-model="baseForm.changeClassify" filterable block :disabled="!isEdits || tableInfo.status === 2"
                                @blur="currentInputBlur('changeClassify')" @focus="currentInputFocus('changeClassify')"
                            >
                                <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" :disabled="!isEdits || tableInfo.status === 2"
                                @blur="currentInputBlur('changeApprovalNumber')" @focus="currentInputFocus('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" :disabled="!isEdits || tableInfo.status === 2"
                                @blur="currentInputBlur('changeApprovalDate')" @focus="currentInputFocus('changeApprovalDate')"
                            />
                        </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"
                                :disabled="!isEdits || tableInfo.status === 2" @blur="currentInputBlur('changeCause')"
                                @focus="currentInputFocus('changeCause')"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </hc-card-item>
        <!-- 变更申请部位 -->
        <hc-card-item title="变更申请部位" class="mt-3">
            <hc-table ref="tableRef1" :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" :disabled="!isEdits || tableInfo.status === 2"
                        @focus="meterInputFocus(row)" @blur="meterInputBlur(row)"
                    />
                </template>
                <template #action="{ row, index }">
                    <el-link type="danger" @click="delChangeNode(row)">删除</el-link>
                </template>
            </hc-table>
        </hc-card-item>
        <!-- 变更申请清单 -->
        <hc-card-item title="变更申请清单" class="mt-3">
            <template #extra>
                <el-link type="primary" :disabled="!isEdits || tableInfo.status === 2" @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" :disabled="!isEdits || tableInfo.status === 2"
                                    @focus="totalInputFocus(row)" @blur="totalInputBlur(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="{ row }">
                            <el-link type="danger" @click="tableFormListDel(row)">删除</el-link>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </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>
        <!-- 变更申请清单 -->
        <ChangeRequest v-model="isChangeShow" :info="changeNodeInfo" @finish="changeNodeFinish" />
        <!-- 文件上传组件 -->
        <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 ChangeRequest from './changeRequest.vue'
import { delMessage, getDictionaryData, isNumberReg } from '~uti/tools'
import { arrIndex, arrToKey, getArrValue, getObjVal, getObjValue, isArray, isNullES } from 'js-fast-way'
import { getHeader } from 'hc-vue3-ui'
import mainApi from '~api/tasks/hc-data'

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)) {
        getMeterChangeClassify()
        getMeterChangeType()
        getDataDetail()
    }
}

//计量变更归类
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 isLoading = ref(false)
const getDataDetail = async () => {
    const id = taskInfo.value.id
    const dataId = tableInfo.value.id
    const { data } = await mainApi.getDataDetail({ id, dataId })
    //转换数据
    const { changeTokenFormVO, attachmentFormTask } = getObjValue(data)
    const res = getObjValue(changeTokenFormVO)
    baseForm.value = res //表单信息
    baseForm.value.fileList = getArrValue(attachmentFormTask) //附件列表
    const nodeList = getArrValue(res.nodeList)
    tableData.value = nodeList //部位列表
    if (nodeList.length > 0) {
        rowChangeNodeClick({ row: nodeList[0] })
        tableRef1.value?.tableRef?.setCurrentRow(nodeList[0])
        changeNodeItem.value = nodeList[0]
        tableIndex.value = 0
    }
}

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

//基础表单的输入框获得焦点
const currentBaseForm = ref('')
const currentInputFocus = (key) => {
    currentBaseForm.value = baseForm.value[key]
}

//基础表单的输入框失去焦点
const currentInputBlur = async (key) => {
    if (currentBaseForm.value === baseForm.value[key]) {
        return false
    }
    //处理数据
    let form = {
        id: baseForm.value.id,
        taskId: taskInfo.value.id,
    }
    form[key] = baseForm.value[key]
    const { error, msg, code } = await mainApi.changeTokenFromUpdate(form)
    if (!error && code === 200) {
        window.$message.success('更新成功')
    } else {
        window.$message.error(msg ?? '更新失败')
    }
}

//清单表格
const tableRef1 = ref(null)
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 currentPicture = ref('')
const meterInputFocus = (row) => {
    currentPicture.value = row.contractPicture
}

//合同图号的输入框失去焦点
const meterInputBlur = async (row) => {
    if (currentPicture.value === row.contractPicture) {
        return false
    }
    //处理数据
    const { error, msg, code } = await mainApi.changeTokenMeterUpdate({
        primaryKeyId: row.primaryKeyId,
        taskId: taskInfo.value.id,
        contractPicture: row.contractPicture,
    })
    if (!error && code === 200) {
        window.$message.success('更新成功')
    } else {
        window.$message.error(msg ?? '更新失败')
    }
}

//删除变更申请部位
const delChangeNode = (row) => {
    delMessage(async () => {
        const { code, msg } = await mainApi.remove({
            projectId: projectId.value,
            contractId: contractId.value,
            dataId: tableInfo.value.id,
            taskId: taskInfo.value.id,
            middleMeterInventoryFormId: '',
            changeNodeId: row.primaryKeyId,
            changeFormId: '',
            type: 1,
        })
        if (code === 200) {
            window.$message.success('删除成功')
            getDataDetail()
        } else {
            window.$message.error(msg ?? '删除失败')
        }
    })
}

//变更申请部位 行被点击
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
    changeNodeItem.value = row
}

//删除变更申请清单
const tableFormListDel = (row) => {
    delMessage(async () => {
        const { primaryKeyId } = changeNodeItem.value
        const { code, msg } = await mainApi.tableRemove({
            projectId: projectId.value,
            contractId: contractId.value,
            dataId: tableInfo.value.id,
            taskId: taskInfo.value.id,
            middleMeterInventoryFormId: '',
            changeFormId: row.primaryKeyId,
            changeNodeId: primaryKeyId,
            type: 2,
        })
        if (code === 200) {
            window.$message.success('删除成功')
            getDataDetail()
        } else {
            window.$message.error(msg ?? '删除失败')
        }
    })
}

//变更清单的添加弹窗
const isChangeShow = ref(false)
const changeNodeInfo = ref({})
const changeShowClick = () => {
    const { id, primaryKeyId } = changeNodeItem.value
    if (isNullES(id)) {
        window.$message.warning('请先选择变更申请部位')
        return false
    }
    //处理数据
    const ids = arrToKey(tableData.value[tableIndex.value].formList, 'id')
    changeNodeInfo.value = {
        ids: ids,
        treeId: id ?? '',
        primaryKeyIdMeter: primaryKeyId ?? '',
        dataId: tableInfo.value.id ?? '',
        taskId: taskInfo.value.id ?? '',
    }
    nextTick(() => {
        isChangeShow.value = true
    })
}

//确认选择完成
const changeNodeFinish = () => {
    getDataDetail()
}

//变更增减的输入框获得焦点
const currentChangeTotal = ref('')
const totalInputFocus = (row) => {
    currentChangeTotal.value = row.currentChangeTotal
}

//变更增减的输入框失去焦点
const totalInputBlur = async (row) => {
    //如果为空
    let val = row.currentChangeTotal
    const isMeter = isNumberReg(val)
    if (isNullES(val) || !isMeter) {
        val = 0
    }
    if (currentChangeTotal.value === val) {
        return false
    }
    //处理数据
    const { error, msg, code } = await mainApi.changeTokenInventoryUpdate({
        contractId: contractId.value,
        primaryKeyIdInventory: row.primaryKeyId ?? '',
        primaryKeyIdMeter: changeNodeItem.value?.primaryKeyId ?? '',
        taskId: taskInfo.value.id ?? '',
        dataId: tableInfo.value.id ?? '',
        changTotal: val,
    })
    if (!error && code === 200) {
        window.$message.success('更新成功')
        getDataDetail().then()
    } else {
        window.$message.error(msg ?? '更新失败')
    }
}

//文件上传
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 {

}
</style>
