<template>
    <div class="hc-table-form-content">
        <div class="hc-content-box">
            <div class="hc-table-forem-box">
                <HcTableForm ref="tableFormRef"
                             :form="tableFormData"
                             :html="excelHtmlData"
                             :loading="loading"
                             :pkey="excelIdVal"
                             @render="tableFormRender"/>
            </div>
            <div v-if="formLogDataList.length > 1" class="hc-fixed-page">
                <el-scrollbar>
                    <div class="hc-fixed-page-list-box">
                        <template v-for="(item, index) in formLogDataList">
                            <div :class="index === formLogIndex ? 'primary' : ''" class="fixed-page-item"
                                 @click="getBussDataInfo(index)">
                                <div class="name-box">
                                    <HcIcon name="sticky-note"/>
                                    <span class="page">第{{ index + 1 }}页</span>
                                </div>
                                <div class="close-box" @click.stop="closeBussDataInfo(index)">
                                    <HcIcon name="close"/>
                                </div>
                            </div>
                        </template>
                    </div>
                </el-scrollbar>
            </div>
            <div class="hc-right-pian-box hc-flex-column">
                <DateCalendar :dateData="dateData" :recordDate="recordDates" @choice-date="dateCalendarChoice"/>
                <el-alert show-icon title="蓝色代表当天已填写过日志" type="warning"/>
                <div v-if="menuItem?.nodeType === 7 || menuItem?.nodeType === 11" class="my-4">
                    <el-button hc-btn type="primary" @click="showProcessModal">
                        <HcIcon name="add-circle"/>
                        <span>关联工序</span>
                    </el-button>
                </div>
                <div v-if="menuItem?.nodeType === 7 || menuItem?.nodeType === 11" class="hc-process-box">
                    <el-scrollbar>
                        <div v-for="(item,index) in processDataList" class="process-item-box">
                            <div class="process-item">{{ item.path }}</div>
                            <HcIcon class="process-icon" fill name="close-circle" @click="deleProcess(index)"/>
                        </div>
                    </el-scrollbar>
                </div>
            </div>
        </div>
        <div class="hc-footer-box">
            <HcTooltip keys="ledger_query_save_form">
                <el-button :disabled="!isTableForm || taskStatus === 3 || taskStatus === 4"
                           :loading="tableFormSaveLoading" hc-btn
                           type="primary" @click="tableFormSaveClick">
                    <HcIcon name="save"/>
                    <span>保存</span>
                </el-button>
            </HcTooltip>
            <HcTooltip keys="ledger_query_report_form">
                <el-button :disabled="!isTableForm || taskStatus === 1 || taskStatus === 3 || taskStatus === 4" hc-btn
                           @click="reportModalClick">
                    <HcIcon name="send-plane-2"/>
                    <span>上报</span>
                </el-button>
            </HcTooltip>
            <HcTooltip keys="ledger_query_preview_form">
                <el-button :disabled="!isTableForm || taskStatus === 1 " :loading="previewLoading" hc-btn
                           @click="previewBussPdf">
                    <HcIcon name="eye"/>
                    <span>预览</span>
                </el-button>
            </HcTooltip>
            <HcTooltip keys="ledger_query_copy_form">
                <el-button :disabled="!isTableForm || taskStatus === 3 || taskStatus === 4" hc-btn
                           @click="copyTableFormClick">
                    <HcIcon name="file-copy-2"/>
                    <span>复制当前表格及内容</span>
                </el-button>
            </HcTooltip>
            <HcTooltip keys="ledger_query_time_form">
                <el-button :disabled="!isTableForm || taskStatus === 3 || taskStatus === 4" hc-btn
                           @click="copyTimeLogModal">
                    <HcIcon name="file-copy-2"/>
                    <span>复制任意时间</span>
                </el-button>
            </HcTooltip>
            <HcTooltip keys="ledger_query_add_form">
                <el-button :disabled="!isTableForm || taskStatus === 3 || taskStatus === 4" hc-btn
                           @click="addTableFormClick">
                    <HcIcon name="add-circle"/>
                    <span>新增表格</span>
                </el-button>
            </HcTooltip>
            <HcTooltip keys="ledger_query_abolish_form">
                <el-button :disabled="!isTableForm || taskStatus === 1  || taskStatus === 2" hc-btn
                           @click="abolishTableFormClick">
                    <HcIcon name="delete-bin-3"/>
                    <span>废除</span>
                </el-button>
            </HcTooltip>
        </div>

        <!--关联工序-->
        <HcDialog :show="processNodeModal" title="选择关联工序" widths="62rem" @close="processNodeModal = false"
                  @save="processNodeClick">
            <div class="node-many-tree">
                <el-tree ref="processElTree" :default-checked-keys="defaultChecked"
                         :default-expanded-keys="defaultExpanded" :load="ElTreeLoadNode" :props="processTreeProps"
                         check-strictly
                         class="my-tree" lazy node-key="primaryKeyId"
                         show-checkbox/>
            </div>
        </HcDialog>

        <!--复制任意时间-->
        <HcDialog :loading="copyTimeLoading" :padding="false" :show="copyTimeModal" isTable saveText="复制"
                  title="复制任意时间"
                  widths="62rem" @close="copyTimeModal = false" @save="copyTimeSaveClick">
            <div class="hc-user-time-box">
                <div class="tree-box">
                    <el-scrollbar>
                        <el-tree :data="copyTimeTreeData" :default-expanded-keys="copyTimeTreeKeys"
                                 :props="copyTimeTreeProps"
                                 accordion class="hc-tree-node" highlight-current
                                 node-key="hierarchy" @node-click="copyTimeTreeNodeClick"/>
                    </el-scrollbar>
                </div>
                <div class="user-box">
                    <HcTable ref="copyTimeTableRef" :column="copyTimeTableColumn" :datas="copyTimeTableData"
                             :loading="copyTimeTableLoading" isCheck @selection-change="copyTimeTableSelection"/>
                </div>
            </div>
        </HcDialog>

        <!--批量上报审批-->
        <HcReportModal :addition="reportAddition" :contractId="contractId" :projectId="projectId"
                       :show="showReportModal" :taskName="reportTaskName" :typeData="menuItem.primaryKeyId"
                       title="日志填报上报"
                       type="log" url="contractLog/startTaskTheLog" @finish="showReportFinish"
                       @hide="showReportModal = false"/>
    </div>
