<template>
    <div class="hc-layout-content">
        <div class="hc-content-box">
            <div class="hc-table-forem-box">
                <el-scrollbar v-if="excelIdVal && isTableForm">
                    <div class="hc-excel-table-form-view" :id="`table-form-${excelIdVal}`"></div>
                </el-scrollbar>
                <HcStatus :desc="statusDesc" v-else/>
            </div>
            <div class="hc-right-pian-box hc-flex-column">
                <DateCalendar :dateData="dateData" @choice-date="dateCalendarChoice"/>
                <el-alert title="蓝色代表当天已填写过日志" type="warning" show-icon/>
                <div class="my-4" v-if="menuItem?.nodeType === 7 || menuItem?.nodeType === 11">
                    <el-button type="primary" hc-btn @click="showProcessModal">
                        <HcIcon name="add-circle"/>
                        <span>关联工序</span>
                    </el-button>
                </div>
                <div class="hc-process-box" v-if="menuItem?.nodeType === 7 || menuItem?.nodeType === 11">
                    <el-scrollbar>
                        <div class="process-item-box" v-for="(item,index) in processDataList">
                            <div class="process-item">{{item.pathName}}</div>
                            <HcIcon name="close-circle" fill class="process-icon" @click="deleProcess(index)"/>
                        </div>
                    </el-scrollbar>
                </div>
            </div>
        </div>
        <div class="hc-footer-box">
            <HcTooltip keys="ledger_query_save_form">
                <el-button type="primary" hc-btn :disabled="!isTableForm" :loading="tableFormSaveLoading" @click="tableFormSaveClick">
                    <HcIcon name="save"/>
                    <span>保存</span>
                </el-button>
            </HcTooltip>
            <HcTooltip keys="ledger_query_report_form">
                <el-button hc-btn :disabled="!isTableForm">
                    <HcIcon name="send-plane-2"/>
                    <span>上报</span>
                </el-button>
            </HcTooltip>
            <HcTooltip keys="ledger_query_preview_form">
                <el-button hc-btn :disabled="!isTableForm" :loading="previewLoading" @click="previewBussPdf">
                    <HcIcon name="eye"/>
                    <span>预览</span>
                </el-button>
            </HcTooltip>
            <HcTooltip keys="ledger_query_copy_form">
                <el-button hc-btn :disabled="!isTableForm">
                    <HcIcon name="file-copy-2"/>
                    <span>复制当前表格及内容</span>
                </el-button>
            </HcTooltip>
            <HcTooltip keys="ledger_query_time_form">
                <el-button hc-btn :disabled="!isTableForm">
                    <HcIcon name="file-copy-2"/>
                    <span>复制任意时间</span>
                </el-button>
            </HcTooltip>
            <HcTooltip keys="ledger_query_add_form">
                <el-button hc-btn :disabled="!isTableForm">
                    <HcIcon name="add-circle"/>
                    <span>新增表格</span>
                </el-button>
            </HcTooltip>
        </div>

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

    </div>
</template>

<script setup>
import {ref, watch, nextTick} from "vue";
import queryApi from '~api/ledger/query';
import wbsQueryApi from '~api/data-fill/query';
import {HTableForm} from "~src/plugins/HTableForm"
import DateCalendar from "./dateCalendar/index.vue"
import {getObjValue, getObjNullValue, isString, getArrValue} from "vue-utils-plus"

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

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

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

//渲染完成
nextTick(() => {
    getQueryData()
})

//获取相关数据
const getQueryData = () => {
    const item = menuItem.value
    const eid = item?.excelId > 0 ? item?.excelId + '' : ''
    excelIdVal.value = eid
    getExcelHtmlData(eid)
    getSubmitLogDateList(item?.primaryKeyId)
}

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

//表格表单渲染
const isTableForm = ref(false)
const getExcelHtmlData = async (excelId) => {
    if (excelId) {
        getBussDataInfo(excelId)
        getExcelHtml(excelId)
    } else {
        statusDesc.value = `excelId： ${excelId || '-1 或 空'}`
        isTableForm.value = false
    }
}

//获取表单初始数据
const tableFormData = ref({})
const getBussDataInfo = async (excelId) => {
    const { data } = await queryApi.getBussDataInfo({
        pkeyId: excelId
    }, false)
    const info = getObjValue(data)
    if (getObjNullValue(info)) {
        const pickerKey = info['pickerKey'] || ''
        const pickerKeys = pickerKey.split(',')
        for (let i = 0; i < pickerKeys.length; i++) {
            const val = info[pickerKeys[i]] || ''
            if (val) {
                const data = val.replace(/'/g,'"');
                info[pickerKeys[i]] = JSON.parse(data)
            } else {
                info[pickerKeys[i]] = []
            }
        }
        //有数据，关联数据
        tableFormData.value = info
    } else {
        tableFormData.value = {}
    }
}

//获取模板标签数据
const getExcelHtml = async (excelId) => {
    //获取数据
    const { error, code, data } = await queryApi.getExcelHtml({
        pkeyId: excelId
    }, false)
    //处理数据
    const resData = isString(data) ? data || '' : ''
    if (!error && code === 200 && resData) {
        isTableForm.value = true
        //渲染表单
        await nextTick(() => {
            HTableForm({
                template: resData,
                tableForm: tableFormData.value,
                appId: `#table-form-${excelId}`
            })
        })
    } else {
        isTableForm.value = false
        statusDesc.value = '暂无表单'
        window?.$message?.warning('暂无表单')
    }
}

//关联工序
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: ''
        })
        //处理数据
        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
        })
        //处理数据
        if (!error && code === 200) {
            resolve(getArrValue(data))
        } else {
            resolve([])
        }
    }
}

