<template>
    <hc-new-card>
        <template #header>
            <hc-new-switch :datas="tabTab" :keys="tabKey" :round="false" size="default" @change="tabChange" />
            <div v-if="tabKey === 'key2'" class="ml-3 w-40">
                <el-select v-model="searchForm.key1" filterable block placeholder="选择工区">
                    <el-option label="工区1" value="1" />
                    <el-option label="工区2" value="2" />
                    <el-option label="工区3" value="3" />
                </el-select>
            </div>
        </template>
        <template #extra>
            <el-button hc-btn type="primary" @click="addModalClick">
                <hc-icon name="add" />
                <span>新增</span>
            </el-button>
            <el-button hc-btn type="warning" :disabled="tableCheckKeys.length <= 0" @click="reportClick">
                <hc-icon name="send-plane-2" />
                <span>上报</span>
            </el-button>
        </template>
        <div class="relative h-full flex">
            <div :id="`hc_table_card_${uuid}`" class="flex-1">
                <hc-card-item>
                    <hc-table
                        ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading"
                        is-current-row is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
                        @row-click="tableRowClick" @selection-change="tableCheckChange"
                    >
                        <template #action="{ row }">
                            <template v-if="row.approveStatus === 2">
                                <el-link v-if="row.commandStatus === 0" type="success" @click="rowExecuteChange(row.id)">下达</el-link>
                                <el-link v-if="row.commandStatus === 0" type="danger" @click="delRowClick(row)">删除</el-link>
                                <el-link v-if="row.commandStatus === 1 && row.citeStatus === 0" type="success" @click="rowAnnulChange(row.id)">撤销下达</el-link>
                            </template>
                            <template v-if="row.approveStatus === 0 || row.approveStatus === 3">
                                <el-link type="success" @click="rowEditClick(row)">修改</el-link>
                                <el-link type="danger" @click="delRowClick(row)">删除</el-link>
                            </template>
                        </template>
                    </hc-table>
                    <template #action>
                        <hc-pages :pages="searchForm" @change="pageChange" />
                    </template>
                </hc-card-item>
            </div>
            <div :id="`hc_info_card_${uuid}`">
                <el-scrollbar>
                    <hc-card-item title="详情信息">
                        <hc-info-table>
                            <tr>
                                <hc-info-table-td center is-title>变更方案编号：</hc-info-table-td>
                                <hc-info-table-td width="120px">{{ tableInfo.changeNumber ?? '-' }}</hc-info-table-td>
                                <hc-info-table-td center is-title>变更方案名称：</hc-info-table-td>
                                <hc-info-table-td width="120px">{{ tableInfo.changeName ?? '-' }}</hc-info-table-td>
                                <hc-info-table-td center is-title>变更发起单位：</hc-info-table-td>
                                <hc-info-table-td width="120px">{{ tableInfo.changeUnit ?? '-' }}</hc-info-table-td>
                            </tr>
                            <tr>
                                <hc-info-table-td center is-title>业务日期：</hc-info-table-td>
                                <hc-info-table-td width="160px">{{ tableInfo.businessDate ?? '-' }}</hc-info-table-td>
                                <hc-info-table-td center is-title>变更类型：</hc-info-table-td>
                                <hc-info-table-td width="120px">{{ tableInfo.changeTypeName ?? '-' }}</hc-info-table-td>
                                <hc-info-table-td center is-title>延长工期：</hc-info-table-td>
                                <hc-info-table-td width="120px">{{ tableInfo.lengthenDays ?? '-' }}</hc-info-table-td>
                            </tr>
                            <tr>
                                <hc-info-table-td center is-title>变更申请金额：</hc-info-table-td>
                                <hc-info-table-td width="120px">{{ tableInfo.changeMoney ?? '-' }}</hc-info-table-td>
                                <hc-info-table-td center is-title>设计图完成时间：</hc-info-table-td>
                                <hc-info-table-td width="120px">{{ tableInfo.designDate ?? '-' }}</hc-info-table-td>
                                <hc-info-table-td center is-title>实际变更桩号：</hc-info-table-td>
                                <hc-info-table-td width="120px">{{ tableInfo.realityChangeNumber ?? '-' }}</hc-info-table-td>
                            </tr>
                            <tr>
                                <hc-info-table-td center is-title>变更归类：</hc-info-table-td>
                                <hc-info-table-td width="120px">{{ tableInfo.changeClassifyName ?? '-' }}</hc-info-table-td>
                                <hc-info-table-td center is-title>变更批复文号：</hc-info-table-td>
                                <hc-info-table-td width="120px">{{ tableInfo.changeApprovalNumber ?? '-' }}</hc-info-table-td>
                                <hc-info-table-td center is-title>变更批复时间：</hc-info-table-td>
                                <hc-info-table-td width="120px">{{ tableInfo.changeApprovalDate ?? '-' }}</hc-info-table-td>
                            </tr>
                            <tr>
                                <hc-info-table-td center is-title>引用预变更：</hc-info-table-td>
                                <hc-info-table-td width="auto" colspan="5">-</hc-info-table-td>
                            </tr>
                            <tr>
                                <hc-info-table-td center is-title>变更原因：</hc-info-table-td>
                                <hc-info-table-td width="auto" colspan="5">{{ tableInfo.changeCause ?? '-' }}</hc-info-table-td>
                            </tr>
                        </hc-info-table>
                    </hc-card-item>
                    <hc-card-item class="mt-3" title="变更申请部位">
                        <hc-table ref="tableRef1" :column="tableColumn1" :datas="tableInfo.nodeList" is-new :index-style="{ width: 60 }" is-current-row @row-click="tableNodeRowClick" />
                    </hc-card-item>
                    <hc-card-item v-if="tableChangeData.length > 0" class="mt-3" title="变更申请清单">
                        <div class="hc-table-ref-box no-border">
                            <el-table class="w-full" :data="tableChangeData" 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="变更增减" />
                                    <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>
                        </div>
                    </hc-card-item>
                    <!-- 附件列表 -->
                    <hc-card-item class="mt-3" title="附件列表">
                        <hc-form-upload class="table-info-file" type="list" :src="tableInfo.fileList" :h-props="uploadFormProps" />
                    </hc-card-item>
                </el-scrollbar>
            </div>
        </div>

        <!-- 上报弹窗 -->
        <hc-report-dialog v-model="isReport" :info="reportInfo" @finish="reportFinish" />

        <!-- 新增修改的弹窗 -->
        <addModal v-model="isAddShow" :ids="addEditIds" @finish="addEditFinish" />
    </hc-new-card>