</template>

<script setup>
import {ref, watch, onMounted, onActivated, onDeactivated, onUnmounted} from "vue";
import queryApi from '~api/ledger/query';
import wbsQueryApi from '~api/data-fill/query';
import DateCalendar from "./dateCalendar/index.vue"
import {getObjValue, getObjNullValue, isString, getArrValue, isValueNull} from "vue-utils-plus"
import HcTableForm from "~com/table-form/index.vue";
import {useAppStore} from "~src/store";

const useAppState = useAppStore()
//参数
const props = defineProps({
    projectId: {
        type: [String, Number],
        default: ''
    },
    contractId: {
        type: [String, Number],
        default: ''
    },
    items: {
        type: Object,
        default: () => ({})
    },
    userName: {
        type: [String, Number],
        default: ''
    }
})

//变量
const projectId = ref(props.projectId);
const contractId = ref(props.contractId);
const menuItem = ref(props.items);
const userName = ref(props.userName);
const excelIdVal = ref('');
const tableFormRef = ref(null);


const contractInfo = ref(useAppState.getContractInfo);
const {contractType} = contractInfo.value;
const classifyType = ref(contractType === 2 ? '2' : '1')

//监听
watch(() => [
    props.projectId,
    props.contractId,
    props.items,
    props.userName,
], ([pid, cid, item, name]) => {
    projectId.value = pid
    contractId.value = cid
    menuItem.value = item
    userName.value = name
    getQueryData()
})

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

//获取相关数据
const getQueryData = () => {
    setQueryDataDate()
    const date = recordDate.value ?? {}, time = recordTime.value ?? ''
    getExcelBusinessData(date, time)
}

const setQueryDataDate = () => {
    const {excelId} = menuItem.value
    excelIdVal.value = excelId > 0 ? excelId + '' : ''
}

//日期日历回调
const recordTime = ref('')
const recordDate = ref({})
const recordDates = ref({})
const dateCalendarChoice = ({date, choices, dates}) => {
    recordTime.value = choices
    recordDate.value = date
    recordDates.value = dates
    getExcelBusinessData(date, choices)
}

