<template>
    <div class="hc-layout-box" id="first-item-node-layout-target">
        <div class="hc-layout-left-box" :style="'width:' + leftWidth + 'px;'" v-show="!isFirstReportDrawer">
            <div class="hc-project-box">
                <div class="hc-project-icon-box">
                    <HcIcon name="stack"/>
                </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">
                <el-scrollbar>
                    <WbsTree :autoExpandKeys="TreeAutoExpandKeys" :projectId="projectId" :contractId="contractId" @nodeTap="nodeWbsElTreeClick"/>
                </el-scrollbar>
            </div>
            <!--左右拖动-->
            <div class="horizontal-drag-line" @mousedown="onmousedown"/>
        </div>
        <div class="hc-layout-content-box first-item" v-show="!isFirstReportDrawer">
            <HcCard :scrollbar="false" actionSize="lg">
                <template #header>
                    <HcTooltip keys="other-first-item-report" v-if="tabTypeKey === 'mark'">
                        <el-button type="primary" hc-btn :disabled="tableSelectionKeys.length <= 0" @click="firstReportClick">
                            <HcIcon name="send-plane-2"/>
                            <span>上报首件</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="other-first-item-report-approval" v-if="tabTypeKey === 'query'">
                        <el-button type="primary" hc-btn :disabled="tableSelectionKeys.length <= 0" @click="reportModalClick">
                            <HcIcon name="send-plane-2"/>
                            <span>上报审批</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="other-first-item-repeal">
                        <el-button hc-btn :disabled="tableSelectionKeys.length <= 0">
                            <HcIcon name="delete-bin-3"/>
                            <span>批量废除</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="other-first-item-down-print">
                        <el-button hc-btn :disabled="tableSelectionKeys.length <= 0">
                            <HcIcon name="printer"/>
                            <span>预览/打印</span>
                        </el-button>
                    </HcTooltip>
                </template>
                <template #extra>
                    <HcNewSwitch :datas="tabTypeTab" :keys="tabTypeKey" @change="tabTypeChange"/>
                </template>
                <template #search>
                    <div class="w-32">
                        <el-select v-model="searchForm.status" placeholder="流程状态" clearable>
                            <el-option v-for="item in processStatus" :label="item['dictValue']" :value="item['dictKey']"/>
                        </el-select>
                    </div>
                    <div class="w-32 ml-3">
                        <el-select v-model="searchForm.reportNumber" placeholder="上报批次" clearable>
                            <el-option v-for="item in reportBatch" :label="item" :value="item"/>
                        </el-select>
                    </div>
                    <div class="w-64 ml-3">
                        <HcDatePicker :dates="betweenTime" clearable @change="betweenTimeUpdate"/>
                    </div>
                    <div class="w-64 ml-3">
                        <el-input v-model="searchForm.queryValue" placeholder="请输入名称关键词检索" clearable @keyup="keyUpEvent"/>
                    </div>
                    <div class="ml-2">
                        <el-button type="primary" @click="searchClick">
                            <HcIcon name="search-2"/>
                            <span>搜索</span>
                        </el-button>
                    </div>
                </template>
                <HcTable ref="tableListRef" :column="tableListColumn" :datas="tableListData" :loading="tableLoading" isCheck @selection-change="tableSelectionChange">
                    <template #name="{row}">
                        <span class="text-link" @click="tableRowName(row)">{{row?.name}}</span>
                    </template>
                    <template #waitingUserList="{row}">
                        <template v-for="item in row['waitingUserList']">
                            <el-tag :type="`${item.status === 2 ? 'success' : item.status === 3 ? 'warning' : item.status === 999 ? 'danger' : 'info'}`"
                                    class="mx-1" effect="dark" v-if="item['waitingUserName']">{{item['waitingUserName']}}</el-tag>
                        </template>
                    </template>
                    <template #taskStatusStr="{row}">
                        <el-tag :type="`${row.status === 2 ? 'success' : row.status === 0 ? 'warning' : row.status === 1 ? 'danger' : 'info'}`"
                                class="mx-1" effect="dark" v-if="row['taskStatusStr']">{{row['taskStatusStr']}}</el-tag>
                    </template>
                </HcTable>
                <template #action>
                    <div class="lr-dialog-footer">
                        <div class="left">
                            <span class="text-success">任务人中：</span>
                            <el-tag type="success" class="mx-1" effect="dark">已签字</el-tag>
                            <el-tag type="warning" class="mx-1" effect="dark">已废除</el-tag>
                            <el-tag type="danger" class="mx-1" effect="dark">签字异常</el-tag>
                        </div>
                        <div class="right">
                            <HcPages :pages="searchForm" @change="pageChange"/>
                        </div>
                    </div>
                </template>
            </HcCard>
        </div>

        <!--上报首件-->
        <HcDrawer :show="isFirstReportDrawer" :isCard="false" uis="hc-first-item-node-layout" to-id="first-item-node-layout-target" @close="FirstReportDrawerClose">
            <div class="node-content">
                <div class="node-form">
                    <el-scrollbar v-if="contractId && isTableForm">
                        <div class="hc-excel-table-form-view" :id="`table-form-${contractId}`"></div>
                    </el-scrollbar>
                    <HcStatus :desc="statusDesc" v-else/>
                </div>
                <div class="node-file">
                    <div class="title">上传总结报告</div>
                    <div class="node-upload-box" v-if="contractId && isTableForm">
                        <HcUpload :fileList="fileListData" :pkeyId="pkeyIds" @finish='uploadChange'/>
                    </div>
                    <div class="node-upload-box" v-else>
                        <el-alert title="表单异常，暂时无法使用上传" type="warning" show-icon :closable="false"/>
                    </div>
                    <el-divider border-style="dashed" />
                    <div class="title">文件附件</div>
                    <div class="hc-table-node-file-box">
                        <HcTable :column="tableFileColumn" :datas="tableFileData" :isIndex="false">
                            <template #action="{row,index}">
                                <el-button type="danger" plain size="small" @click="tableDelButton(index)">删除</el-button>
                            </template>
                        </HcTable>
                    </div>
                </div>
            </div>
            <div class="node-action">
                <el-button type="primary" hc-btn :disabled="!contractId || !isTableForm" :loading="tableFormSaveLoading" @click="saveBussData">
                    <HcIcon name="save"/>
                    <span>保存</span>
                </el-button>
                <el-button hc-btn :disabled="!contractId || !isTableForm" @click="bussPdfInfo">
                    <HcIcon name="eye"/>
                    <span>预览</span>
                </el-button>
                <el-button hc-btn :disabled="!contractId || !isTableForm" :loading="reportLoading" @click="reportModalClick">
                    <HcIcon name="send-plane-2"/>
                    <span>上报</span>
                </el-button>
                <el-button hc-btn @click="FirstReportDrawerClose">
                    <HcIcon name="close"/>
                    <span>返回</span>
                </el-button>
            </div>
        </HcDrawer>

        <!--上报审批-->
        <HcReportModal title="上报审批" url="informationWriteQuery/taskOne" :show="showReportModal" :projectId="projectId" :contractId="contractId" type="first" :typeData="reportTypeData"
                       :taskName="reportTaskName" :ids="reportIds" @hide="showReportModal = false" @finish="showReportFinish"/>
    </div>