//确认关联工序
const processDataList = ref([])
const processNodeClick = () => {
    const keys = processElTree.value.getCheckedKeys();
    let NodesArr = []
    for (let index = 0; index < keys.length; index++) {
        let pathArr = [];
        let node = processElTree.value.getNode(keys[index]);
        getPathName(node, pathArr);
        NodesArr.push({
            primaryKeyId: keys[index],
            pathName: pathArr.join('/')
        })
    }
    processDataList.value = NodesArr
    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) => {
    processDataList.value.splice(index, 1);
}

//保存数据
const tableFormSaveLoading = ref(false)
const tableFormSaveClick = async () => {
    const res = await saveExcelBussData()
    if (res) {
        await getBussPdfInfo()
    }
}

//保存
const saveExcelBussData = async () => {
    let linkTabIds = setProcessData(); //处理工序ID
    if (linkTabIds) {
        tableFormSaveLoading.value = true
        const { error, code } = await queryApi.saveExcelBussData({
            ...tableFormData.value,
            classify: 1,
            projectId: projectId.value,
            contractId: contractId.value,
            pkeyId: excelIdVal.value,
            linkTabIds: linkTabIds,
            isTheLog: "1",
            theLogId: "",
            recordTime: recordTime.value
        },false)
        tableFormSaveLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('保存成功')
            return true
        } else {
            window?.$message?.warning('保存失败')
            return false
        }
    }
}

//处理工序数据
const setProcessData = () => {
    let linkTabIds = [], {nodeType} = menuItem.value;
    if (nodeType === 7 || nodeType === 11) {
        const nodes = processDataList.value || [];
        if (nodes.length > 0) {
            for (let i = 0; i < nodes.length; i++) {
                let item = nodes[i];
                linkTabIds.push({
                    path: item['pathName'],
                    primaryKeyId: item['primaryKeyId']
                })
            }
            return linkTabIds
        } else {
            window?.$message?.warning('请先关联工序')
            return false
        }
    } else {
        return true
    }
}

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

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

</script>

<style lang="scss" scoped>
.hc-layout-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    position: relative;
    margin-left: 24px;
    height: 100%;
    .hc-content-box {
        flex: 1;
        display: flex;
        position: relative;
        margin-bottom: 24px;
        height: calc(100% - 105px);
        .hc-table-forem-box {
            flex: 1;
            padding: 24px;
            margin-right: 24px;
            position: relative;
            background: #f1f5f8;
            border-radius: 10px;
            box-shadow: -2px 0px 10px 0px rgba(32,37,50,0.03), 0px 10px 21px 20px rgba(32,37,50,0.03);
        }
        .hc-right-pian-box {
            width: 360px;
            position: relative;
            padding: 24px 20px;
            background: #f1f5f8;
            border-radius: 10px;
            box-shadow: -2px 0px 10px 0px rgba(32,37,50,0.03), 0px 10px 21px 20px rgba(32,37,50,0.03);
            .hc-process-box {
                position: relative;
                flex: 1;
                overflow: hidden;
                .hc-scrollbar-box {
                    display: contents;
                }
                .process-item-box {
                    position: relative;
                    color: #838791;
                    font-size: 14px;
                    padding: 8px 0;
                    display: flex;
                    align-items: flex-start;
                    .process-item {
                        position: relative;
                        flex: 1;
                    }
                    .process-icon {
                        font-size: 20px;
                        cursor: pointer;
                        margin-left: 16px;
                        transition: color 0.2s;
                        &:hover {
                            color: var(--el-color-primary-light-3);
                        }
                    }
                }
                .process-item-box + .process-item-box {
                    border-top: 0.5px solid #e9e9e9;
                }
            }
        }
    }
    .hc-footer-box {
        position: relative;
        height: 80px;
        background: #f1f5f8;
        border-radius: 10px;
        display: flex;
        align-items: center;
        padding: 20px 24px;
        box-shadow: -2px 0px 10px 0 rgba(32,37,50,0.03), 0 -10px 21px 3px rgba(32,37,50,0.03);
        overflow: hidden;
    }
}
</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;
    }
}
</style>