//获取数据
const loading = ref(false)
const getExcelBusinessData = async (date, choices) => {
    const {primaryKeyId} = menuItem.value
    loading.value = true
    await getTheLogBusinessData(excelIdVal.value, choices)
    await getExcelHtml(excelIdVal.value)
    loading.value = false
    await getSubmitLogDateList(date, primaryKeyId)
    await checkTheLogTaskStatus(choices, primaryKeyId)
}

//获取模板标签数据
const isTableForm = ref(false)
const excelHtmlData = ref('')
const getExcelHtml = async (excelId) => {
    if (excelId) {
        //获取数据
        const {error, code, data} = await queryApi.getExcelHtml({
            contractId: contractId.value || '',
            pkeyId: excelId
        }, false)
        //处理数据
        const resData = isString(data) ? data || '' : ''
        if (!error && code === 200 && resData) {
            excelHtmlData.value = resData
        } else {
            excelHtmlData.value = ''
            isTableForm.value = false
            window?.$message?.warning('暂无表单')
        }
    } else {
        isTableForm.value = false
        window?.$message?.error(`excelId： ${excelId || '-1 或 空'}`)
    }
}

//渲染表单完成
const tableFormRender = (form) => {
    isTableForm.value = form.isRenderForm
}


//表单数据
const formLogDataList = ref([])
const getTheLogBusinessData = async (excelId, recordDate) => {
    const {primaryKeyId} = menuItem.value
    const {data} = await queryApi.getTheLogBusinessData({
        contractId: contractId.value || '',
        pkeyId: excelId,
        nodePrimaryKeyId: primaryKeyId,
        recordTime: recordDate,
        theLogId: ""
    }, false)
    //设置默认数据
    let formArrData = getArrValue(data)
    if (formArrData.length > 0) {
        for (let i = 0; i < formArrData.length; i++) {
            formArrData[i] = setFormDefaultData(formArrData[i])
        }
    } else {
        formArrData = [setFormDefaultData()]
    }
    formLogDataList.value = formArrData
    getBussDataInfo()
}

//获取表单初始数据
const formLogIndex = ref(0)
const tableFormData = ref({})
const getBussDataInfo = (index = 0) => {
    const formLog = formLogDataList.value
    const info = getObjValue(formLog[index])
    formLogIndex.value = index
    if (getObjNullValue(info)) {
        tableFormData.value = info
    } else {
        tableFormData.value = {}
    }
    tableFormRef.value?.setExcelHtml()
    queryCurrentLogSelectProcessList(info?.id ?? '')
}

//获取日期记录
const dateData = ref([])
const getSubmitLogDateList = async ({year}, pid) => {
    if (pid > 0 && year) {
        const {data} = await queryApi.getSubmitLogDateList({
            projectId: projectId.value,
            contractId: contractId.value,
            primaryKeyId: pid,
            year: year
        }, false)
        //处理数据
        dateData.value = getArrValue(data)
    } else {
        dateData.value = []
    }
}

//获取当前资料的任务状态
const taskStatus = ref(1)
const checkTheLogTaskStatus = async (choices, primaryKeyId) => {
    if (primaryKeyId > 0) {
        const {error, code, data} = await queryApi.checkTheLogTaskStatus({
            projectId: projectId.value,
            contractId: contractId.value,
            nodePrimaryKeyId: primaryKeyId,
            recordTime: choices
        }, false)
        //处理数据
        const res = isValueNull(data) ? '' : data || ''
        if (!error && code === 200 && res) {
            //1和2的时候所有按钮皆可操作，废除 除外
            //3和4时, 除了预览和废除 都不行
            taskStatus.value = data
        } else {
            taskStatus.value = 1
        }
    } else {
        taskStatus.value = 1
    }
}

//关联工序
const processNodeModal = ref(false)
const showProcessModal = () => {
    processNodeModal.value = true
}

//树的配置
const processElTree = ref(null)
const processTreeProps = {label: 'title', children: 'children', isLeaf: 'notExsitChild'}
const defaultExpanded = ref([]) //默认展开
const defaultChecked = ref([]) //默认选中

