<template>
    <div class="hc-layout-box">
        <div class="hc-layout-left-box" id="wbs-left-tree" :style="'width:' + leftWidth + 'px;'">
            <div class="hc-project-box">
                <div class="hc-project-icon-box">
                    <HcIcon name="layers"/>
                </div>
                <div class="ml-2 project-name-box">
                    <span class="text-xl text-cut project-alias">{{projectInfo['projectAlias']}}</span>
                    <div class="text-xs text-cut project-name">{{projectInfo['name']}}</div>
                </div>
            </div>
            <div class="hc-tree-box">
                <div class="hc-search-tree-val">
                    <el-input v-model="searchTreeVal" block size="large" placeholder="请输入名称关键词检索" clearable @keyup="searchTreeKeyUp">
                        <template #suffix>
                            <HcIcon name="search" ui="text-2xl"/>
                        </template>
                    </el-input>
                </div>
                <div class="hc-tree-scrollbar" v-loading="treeLoading" element-loading-text="获取数据中...">
                    <el-scrollbar>
                        <KeepAlive>
                            <template v-if="isSearchTree">
                                <HcTreeData :datas="searchTreeData" :autoExpandKeys="treeAutoExpandKeys" isColor @nodeTap="wbsElTreeClick"/>
                            </template>
                            <template v-else>
                                <WbsTree :autoExpandKeys="treeAutoExpandKeys" :projectId="projectId" :contractId="contractId" isColor @nodeTap="wbsElTreeClick"/>
                            </template>
                        </KeepAlive>
                    </el-scrollbar>
                </div>
            </div>
            <div class="hc-tree-foot-tip-box">
                <div class="dot-view green">已审批</div>
                <div class="dot-view black">未填报</div>
                <div class="dot-view orange">已填报-待审批</div>
                <div class="dot-view blue">已填报-未上报</div>
            </div>
            <!--左右拖动-->
            <div class="horizontal-drag-line" @mousedown="onmousedown"/>
        </div>
        <div class="hc-layout-content-box">
            <HcCard :scrollbar="false" actionSize="lg">
                <template #header>
                    <HcTooltip keys="query_report">
                        <el-button type="primary" hc-btn :disabled="tableCheckedKeys.length <= 0" @click="reportModalClick">
                            <HcIcon name="drive_folder_upload"/>
                            <span>上报</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="query_download">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="downloadLoading" @click="batchDownload">
                            <HcIcon name="download"/>
                            <span>下载</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="query_print">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="printLoading" @click="batchPrint">
                            <HcIcon name="print"/>
                            <span>打印</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="query_abolish">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="batchAbolishClick">
                            <HcIcon name="delete"/>
                            <span>废除</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="query_local_attestation">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="localLoading" @click="batchLocal">
                            <HcIcon name="folder"/>
                            <span>本地验签</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="query_online_attestation">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="onlineLoading" @click="batchOnline">
                            <HcIcon name="browse_activity"/>
                            <span>在线验签</span>
                        </el-button>
                    </HcTooltip>
                </template>
                <template #search>
                    <div class="flex items-center">
                        <div class="w-40">
                            <el-select v-model="searchForm.taskStatus" placeholder="流程状态" clearable>
                                <el-option v-for="item in processStatusData" :key="item.value" :label="item['dictValue']" :value="item['dictKey']"/>
                            </el-select>
                        </div>
                        <div class="w-40 ml-2">
                            <el-select v-model="searchForm.fileUserIdAndName" placeholder="填报人" clearable>
                                <el-option v-for="item in reportingPersonData" :key="item.value" :label="item['label']" :value="item['value']"/>
                            </el-select>
                        </div>
                        <div class="w-40 ml-2">
                            <el-select v-model="searchForm.sourceType" placeholder="文件类型" clearable>
                                <el-option v-for="item in fileTypeData" :key="item.value" :label="item['dictValue']" :value="item['dictKey']"/>
                            </el-select>
                        </div>
                        <div class="w-32 ml-2">
                            <el-select v-model="searchForm.reportNumber" placeholder="上报批次" clearable>
                                <el-option v-for="item in reportBatchData" :key="item.value" :label="item['label']" :value="item['value']"/>
                            </el-select>
                        </div>
                        <div class="w-64 ml-2">
                            <HcDatePicker :dates="betweenTime" clearable @change="betweenTimeUpdate"/>
                        </div>
                        <div class="w-60 ml-2">
                            <el-input v-model="searchForm.queryValue" placeholder="请输入名称关键词检索" clearable @keyup="keyUpEvent"/>
                        </div>
                        <div class="ml-2">
                            <el-button type="primary" @click="searchClick">搜索</el-button>
                        </div>
                    </div>
                </template>
                <el-scrollbar>
                    <div class="hc-table-ref-box">
                        <el-table ref="recycleTableRef" hc :data="tableListData" :loading="tableLoading" stripe @selection-change="tableSelectionChange">
                            <el-table-column type="selection" width="50" />
                            <el-table-column prop="num" label="序号" width="80">
                                <template #default="scope">
                                    {{scope.$index + 1}}
                                </template>
                            </el-table-column>
                            <el-table-column prop="name" label="文件名称" />
                            <el-table-column prop="startTime" label="开始时间"/>
                            <el-table-column prop="taskStatusStr" label="流程状态"/>
                            <el-table-column prop="reportNumber" label="上报批次"/>
                            <el-table-column prop="fileUserIdAndName" label="填报人"/>
                            <el-table-column prop="tesk" label="任务人"/>
                        </el-table>
                    </div>
                </el-scrollbar>
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange"/>
                </template>
            </HcCard>
        </div>

        <!--批量上报审批-->
        <HcReportModal  title="批量上报审批" url="informationWriteQuery/batchTask" :show="showReportModal" :projectId="projectId" :contractId="contractId"
                        :taskName="reportTaskName" :ids="reportIds" :addition="reportAddition" @hide="showReportModal = false" @finish="showReportFinish"/>
    </div>
