<template>
    <hc-new-card>
        <template #header>
            <div class="w-40">
                <el-select v-model="searchForm.meterPeriodId" placeholder="选择计量期" filterable clearable block @change="searchKey1Click">
                    <el-option v-for="item in key1Data" :key="item.id" :label="item.periodName" :value="item.id" clearable>
                        <div class="search-form-contract-period-id hc-flex">
                            <el-tag :color="(item.approveStatus !== 0 || item.id === -1) ? '#e6a23c' : '#67c23a'" class="mr-8px" size="small" />
                            <span>{{ item.periodName }}</span>
                        </div>
                    </el-option>
                </el-select>
            </div>
        </template>
        <template #extra>
            <el-button hc-btn type="primary" :disabled="approveStatus !== 0" @click="importClick">
                <hc-icon name="upload-cloud" />
                <span>导入</span>
            </el-button>
            <el-button hc-btn type="primary" :disabled="approveStatus !== 0" @click="importBatchClick">
                <hc-icon name="upload-cloud" />
                <span>附件批量导入</span>
            </el-button>
            <el-button hc-btn type="primary" :disabled="approveStatus !== 0" @click="addModalClick">
                <hc-icon name="add" />
                <span>新增</span>
            </el-button>
            <el-button v-if="approveStatus === 0" hc-btn type="primary" @click="reportClick">
                <hc-icon name="send-plane-2" />
                <span>上报</span>
            </el-button>
            <el-button v-if="approveStatus !== 0" :loading="undoLoading" hc-btn color="#FF7D43" class="text-white" @click="undoReportClick">撤销上报</el-button>
        </template>
        <div class="relative h-full flex">
            <div class="flex-1">
                <hc-card-item>
                    <hc-table
                        is-current-row :column="tableColumn" :datas="tableData" :loading="tableLoading"
                        is-new is-check :check-style="{ width: 29 }" :index-style="{ width: 60 }"
                        @selection-change="tableCheckChange" @row-click="hanleRow"
                    >
                        <template #approveStatusName="{ row }">
                            <el-link v-if="row.approveStatusName !== '未上报' && row.approveStatusName !== '审批失败'" type="primary" @click="rowTableClick(row)">{{ row.approveStatusName }}</el-link>
                            <span v-else>{{ row.approveStatusName }}</span>
                        </template>
                        <template #action="{ row }">
                            <el-link type="success" :disabled="approveStatus !== 0" @click="rowEditClick(row)">修改</el-link>
                            <el-link type="danger" :disabled="approveStatus !== 0" @click="delRowClick(row)">删除</el-link>
                        </template>
                    </hc-table>
                    <template #action>
                        <hc-pages :pages="searchForm" @change="pageChange" />
                    </template>
                </hc-card-item>
            </div>
            <div class="ml-3 w-[600px]">
                <hc-card-item title="详情信息" scrollbar>
                    <hc-info-table>
                        <tr>
                            <hc-info-table-td center is-title>合同材料：</hc-info-table-td>
                            <hc-info-table-td width="120px">{{ infoData?.contractMaterialName }}</hc-info-table-td>
                            <hc-info-table-td center is-title>材料到场编号：</hc-info-table-td>
                            <hc-info-table-td width="120px">{{ infoData?.materialArriveNumber }}</hc-info-table-td>
                        </tr>
                        <tr>
                            <hc-info-table-td center is-title>计量期：</hc-info-table-td>
                            <hc-info-table-td width="120px">{{ infoData?.meterPeriodName }}</hc-info-table-td>
                            <hc-info-table-td center is-title>业务日期：</hc-info-table-td>
                            <hc-info-table-td width="120px">{{ infoData?.businessDate }}</hc-info-table-td>
                        </tr>
                        <tr>
                            <hc-info-table-td center is-title>单价：</hc-info-table-td>
                            <hc-info-table-td width="120px">{{ infoData?.price }}</hc-info-table-td>
                            <hc-info-table-td center is-title>数量：</hc-info-table-td>
                            <hc-info-table-td width="120px">{{ infoData?.meterAmount }}</hc-info-table-td>
                        </tr>
                        <tr>
                            <hc-info-table-td center is-title>计量金额：</hc-info-table-td>
                            <hc-info-table-td width="120px">{{ infoData?.meterMoney }}</hc-info-table-td>
                            <hc-info-table-td center is-title>合同规定预付款金额：</hc-info-table-td>
                            <hc-info-table-td width="120px">{{ infoData?.contractStatedMoney }}</hc-info-table-td>
                        </tr>
                        <tr>
                            <hc-info-table-td center is-title>进料发票（单据）号：</hc-info-table-td>
                            <hc-info-table-td width="120px">{{ infoData?.storagePlace }}</hc-info-table-td>
                            <hc-info-table-td center is-title>质保书编号：</hc-info-table-td>
                            <hc-info-table-td width="120px">{{ infoData?.storageStatus }}</hc-info-table-td>
                        </tr>
                        <tr>
                            <hc-info-table-td center is-title>材料来源：</hc-info-table-td>
                            <hc-info-table-td width="120px">{{ infoData?.materialSource }}</hc-info-table-td>
                            <hc-info-table-td center is-title>材料是否符合要求：</hc-info-table-td>
                            <hc-info-table-td width="120px">{{ infoData?.materialConformName }}</hc-info-table-td>
                        </tr>
                        <tr>
                            <hc-info-table-td center is-title>存储方法是否符合要求：</hc-info-table-td>
                            <hc-info-table-td width="120px">{{ infoData?.storageConformName }}</hc-info-table-td>
                            <hc-info-table-td center is-title>抽检报告编号：</hc-info-table-td>
                            <hc-info-table-td width="auto" colspan="3">{{ infoData?.certificate }}</hc-info-table-td>
                        </tr>
                        <tr>
                            <hc-info-table-td center is-title>备注：</hc-info-table-td>
                            <hc-info-table-td width="auto" colspan="3">{{ infoData?.remark }}</hc-info-table-td>
                        </tr>
                    </hc-info-table>
                    <div class="mt-5">附件列表</div>
                    <div class="mt-3">
                        <template v-if="infoData?.fileList?.length > 0">
                            <el-check-tag v-for="item in infoData?.fileList" :key="item.id" checked class="mr-2" @click="viewFile(item)">{{ item.fileName }}</el-check-tag>
                        </template>

                        <hc-empty v-else />
                    </div>
                </hc-card-item>
            </div>
        </div>

        <!-- 新增/修改 -->
        <HcDataModal v-model="isDataModal" :info-data="infoData" :meter-period-id="searchForm.meterPeriodId" :ids="editId" @close="finishData" />

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

        <!-- 任务流程 -->
        <HcTaskModal v-model="isTaskModal" :ids="taskDataId" @close="taskDataId = ''" />

        <!-- 导入 -->
        <HcImportFile v-model="isImportShow" :ids="searchForm.meterPeriodId" @finish="getTableData" />

        <!-- 批量导入 -->
        <HcBatchImport v-model="importBatchShow" :ids="searchForm.meterPeriodId" @finish="getTableData" />
    </hc-new-card>