//树形结构异步加载数据
const ElTreeLoadNode = async (node, resolve) => {
    if (node.level === 0) {
        const {error, code, data} = await wbsQueryApi.queryWbsTreeData({
            contractId: contractId.value || '',
            contractIdRelation: '',
            primaryKeyId: '',
            parentId: '',
            classifyType: classifyType.value,
        })
        //处理数据
        if (!error && code === 200) {
            const resData = getArrValue(data)
            resolve(resData)
            defaultExpanded.value = [resData[0]?.primaryKeyId]
        } else {
            resolve([])
        }
    } else {
        const {id, contractIdRelation, primaryKeyId} = node.data
        const {error, code, data} = await wbsQueryApi.queryWbsTreeData({
            contractId: contractId.value || '',
            contractIdRelation: contractIdRelation,
            primaryKeyId: id,
            parentId: contractIdRelation ? primaryKeyId : id,
            classifyType: classifyType.value,
        })
        //处理数据
        if (!error && code === 200) {
            resolve(getArrValue(data))
        } else {
            resolve([])
        }
    }
}

//确认关联工序
const processDataList = ref([])
const processNodeClick = () => {
    const keys = processElTree.value.getCheckedKeys()
    const formIndex = formLogIndex.value
    const formData = formLogDataList.value[formIndex]
    const linkTabIds = getArrValue(formData?.linkTabIds)
    for (let index = 0; index < keys.length; index++) {
        let pathArr = [];
        let node = processElTree.value.getNode(keys[index]);
        getPathName(node, pathArr);
        linkTabIds.push({
            path: pathArr.join('/'),
            primaryKeyId: keys[index]
        });
    }
    formLogDataList.value[formIndex]['linkTabIds'] = linkTabIds
    processDataList.value = linkTabIds
    processNodeModal.value = false
}

//获取节点的路径名字
const getPathName = (node, pathArr) => {
    if (node.parent?.parent) {
        pathArr.unshift(node.data?.title.replace(/(^\s*)|(\s*$)/g, ""));   //去掉头尾空格
        getPathName(node.parent, pathArr);
    } else {
        return; //根节点结束
    }
}

//移除工序
const deleProcess = (index) => {
    const formIndex = formLogIndex.value
    const formData = formLogDataList.value[formIndex]
    const linkTabIds = getArrValue(formData?.linkTabIds)
    linkTabIds.splice(index, 1)
    formLogDataList.value[formIndex]['linkTabIds'] = linkTabIds
    processDataList.value = linkTabIds
}

//保存数据
const tableFormSaveLoading = ref(false)
const tableFormSaveClick = async () => {
    const {primaryKeyId} = menuItem.value
    const res = await saveExcelBussData()
    if (res) {
        await checkTheLogTaskStatus(recordTime.value, primaryKeyId)
        await getBussPdfInfo()
        tableFormSaveLoading.value = false
    }
}

//保存
const saveExcelBussData = async () => {
    let isLinkTabIds = getLinkTabIds(); //处理工序ID
    console.log('orderList:', formLogDataList.value)
    if (isLinkTabIds) {
        tableFormSaveLoading.value = true
        const {error, code, msg} = await queryApi.saveExcelBussData({
            dataInfo: {orderList: formLogDataList.value}
        }, false)
        if (!error && code === 200) {
            window?.$message?.success(msg)
            return true
        } else {
            window?.$message?.warning(msg)
            return false
        }
    }
}

//处理工序数据
const getLinkTabIds = () => {
    let {nodeType} = menuItem.value;
    let isLink = false
    if (nodeType === 7 || nodeType === 11) {
        isLink = formLogDataList.value.some((item) => {
            const linkIds = getArrValue(item?.linkTabIds)
            return linkIds.length > 0
        })
        if (isLink) {
            return true
        } else {
            window?.$message?.warning('请先关联工序')
            return false
        }
    } else {
        return true
    }
}

//预览
const previewLoading = ref(false)
const previewBussPdf = () => {
    getBussPdfInfo()
}