</template>

<script setup>
import {useAppStore} from "~src/store";
import {nextTick, onMounted, ref, watch} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import WbsTree from "./components/WbsTree.vue"
import HcUpload from "./components/HcUpload.vue"
import HTableForm from "~src/plugins/HTableForm"
import {getReportNumber,eVisaTaskCheckApi} from "~api/other";
import firstApi from '~api/other/first-item';
import tasksApi from '~api/tasks/data';
import {getStoreData, setStoreData} from '~src/utils/storage'
import {getArrValue, isString, getObjValue, getObjNullValue,deepClone} from "vue-utils-plus"

//变量
const router = useRouter()
const useRoutes = useRoute()
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);
const projectInfo = ref(useAppState.getProjectInfo);
const isCollapse = ref(useAppState.getCollapse)

//路由参数
const routerQuery = useRoutes?.query;
const typeName = routerQuery?.type || 'mark'

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


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

//类型tab数据和相关处理
const tabTypeKey = ref(typeName)
const tabTypeTab = ref([
    {key:'mark',  name: '已标记为首件'},
    {key:'query', name: '首件查询'}
]);
const tabTypeChange = (item) => {
    tabTypeKey.value = item?.key
    if (searchForm.value.wbsId) {
        searchForm.value.current = 1;
        getTableData()
    }
    //路由跳转
    router.push({
        path: useRoutes.path,
        query: {type: item?.key}
    })
}

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

//项目树被点击
const treeItem = ref({})
const nodeWbsElTreeClick = ({data, keys}) => {
    treeItem.value = data
    searchForm.value.contractIdRelation = data['contractIdRelation']
    searchForm.value.wbsId = data['primaryKeyId']
    //缓存自动展开
    TreeAutoExpandKeys.value = keys
    setStoreData('firstItemTreeKeys', keys)
    //获取相关数据
    getReportNumberByContractId(data['contractIdRelation'])
    searchClick()
}

//获取流程状态
const processStatus = ref([])
const firstTaskStatus = async () => {
    const { data } = await tasksApi.queryTaskTypeStatus({
        typeOrStatus: 'first_task_status'
    })
    //处理数据
    processStatus.value = getArrValue(data)
}