</template>

<script setup>
import {ref,watch,onMounted} from "vue";
import {useAppStore} from "~src/store/index";
import WbsTree from "./components/WbsTree.vue"
import HcTreeData from "./components/HcTreeData.vue"
import {getStoreData, setStoreData} from '~src/utils/storage'
import {isType, downloadBlob} from "vue-utils-plus"
import queryApi from '~api/data-fill/query';

//变量
const useAppState = useAppStore()
const {getObjValue, getArrValue, isObjNull} = isType()
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);
const projectInfo = ref(useAppState.getProjectInfo);
const isCollapse = ref(useAppState.getCollapse)

//监听
watch(() => [
    useAppState.getCollapse
], ([Collapse]) => {
    isCollapse.value = Collapse
})

//自动展开缓存
const treeAutoExpandKeys = ref(getStoreData('wbsTreeExpandKeys') || [])

//渲染完成
onMounted(() => {
    getFileUser()
    getReportNumber()
    getDictBizClassify('flowTaskStatus')
    getDictBizClassify('fileType')
})

//树搜索
const isSearchTree = ref(false)
const searchTreeVal = ref('')
const searchTreeData = ref([])

//回车
const treeLoading = ref(false)
const searchTreeKeyUp = (e) => {
    if (e.key === "Enter") {
        searchTreeClick()
    }
}
const searchTreeClick = async () => {
    if (searchTreeVal.value) {
        isSearchTree.value = true
        treeLoading.value = true
        const {error, code, data} = await queryApi.searchContractTree({
            contractId: contractId.value,
            queryValue: searchTreeVal.value
        })
        //判断状态
        if (!error && code === 200) {
            searchTreeData.value = getArrValue(data)
            treeLoading.value = false
        } else {
            treeLoading.value = false
            searchTreeData.value = []
        }
    } else {
        treeLoading.value = false
        isSearchTree.value = false
    }
}

//树相关的变量
const primaryKeyId = ref('')
const nodeItemInfo = ref({})
const nodeDataInfo = ref({})