//预览PDF
const getBussPdfInfo = async () => {
    previewLoading.value = true
    const {primaryKeyId} = menuItem.value
    const {error, code, data} = await queryApi.getBussPdfInfo({
        contractId: contractId.value || '',
        pkeyId: excelIdVal.value,
        nodePrimaryKeyId: primaryKeyId,
        recordTime: recordTime.value,
        theLogId: ""
    }, false)
    //处理数据
    previewLoading.value = false
    const resData = isString(data) ? data || '' : ''
    if (!error && code === 200 && resData) {
        window.open(resData, '_blank')
    } else {
        window?.$message?.warning('暂无PDF，无法预览')
    }
}

//获取当前日志资料关联的工序节点信息
const queryCurrentLogSelectProcessList = async (bid) => {
    if (bid) {
        const {error, code, data, msg} = await queryApi.queryCurrentLogSelectProcessList({
            contractId: contractId.value || '',
            businessId: bid ?? ''
        }, false)
        //处理数据
        const formIndex = formLogIndex.value
        if (!error && code === 200) {
            let linkTabIds = getArrValue(data)
            formLogDataList.value[formIndex]['linkTabIds'] = linkTabIds
            processDataList.value = linkTabIds
        } else {
            processDataList.value = []
            if (msg) window?.$message?.warning(msg)
        }
    } else {
        const formIndex = formLogIndex.value
        const formData = formLogDataList.value[formIndex]
        processDataList.value = getArrValue(formData?.linkTabIds)
    }
}

//新增表格
const addTableFormClick = () => {
    const defaultData = setFormDefaultData({})
    formLogDataList.value.push(defaultData)
    const index = formLogDataList.value.length - 1
    getBussDataInfo(index)
}

//复制表格内容
const copyTableFormClick = () => {
    const formLog = formLogDataList.value
    const logIndex = formLogIndex.value
    const defaultData = setFormDefaultData(formLog[logIndex])
    formLogDataList.value.push({
        ...defaultData,
        id: ''
    })
    const index = formLogDataList.value.length - 1
    getBussDataInfo(index)
}

//复制任意时间
const copyTimeModal = ref(false)
const copyTimeLogModal = () => {
    copyTimeModal.value = true
    copyTimeLoading.value = false
    queryReportLogTimeTree()
}

//日期数
const copyTimeTreeProps = {
    children: 'treeList', label: 'name'
}
const copyTimeTreeData = ref([])
const copyTimeTreeKeys = ref([])

//获取当前合同段下本日志节点的填报资料日期树
const queryReportLogTimeTree = async () => {
    const {primaryKeyId} = menuItem.value
    const {data} = await queryApi.queryReportLogTimeTree({
        contractId: contractId.value || '',
        nodePrimaryKeyId: primaryKeyId
    })
    const res = getArrValue(data)
    copyTimeTreeData.value = res
    if (res.length > 0) {
        copyTimeTreeKeys.value = [res[0]?.hierarchy]
    }
}

//日期树被点击
const copyTimeTreeNodeClick = (data) => {
    queryLogTimeTreeList(data?.hierarchy)
}

//复制任意时间的记录人
const copyTimeTableRef = ref(null)
const copyTimeTableColumn = ref([
    {key: 'createUserName', name: '记录人'},
    {key: 'recordTime', name: '时间'},
])
const copyTimeTableData = ref([])

//获取填报记录
const copyTimeTableLoading = ref(false)
const queryLogTimeTreeList = async (time) => {
    copyTimeTableLoading.value = true
    const {primaryKeyId} = menuItem.value
    const {data} = await queryApi.queryLogTimeTreeList({
        contractId: contractId.value || '',
        nodePrimaryKeyId: primaryKeyId,
        time: time
    })
    copyTimeTableLoading.value = false
    copyTimeTableData.value = getArrValue(data)
}

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

//确认复制
const copyTimeLoading = ref(false)
const copyTimeSaveClick = () => {
    const rows = copyTimeTableKeys.value
    if (rows.length > 0) {
        const ids = rowsToId(rows)
        copyTheLogBusinessData(ids)
    } else {
        window.$message?.warning('请先勾选记录人')
    }
}