</template>

<script setup>
import { nextTick, onActivated, ref } from 'vue'
import { backMeterTask } from '~api/other'
import { useAppStore } from '~src/store'
import { toPdfPage } from '~uti/btn-auth'
import { HcDelMsg } from 'hc-vue3-ui'
import { getArrValue, getObjValue, isNullES } from 'js-fast-way'
import HcDataModal from './components/order/dataModal.vue'
import HcTaskModal from '~src/components/task-modal/task-modal.vue'
import HcImportFile from './components/order/importFile.vue'
import HcBatchImport from './components/order/batchImport.vue'
import mainApi from '~api/debit-pay/material/order.js'
import periodApi from '~api/debit-pay/material/periods.js'

const useAppState = useAppStore()
const contractId = ref(useAppState.getContractId)

defineOptions({
    name: 'DebitPayMaterialOrder',
})

//渲染完成
onActivated(async () => {
    await getKey1Data()
    getTableData().then()
})

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

//计量期
const key1Data = ref([])
const approveStatus = ref(0)
const getKey1Data = async ()=>{
    const { error, code, data } = await periodApi.allPeriod({
       contractId:contractId.value,
       type: 1,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        let newArr = getArrValue(data), info = getObjValue(newArr[newArr.length - 1])
        searchForm.value.meterPeriodId = info.id
        approveStatus.value = info.approveStatus
        key1Data.value = newArr
    } else {
        key1Data.value = []
    }
}
const searchKey1Click = () => {
    let info = getObjValue(key1Data.value.find((item) => item.id === searchForm.value.meterPeriodId))
    approveStatus.value = info.approveStatus
    searchForm.value.current = 1
    getTableData()
}

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

//表格数据
const tableLoading = ref(false)
const tableColumn = ref([
    { key: 'contractMaterialName', name: '合同材料' },
    { key: 'materialArriveNumber', name: '材料到场编号' },
    { key: 'businessDate', name: '业务日期' },
    { key: 'meterMoney', name: '计量金额' },
    { key: 'approveStatusName', name: '审核状态' },
    { key: 'action', name: '操作', width: 94 },
])
const tableData = ref([])
const getTableData = async () => {
    tableLoading.value = true
    console.log(searchForm.value, 'searchForm.value')
    const { error, code, data } = await mainApi.getPage({
       ...searchForm.value,
       contractId:contractId.value,
    //    meterPeriodId:searchForm.value.key1,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data['total']
        if (tableData.value.length > 0) {
            getDetail(tableData.value[0].id)


        } else {
            infoData.value = {}
        }
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}
const hanleRow = ({ row })=>{
    getDetail(row.id)
}
//获取详情
const infoData = ref({})
const getDetail = async (id)=>{
    const { error, code, data } = await mainApi.detail({
       id,
    })
    if (!error && code === 200) {
        infoData.value = getObjValue(data)

    } else {
        infoData.value = {}
    }
}
//查看附件
const viewFile = (item)=>{
    toPdfPage(item.filePdfUrl)
}
//表格选择
const tableCheckChange = () => {

}

//新增
const isDataModal = ref(false)
const addModalClick = () => {
    isDataModal.value = true
    editId.value = ''
}
const finishData = ()=>{
    isDataModal.value = false
    getTableData()
}
//修改
const editId = ref('')
const rowEditClick = (row) => {
    isDataModal.value = true
    editId.value = row.id
}
const delRowClick = (row)=>{
    HcDelMsg(async (resolve) => {
        await removeProPay(row.id)
        resolve()
    })
}
const removeProPay = async (id) => {
    const { error, code, msg } = await mainApi.remove({ ids: id })
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
       getTableData().then()
    } else {
        window.$message.error(msg ?? '操作失败')
    }
}

//是否上报
const isReport = ref(false)
const reportInfo = ref({})
const reportClick = () => {
    reportInfo.value = {
        type: 2,
        periodId: searchForm.value.meterPeriodId,
    }
    nextTick(() => {
        isReport.value = true
    })
}

//审批状态
const isTaskModal = ref(false)
const taskDataId = ref('')
const rowTableClick = ({ taskId }) => {
    if (isNullES(taskId)) {
        window.$message.warning('暂无审批数据')
        return
    }
    taskDataId.value = taskId
    setTimeout(()=> {
        isTaskModal.value = true
    }, 200)
}

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

//撤销上报
const undoLoading = ref(false)
const undoReportClick = async () => {
    undoLoading.value = true
    const { meterPeriodId } = searchForm.value
    const { isRes } = await backMeterTask({
        periodId: meterPeriodId,
        type: 1,
    })
    undoLoading.value = false
    if (!isRes) return
    window.$message.success('撤回成功')
    reportFinish()
}

//导入
const isImportShow = ref(false)
const importClick = () => {
    isImportShow.value = true
}

//附件批量导入
const importBatchShow = ref(false)
const importBatchData = ref([])
const importBatchClick = () => {
    importBatchShow.value = true
    importBatchData.value = tableData.value
}
</script>

<style scoped lang="scss">

</style>