//树被点击
const wbsElTreeClick = ({node, data, keys}) => {
    nodeItemInfo.value = node
    nodeDataInfo.value = data
    primaryKeyId.value = data['primaryKeyId'] || ''
    //缓存自动展开
    treeAutoExpandKeys.value = keys
    setStoreData('wbsTreeExpandKeys',keys)
    //改变搜索表单数据
    searchForm.value.wbsId = data['contractIdRelation'] ? data['id'] : data['primaryKeyId']
    searchForm.value.contractIdRelation = data['contractIdRelation']
    searchForm.value.current = 1;
    getTableData()
}

//搜索条件
const processStatusData = ref([])   //流程状态
const reportingPersonData = ref([]) //填报人
const fileTypeData = ref([])        //文件类型
const reportBatchData = ref([])     //上报批次

//获取所有填报人
const getFileUser = async () => {
    const {error, code, data} = await queryApi.getFileUser({
        contractId: contractId.value
    })
    //判断状态
    if (!error && code === 200) {
        let res = getArrValue(data), userArr = [];
        res.forEach(item => {
            userArr.push({label: item['userName'], value: `${item['userId']}-${item['userName']}`})
        })
        reportingPersonData.value = userArr
    } else {
        reportingPersonData.value = []
    }
}
//获取上报批次
const getReportNumber = async () => {
    const {error, code, data} = await queryApi.getReportNumber({
        contractId: contractId.value
    })
    //判断状态
    if (!error && code === 200) {
        console.log(data)
        //let res = getArrValue(data);
        reportBatchData.value = []
    } else {
        reportBatchData.value = []
    }
}
//获取流程状态分类和文件类型分类
const getDictBizClassify = async (type) => {
    const {error, code, data} = await queryApi.getDictBizClassify({
        contractId: contractId.value,
        code: type
    })
    //判断状态
    if (!error && code === 200) {
        if (code === 'flowTaskStatus') {
            processStatusData.value = getArrValue(data)
        } else if (code === 'fileType') {
            fileTypeData.value = getArrValue(data)
        }
    } else {
        if (code === 'flowTaskStatus') {
            processStatusData.value = []
        } else if (code === 'fileType') {
            fileTypeData.value = []
        }
    }
}

//搜索表单
const searchForm = ref({
    taskStatus: null, fileUserIdAndName: null, sourceType: null, reportNumber: null, betweenTime: null,
    queryValue: null, contractIdRelation: null, wbsId: null, current: 1, size: 20, total: 0
})

//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({val,arr}) => {
    betweenTime.value = arr
    searchForm.value.betweenTime = `${val['start']}~${val['end']}`
}

//回车搜索
const keyUpEvent = (e) => {
    if (e.key === "Enter") {
        searchForm.value.current = 1;
        getTableData()
    }
}

//搜索
const searchClick = () => {
    searchForm.value.current = 1;
    getTableData()
}

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

//获取数据
const tableLoading = ref(false)
const tableListData = ref([])
const getTableData = async () => {
    if (!!searchForm.value.wbsId) {
        tableLoading.value = true
        const { error, code, data } = await queryApi.getPageData({
            projectId: projectId.value,
            contractId: contractId.value,
            ...searchForm.value
        })
        //处理数据
        tableLoading.value = false
        if (!error && code === 200) {
            tableListData.value = getArrValue(data['records'])
            searchForm.value.total = data.total || 0
        } else {
            tableListData.value = []
            searchForm.value.total = 0
        }
    } else {
        window?.$message?.warning('请先选择一个树节点')
    }
}

//多选
const tableCheckedKeys = ref([]);
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows.filter((item) => {
        return (item??'') !== '';
    })
}

//上报
const reportIds = ref('')
const reportTaskName = ref('')
const reportAddition = ref({})
const showReportModal = ref(false)
const reportModalClick = () => {
    const rows = tableCheckedKeys.value;
    //判断是否满足条件
    const result = rows.every(({status})=> {
        return status === 0 || status === 3
    })
    //判断状态
    if (result) {
        //const info = nodeDataInfo.value;
        const row = getObjValue(rows[0])
        reportIds.value = rowsToId(rows)
        //设置任务名称
        reportTaskName.value = rows.length > 1 ? `${row.name}等${rows.length}个文件` : row.name
        //reportAddition.value = {contractIdRelation: info['contractIdRelation']}
        showReportModal.value = true
    } else {
        window.$message?.warning('已上报的文件不能进行再次上报，若要重新上报，要先撤回之前的上报，再重新上报')
    }
}
//上报完成
const showReportFinish = () => {
    showReportModal.value = false
    getTableData()
}