//复制任意时间
const copyTheLogBusinessData = async (ids) => {
    copyTimeLoading.value = true
    const {primaryKeyId} = menuItem.value
    const {error, code} = await queryApi.copyTheLogBusinessData({
        contractId: contractId.value || '',
        nodePrimaryKeyId: primaryKeyId,
        currentTime: recordTime.value,
        theLogId: ids
    })
    //处理数据
    copyTimeLoading.value = false
    if (!error && code === 200) {
        copyTimeModal.value = false
        window?.$message?.success('复制成功');
        setTimeout(() => {
            window?.location?.reload()  //刷新页面
        }, 3000)
    }
}


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


//设置表单默认数据
const setFormDefaultData = (formInfo = {}) => {
    return {
        linkTabIds: [],
        ...formInfo,
        projectId: projectId.value,
        contractId: contractId.value,
        recordTime: recordTime.value,
        pkeyId: excelIdVal.value,
        isTheLog: "1",
        theLogId: "",
        classify: 1
    }
}

//删除记录
const closeBussDataInfo = (index) => {
    formLogDataList.value.splice(index, 1)
    const logIndex = index <= 0 ? 0 : index - 1
    formLogIndex.value = logIndex
    getBussDataInfo(logIndex)
}

//批量上报
const reportTaskName = ref('')
const reportAddition = ref({})
const showReportModal = ref(false)
const reportModalClick = () => {
    const {primaryKeyId, title} = menuItem.value
    reportTaskName.value = `${recordTime.value} ${title} ${userName.value}`
    reportAddition.value = {
        nodePrimaryKeyId: primaryKeyId,
        recordTime: recordTime.value,
    }
    showReportModal.value = true
}

//上报完成
const showReportFinish = () => {
    showReportModal.value = false
    window?.location?.reload()  //刷新页面
}

//废除
const abolishTableFormClick = () => {
    window?.$messageBox?.alert('是否废除已上报的文件？', '废除文件', {
        showCancelButton: true,
        confirmButtonText: '确定废除',
        cancelButtonText: '取消',
        callback: (action) => {
            if (action === 'confirm') {
                theLogOneAbolish()
            }
        }
    })
}
//确认废除
const theLogOneAbolish = async () => {
    const {primaryKeyId} = menuItem.value
    const {error, code} = await queryApi.theLogOneAbolish({
        projectId: projectId.value,
        contractId: contractId.value,
        nodePrimaryKeyId: primaryKeyId,
        recordTime: recordTime.value
    })
    //处理数据
    if (!error && code === 200) {
        window.$message?.success('废除成功')
        window?.location?.reload()  //刷新页面
    }
}

//缓存被激活时
onActivated(() => {
    setMountKey_down_up()
})

//缓存时被移除
onDeactivated(() => {
    setUnloadKey_down_up()
})


const setMountKey_down_up = () => {
    //全局按键按下监听
    document.onkeydown = async (event) => {
        console.log('按下' + event.key + '键')
        const {key, ctrlKey} = event
        //按下ctrl键
        if (ctrlKey && key === 'Control') {
            tableFormRef.value?.setIsCtrlKey(true)
        }
        //按下复制快捷键
        if (ctrlKey && key === 'c') {
            tableFormRef.value?.setCopyKeyList(event)
        }
        //按下粘贴快捷键
        if (ctrlKey && key === 'v') {
            await tableFormRef.value?.setPasteKeyList(event)
        }
    }
    //全局键盘放开监听
    document.onkeyup = async (event) => {
        const {key, ctrlKey} = event
        if (!ctrlKey && key === 'Control') {
            tableFormRef.value?.setIsCtrlKey(false)
        }
    }
}

const setUnloadKey_down_up = () => {
    document.onkeydown = null
    document.onkeyup = null
}

//页面被卸载
onUnmounted(() => {
    setUnloadKey_down_up()
})
</script>

<style lang="scss" scoped>
@import "./table-form.scss";
</style>

<style lang="scss">
.node-many-tree {
    position: relative;
    .my-tree .el-tree-node .el-checkbox .el-checkbox__inner {
        display: none;
    }
    .my-tree .el-tree-node .is-leaf + .el-checkbox .el-checkbox__inner {
        display: inline-block;
    }
}
.hc-table-form-content .hc-content-box .hc-table-forem-box .hc-fixed-page {
    .el-button {
        display: block;
        margin: 20px;
    }
}
</style>