</template>

<script setup>
import { nextTick, onActivated, onMounted, ref } from 'vue'
import { useAppStore } from '~src/store'
import { actionConfirm, delMessage } from '~uti/tools'
import addModal from './components/order/addModal.vue'
import { arrToId, getArrValue, getObjValue, getRandom, isNullES } from 'js-fast-way'
import mainApi from '~api/alter/admin/order'

defineOptions({
    name: 'AlterAdminOrder',
})

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

//渲染完成
onMounted(() => {
    setSplitRef()
})

//激活
onActivated(() => {
    getTableData()
})

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

//类型tab数据和相关处理
const tabKey = ref('key1')
const tabTab = ref([
    { key: 'key1', name: '普通变更' },
    { key: 'key2', name: '工区变更' },
])

const tabChange = (item) => {
    tabKey.value = item?.key
}

//搜索表单
const searchForm = ref({
    key1: null, current: 1, size: 10, total: 0,
})

//分页
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//表格数据
const tableRef = ref(null)
const tableColumn = ref([
    { key: 'changeNumber', name: '变更编号' },
    { key: 'changeName', name: '变更名称' },
    { key: 'changeMoney', name: '变更金额' },
    { key: 'changeTypeName', name: '变更类型' },
    { key: 'changeApprovalDate', name: '变更批复日期' },
    { key: 'approveStatusName', name: '审批状态' },
    { key: 'action', name: '操作', width: 94 },
])
const tableData = ref([])

//获取表格数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const { data } = await mainApi.getPage({
        ...searchForm.value,
        projectId: projectId.value,
        contractId: contractId.value,
    })
    tableData.value = getArrValue(data['records'])
    searchForm.value.total = data.total || 0
    tableLoading.value = false
    //默认选中第一行
    let info = {}
    if (tableData.value.length > 0) {
        info = tableData.value[0]
    }
    tableRef.value?.tableRef?.setCurrentRow(info)
    getTableDetail(info).then()
}