//获取上报批次
const reportBatch = ref([])
const getReportNumberByContractId = async (cid) => {
    const { data } = await getReportNumber({
        contractId: contractId.value,
        contractIdRelation: cid ?? ''
    })
    //处理数据
    reportBatch.value = getArrValue(data)
}

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

//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({query,arr}) => {
    betweenTime.value = arr
    searchForm.value.betweenTime = query
}

//回车搜索
const keyUpEvent = (e) => {
    if (e.key === "Enter") {
        searchClick()
    }
}

//搜索
const searchClick = () => {
    if (searchForm.value.wbsId) {
        searchForm.value.current = 1;
        getTableData()
    } else {
        window?.$message?.warning('请先在左边选择一个树节点')
    }
}

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

//表格表头
const tableListColumn = ref([
    {key:'name', name: '文件名称'},
    {key:'waitingUserList', name: '任务人'},
    {key:'startTime', name: '开始时间', width: 180},
    {key:'taskStatusStr', name: '流程状态', width: 140},
    {key:'reportNumber', name: '上报批次', width: 120},
])

//获取表格数据
const tableLoading = ref(false)
const tableListData = ref([])
const getTableData = async () => {
    const searchInfo = searchForm.value
    const tabKey = tabTypeKey.value
    if (!!searchInfo.wbsId) {
        //初始处理
        tableLoading.value = true
        tableListRef.value?.clearSelection()
        tableSelectionKeys.value = []
        tableListData.value = []
        //获取相关数据
        let addFormData = {
            projectId: projectId.value,
            contractId: contractId.value,
            isFirst: 1,
        }
        const treeInfo = treeItem.value
        //已标记的首件
        if (tabKey === 'mark' && addFormData['firstTitle']) {
            delete addFormData.firstTitle
        }
        //查询数据
        if (tabKey === 'query') {
            addFormData['firstTitle'] = 1
        }
        addFormData['wbsId'] = treeInfo['contractIdRelation'] ? treeInfo['id'] : treeInfo['primaryKeyId']
        //处理数据
        const { error, code, data } = await firstApi.getQueryPageData({
            ...addFormData,
            ...searchInfo,
        })
        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 tableListRef = ref(null)
const tableSelectionKeys = ref([]);
const tableSelectionChange = (rows) => {
    tableSelectionKeys.value = rows.filter((item) => {
        return (item??'') !== '';
    })
}

//文件名称被点击
const tableRowName = (row) => {
    //如果 evisaPdfUrl 不为空，使用evisaPdfUrl，反之使用pdfUrl
    if (row['evisaPdfUrl']) {
        window.open(row['evisaPdfUrl'],'_blank')
    } else if (row['pdfUrl']) {
        window.open(row['pdfUrl'],'_blank')
    } else {
        window.$message?.warning('文件不存在')
    }
}

//上报首件
const isFirstReportDrawer = ref(false)
const firstReportClick = () => {
    isFirstReportDrawer.value = true
    tableFileData.value = deepClone(tableSelectionKeys.value)
    getFirstExcelHtml()
}
const FirstReportDrawerClose = () => {
    isFirstReportDrawer.value = false
}

//获取表单
const statusDesc = ref('')
const isTableForm = ref(false)
const pkeyIds = ref('')
const getFirstExcelHtml = async () => {
    const cid = contractId.value;
    const { error, code, data } = await firstApi.getFirstExcelHtml({
        contractId: contractId.value || ''
    }, false)
    //处理数据
    const temp = isString(data?.data) ? data?.data || '' : ''
    if (!error && code === 200 && temp) {
        let pkeyId = data?.id || ''
        pkeyIds.value = pkeyId
        setHTableForm(temp, cid, tableFormData.value)
        getFirstBussDataInfo(pkeyId)
    } else {
        isTableForm.value = false
        statusDesc.value = '暂无表单'
        window?.$message?.warning('暂无表单')
    }
}

//渲染表单
const tableFormApp = ref(null)
const setHTableForm = (resData, cid, info) => {
    //先卸载
    if (tableFormApp.value) {
        tableFormApp.value?.unmount()
    }
    if (resData) {
        isTableForm.value = true
        nextTick(() => {
            tableFormApp.value = HTableForm.createForm({
                template: resData,
                tableForm: info,
                appId: `#table-form-${cid}`
            })
        })
    } else {
        isTableForm.value = false
        statusDesc.value = '暂无表单'
        window?.$message?.warning('暂无表单')
    }
}

//获取回显数据
const tableFormData = ref({})
const getFirstBussDataInfo = async (pkeyId) => {
    if (pkeyId) {
        const { data } = await firstApi.getFirstBussDataInfo({
            contractId: contractId.value || '',
            firstId: pkeyId + ''
        }, false)
        const info = getObjValue(data)
        if (getObjNullValue(info)) {
            HTableForm.setPickerKey(info)
            tableFormData.value = info
        } else {
            tableFormData.value = {}
        }
    } else {
        tableFormData.value = {}
    }
}

//上传变量
const fileListData = ref([]);
const finishFile = ref({
    sourceUrl: '', pdfUrl: '', firstFileName: ''
})
//上传文件
const uploadChange = async ({type, res}) => {
    if (type === 'success') {
        const {code, data, msg} = res
        if (code === 200) {
            finishFile.value = {
                sourceUrl: data?.sourceUrl,
                pdfUrl: data?.pdfUrl,
                firstFileName: data?.fileName,
            }
            window.$message?.success(msg);
        } else {
            window.$message?.error(msg || '上传失败');
        }
    }
}

//文件附件列表
const tableFileColumn = ref([
    {key:'name', name: '文件名称'},
    {key:'action', name: '操作', width: 80, align: 'center'}
]);
const tableFileData = ref([]);
const tableDelButton = (index) => {
    window?.$messageBox?.alert('确定删除该文件吗？', '删除提醒', {
        type: 'warning',
        showCancelButton: true,
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        callback: (action) => {
            if (action === 'confirm') {
                tableFileData.value.splice(index, 1)
            }
        }
    })
}

//填报数据保存
const saveBussData = async () => {
    const { id } = treeItem.value
    const res = await saveExcelBussData(id + '')
    if (res) {
        await getBussPdfInfo(res)
    }
}

//保存请求
const tableFormSaveLoading = ref(false)
const saveExcelBussData = async (pkeyId) => {
    const { primaryKeyId } = treeItem.value
    tableFormSaveLoading.value = true
    const linkIds = rowsToArr(tableFileData.value);
    const { error, code, data } = await firstApi.saveBussData({
        ...tableFormData.value,
        projectId: projectId.value,
        contractId: contractId.value,
        firstNodeId: primaryKeyId,
        pkeyId: pkeyId,
        classify: '1',
        isFirst: 1,
        linkProcessList: linkIds,
        ...finishFile.value
    }, false)
    //判断状态
    tableFormSaveLoading.value = false
    if (!error && code === 200 && isString(data)) {
        window.$message?.success('保存成功')
        return data
    } else {
        window.$message?.error('保存失败')
        return ''
    }
}

//pdf预览
const bussPdfInfo = () => {
    const { id } = treeItem.value
    getBussPdfInfo(id + '')
}

//预览PDF请求
const getBussPdfInfo = async (pkeyId) => {
    const liunkIds = rowsToId(tableFileData.value)
    const { error, code, data } = await firstApi.getFirstBussPdfInfo({
        pkeyId: pkeyId,
        liunkIds: liunkIds
    })
    //判断状态
    const res = isString(data)? data ?? '': ''
    if (!error && code === 200 && res) {
        window.open(res,'_blank')
    }
}

//上报审批
const reportIds = ref('')
const showReportModal = ref(false)
const reportTaskName = ref('')
const reportAddition = ref({})
const reportLoading = ref(false)
const reportTypeData = ref('')
const reportModalClick = async () => {
    const { primaryKeyId, contractIdRelation } = treeItem.value
    const rows = tableFileData.value
    if (rows.length > 0) {
        reportLoading.value = true
        const taskCheck = await eVisaTaskCheckApi({
            projectId: projectId.value,
            contractId: contractId.value
        })
        reportTypeData.value = rows[0]['id']
        reportLoading.value = false
        if (taskCheck) {
            reportIds.value = rowsToId(rows)
            reportTaskName.value = rows.length > 1?`${rows[0].name}等${rows.length}个文件`:rows[0].name
            reportAddition.value = {
                classify: 1,
                isFirst: 1,
                primaryKeyId: primaryKeyId,
                contractIdRelation: contractIdRelation ?? contractId.value,
            }
            showReportModal.value = true
        }
    } else {
        window.$message?.warning('暂无相关数据')
    }
}

//上报完成
const showReportFinish = () => {
    showReportModal.value = false
}

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

//处理数据
const rowsToArr = (rows) => {
    let newArr = [];
    for (let i = 0; i < rows.length; i++) {
        newArr.push({
            id: rows[i]?.id,
            name: rows[i]?.name
        })
    }
    return newArr
}

//左右拖动，改变树形结构宽度
const leftWidth = ref(382)
const onmousedown = () => {
    const leftNum = isCollapse.value ? 142 : 272
    document.onmousemove = (ve) => {
        const 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/other/first-item.scss";
</style>

<style lang="scss">
.hc-first-item-node-layout.el-overlay {
    position: absolute;
    background-color: transparent;
    margin: -24px;
    height: revert;
    .hc-drawer-box.el-drawer {
        --el-drawer-bg-color: transparent;
        .el-drawer__body {
            padding: 24px;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
    }
}
</style>