//下载
const downloadLoading = ref(false)
const batchDownload = async () => {
    const rows = tableCheckedKeys.value;
    const ids = rowsToId(rows)
    //批量下载
    downloadLoading.value = true
    const { error, disposition, res } = await queryApi.batchDownloadFileToZip({ids: ids})
    //处理数据
    downloadLoading.value = false
    if (!error) {
        if (disposition) {
            downloadBlob(res,disposition)
        } else {
            window.$message?.error('数据异常')
        }
    }
}

//打印
const printLoading = ref(false)
const batchPrint = async () => {
    const rows = tableCheckedKeys.value;
    const ids = rowsToId(rows)
    //批量下载
    printLoading.value = true
    const { error, code, data } = await queryApi.batchPrint({ids: ids})
    //处理数据
    printLoading.value = false
    if (!error && code === 200) {
        console.log(data)
        if (isObjNull(data)) {
            window.$message?.error('数据异常')
        } else {
            //待写
        }
    }
}

//废除
const batchAbolishClick = async () => {
    const rows = tableCheckedKeys.value;
    //判断是否满足条件
    const result = rows.every(({status})=> {
        return status !== 0 && status !== 3
    })
    //判断状态
    if (result) {
        //拼接ID
        const ids = rowsToId(rows)
        window?.$messageBox?.alert('是否废除勾选的已上报文件？', '废除文件', {
            showCancelButton: true,
            confirmButtonText: '确定废除',
            cancelButtonText: '取消',
            callback: (action) => {
                if (action === 'confirm') {
                    batchAbolishSave(ids)
                }
            }
        })
    } else {
        window.$message?.warning('未上报的文件不能废除')
    }
}
//废除勾选的已上报文件
const batchAbolishSave = async (ids) => {
    const { error, code } = await queryApi.batchAbolish({ids: ids})
    //处理数据
    if (!error && code === 200) {
        window.$message?.success('批量废除成功')
        tableCheckedKeys.value = []
        getTableData()
    }
}

//本地验签
const localLoading = ref(false)
const batchLocal = async () => {
    const rows = tableCheckedKeys.value;
    //判断是否满足条件
    const result = rows.every(({status})=> {
        return status === 2
    })
    //判断状态
    if (result) {
        const ids = rowsToId(rows)
        //请求数据
        localLoading.value = true
        const { error, code, data } = await queryApi.localVerify({
            ids: ids
        })
        //处理数据
        localLoading.value = false
        if (!error && code === 200) {
            console.log(data)
        }
    } else {
        window.$message?.warning('存在未审批或未上报数据')
    }
}

//在线验签
const onlineLoading = ref(false)
const batchOnline = async () => {
    const rows = tableCheckedKeys.value;
    if (rows.length > 1) {
        window.$message?.warning('在线验签只能勾选一条数据进行验签')
        return;
    }
    if (rows[0].status !== 2) {
        window.$message?.warning('存在未审批或未上报数据')
        return;
    }
    //发起
    onlineLoading.value = true
    const { error, code, data } = await queryApi.onlineVerify({
        ids: rows[0]['id']
    })
    //处理数据
    localLoading.value = false
    if (!error && code === 200) {
        console.log(data)
    }
}

//拼接ID
const rowsToId = (rows) => {
    return rows.map((obj) => {
        return obj.id;
    }).join(",")
}


//左右拖动，改变树形结构宽度
const leftWidth = ref(382);
const onmousedown = () => {
    const leftNum = isCollapse.value ? 142 : 272
    document.onmousemove = (ve) => {
        let diffVal = ve.clientX - leftNum;
        if(diffVal >= 310 && diffVal <= 900) {
            leftWidth.value = diffVal;
        }
    }
    document.onmouseup = () => {
        document.onmousemove = null;
        document.onmouseup = null;
    }
}
</script>

<style lang="scss" scoped>
@import "../../styles/data-fill/query.scss";
</style>