//表格行被点击
const tableRowClick = ({ row }) => {
    getTableDetail(row)
}

//获取详情
const tableInfo = ref({})
const getTableDetail = async (row) => {
    if (!row.id) return
    const { data } = await mainApi.getDetail({ id: row.id })
    const dataInfo = getObjValue(data)
    dataInfo.nodeList = getArrValue(dataInfo.nodeList)
    tableInfo.value = dataInfo
    //默认选中部位的第一行
    let info = {}
    if (dataInfo.nodeList.length > 0) {
        info = dataInfo.nodeList[0]
    }
    tableRef1.value?.tableRef?.setCurrentRow(info)
    tableChangeData.value = getArrValue(info.formList)
}

//修改
const addEditIds = ref('')
const rowEditClick = (row) => {
    addEditIds.value = row.id
    nextTick(() => {
        isAddShow.value = true
    })
}

//新增修改的弹窗
const isAddShow = ref(false)
const addModalClick = () => {
    addEditIds.value = ''
    nextTick(() => {
        isAddShow.value = true
    })
}

const tableRef1 = ref(null)
//申请部位
const tableColumn1 = ref([
    { key: 'nodeName', name: '工程名称' },
    { key: 'nodeUrl', name: '节点路径' },
    { key: 'contractPicture', name: '合同图号' },
    { key: 'changeMoney', name: '变更后金额(元)' },
    { key: 'isSupplementName', name: '是否增补' },
])

//申请部位被点击
const tableChangeData = ref([])
const tableNodeRowClick = ({ row }) => {
    tableChangeData.value = getArrValue(row.formList)
}

//附件列表
const uploadFormProps = {
    url: 'fileUrl',
    name: 'fileName',
}

//新增修改完成
const addEditFinish = () => {
    getTableData()
}

//删除
const delRowClick = (row) => {
    delMessage(async () => {
        const { error, code, msg } = await mainApi.remove({ ids: row.id })
        if (!error && code === 200) {
            window.$message.success('删除成功')
            getTableData().then()
        } else {
            window.$message.error(msg ?? '删除失败')
        }
    })
}

//下达变更
const rowExecuteChange = async (id) => {
    if (isNullES(id)) {
        window.$message.error('id异常')
        return
    }
    // 确认发起请求
    actionConfirm(async () => {
        tableLoading.value = true
        const { error, code, msg } = await mainApi.executeChange({ id })
        tableLoading.value = false
        if (!error && code === 200) {
            window.$message.success('下达成功')
            getTableData().then()
        } else {
            window.$message.error(msg ?? '下达失败')
        }
    })
}

//撤销下达
const rowAnnulChange = async (id) => {
    if (isNullES(id)) {
        window.$message.error('id异常')
        return
    }
    // 确认发起请求
    actionConfirm(async () => {
        tableLoading.value = true
        const { error, code, msg } = await mainApi.annulChange({ id })
        tableLoading.value = false
        if (!error && code === 200) {
            window.$message.success('撤销下达成功')
            getTableData().then()
        } else {
            window.$message.error(msg ?? '撤销下达失败')
        }
    })
}

//表格选择
const tableCheckKeys = ref([])
const tableCheckChange = (keys) => {
    tableCheckKeys.value = keys
}

//是否上报
const isReport = ref(false)
const reportInfo = ref({})
const reportClick = () => {
    const rows = tableCheckKeys.value
    //判断是否满足条件
    const result = rows.every(({ approveStatus }) => {
        return approveStatus === 0
    })
    if (!result) {
        window.$message?.warning('请选择未上报的数据')
        return
    }
    //处理数据
    const rowIds = arrToId(rows)
    reportInfo.value = { type: 4, periodId: rowIds }
    nextTick(() => {
        isReport.value = true
    })
}

//上报完成
const reportFinish = () => {
    window.location.reload()
}

</script>

<style lang="scss">
.table-info-file .item-upload-btn {
    display: none;
}
.hc-ui-form-upload-box.table-info-file .hc-ui-form-item-dashed.list .file-list-box {
    margin-top: 0;
}
.hc-ui-form-upload-box.table-info-file .hc-ui-form-item-dashed.list .file-list-box .item .close-icon {
    display: none;
}
</style>
