<template>
    <div class="data-fill-list-box">
        <el-collapse v-model="activeName" accordion>
            <template v-for="(item,index) in listDatas" :key="item?.pkeyId">
                <el-collapse-item :name="`item-${index}-${item?.pkeyId}`" :disabled="item?.isBussShow == 2" :id="`item-${index}-${item?.pkeyId}`">
                    <template #title>
                        <div class="hc-collapse-item-header">
                            <div class="text-lg truncate item-title">{{item.deptName}}</div>
                            <div class="hc-extra-text-box">
                                <el-tooltip :content="btn_del_table?.textInfo" placement="top" :disabled="!bubbleVal || !btn_del_table?.textInfo" v-if="btn_del_table && item?.isCopeTab === 2">
                                    <el-button type="danger" plain :disabled="item?.isBussShow == 2" @click.stop="delClick(item,index)">删除本表</el-button>
                                </el-tooltip>
                                <el-tooltip :content="btn_copy_table?.textInfo" placement="top" :disabled="!bubbleVal || !btn_copy_table?.textInfo" v-if="btn_copy_table">
                                    <el-button type="primary" plain :disabled="item?.isBussShow == 2" @click.stop="copyClick(item,index)">复制本表</el-button>
                                </el-tooltip>
                                <el-tooltip :content="btn_hide_table?.textInfo" placement="top" :disabled="!bubbleVal || !btn_hide_table?.textInfo" v-if="btn_hide_table">
                                    <el-button type="primary" plain @click.stop="hideClick(item,index)">
                                        <template v-if="item?.isBussShow == 1">隐藏本表</template>
                                        <template v-else>显示本表</template>
                                    </el-button>
                                </el-tooltip>
                                <el-tooltip :content="btn_pre_table?.textInfo" placement="top" :disabled="!bubbleVal || !btn_pre_table?.textInfo" v-if="btn_pre_table">
                                    <el-button type="primary" plain :disabled="item?.isBussShow == 2 || item?.isTabPdf === 1" @click.stop="previewClick(item,index)">预览</el-button>
                                </el-tooltip>
                                <el-tooltip :content="btn_up_table?.textInfo" placement="top" :disabled="!bubbleVal || !btn_up_table?.textInfo" v-if="btn_up_table">
                                    <el-button :type="item?.tabFileType === 2?'success':'primary'" plain :disabled="item?.isBussShow == 2" @click.stop="uploadClick(item,index)">
                                        <template v-if="item?.tabFileType === 2">已上传</template>
                                        <template v-else>上传</template>
                                    </el-button>
                                </el-tooltip>
                            </div>
                        </div>
                    </template>
                    <div class="data-fill-list-item-content">
                        <div class="data-fill-table-form-box">
                            <div :id="`table-form-${item?.pkeyId}`"/>
                            <div class="hc-no-table-form" v-if="item?.isTableForm === false">
                                <div class="table-form-no">
                                    <img :src="notableform" alt=""/>
                                    <div class="desc">暂无表单数据</div>
                                </div>
                            </div>
                        </div>
                        <div class="data-fill-table-tip-box">
                            <div class="text-orange tip-title">
                                <HcIcon name="error" fill ui="text-2xl"/>
                                <span class="ml-1">提示</span>
                            </div>
                            <div class="text-gray-400 tip-item">1、灰色框代表可通过系统识别计算，公式自动引用，可通过公式计算少量数据，(表头数据及简单)，也可只填写白色框数据</div>
                            <div class="text-gray-400 tip-item">2、系统支持键盘中，shift + tab键向上一个填报框切换，tab向下一个填报框切换。暂不支持上下按键切换输入框</div>
                            <div class="table-tip-foot">
                                <div class="tip-left-btn">
                                    <el-tooltip :content="btn_impo_table?.textInfo" placement="top" :disabled="!bubbleVal || !btn_impo_table?.textInfo" v-if="btn_impo_table">
                                        <div class="text-gray-400 dow-text">
                                            <HcIcon name="publish" ui="text-lg"/>
                                            <span class="ml-1">导入列表数据</span>
                                        </div>
                                    </el-tooltip>
                                    <el-tooltip :content="btn_down_table?.textInfo" placement="top" :disabled="!bubbleVal || !btn_down_table?.textInfo" v-if="btn_down_table">
                                        <div class="text-main dow-text">
                                            <HcIcon name="file_download" ui="text-lg"/>
                                            <span class="ml-1">下载导入模板</span>
                                        </div>
                                    </el-tooltip>
                                </div>
                                <div class="tip-right-btn">
                                    <el-tooltip :content="btn_save_table?.textInfo" placement="top" :disabled="!bubbleVal || !btn_save_table?.textInfo" v-if="btn_save_table">
                                        <el-button type="primary" hc-btn size="large" @click="tableFormSaveClick(item,index)">保存</el-button>
                                    </el-tooltip>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-collapse-item>
            </template>
        </el-collapse>
    </div>
</template>

<script setup>
import {ref,watch,nextTick} from "vue";
import {createApp} from "vue/dist/vue.esm-bundler.js";
import {useAppStore} from "~src/store/index";
import notableform from '~src/assets/view/notableform.svg';
import wbsApi from "~api/data-fill/wbs"
import {isString} from "vue-utils-plus"
import {ElInput,ElDatePicker} from 'element-plus'

//初始
const useAppState = useAppStore()
const props = defineProps({
    datas: {
        type: Array,
        default: () => ([])
    },
    projectId: {
        type: [String,Number],
        default: ''
    },
    contractId: {
        type: [String,Number],
        default: ''
    },
    classify: {
        type: [String,Number],
        default: ''
    },
})

//按钮气泡开关
const bubbleVal = ref(useAppState.getBubble);
const projectId = ref(props.projectId)
const contractId = ref(props.contractId)
const listDatas = ref(props.datas)
const classify = ref(props.classify)

//监听
watch(() => [
    props.datas,
    props.projectId,
    props.contractId,
    useAppState.getBubble,
    props.classify,
], ([datas, pid, cid, Bubble,classifyVal]) => {
    listDatas.value = datas
    bubbleVal.value = Bubble
    projectId.value = pid
    contractId.value = cid
    classify.value = classifyVal
    //setFormDataNum(datas)
})

//获取气泡数据
const getButtonsVal = (value) => {
    return useAppState.getButtonsVal(value)
}

const btn_copy_table = ref(getButtonsVal('wbs_copy_table')) //复制本表
const btn_hide_table = ref(getButtonsVal('wbs_hide_table')) //隐藏本表
const btn_pre_table = ref(getButtonsVal('wbs_preview_table')) //预览本表
const btn_up_table = ref(getButtonsVal('wbs_upload_table')) //上传
const btn_del_table = ref(getButtonsVal('wbs_del_table')) //删除

const btn_down_table = ref(getButtonsVal('wbs_download_table')) //下载导入模板
const btn_impo_table = ref(getButtonsVal('wbs_import_table')) //导入列表数据
const btn_save_table = ref(getButtonsVal('wbs_save_table'))//保存本表

//事件
const emit = defineEmits(['uploadTap','itemTap','copyTap','hideTap','previewTap','offsetTop'])

nextTick(() => {
    //setFormDataNum(props.datas)
})

const activeName = ref('')


//展开事件
const updateExpandedNames = (name) => {
    const keys = name.length > 0 ? name[0]:'';
    const names = name.length > 0 ? name[0].split('-'): []
    if (names.length > 0) {
        getOffsetTop(keys)
        const index = names[1]
        const item = listDatas.value[index]
        if (!item.isTableFormRender) {
            getExcelHtml(item,index)
        }
    } else {
        emit('offsetTop', {offsetTop: 0, dom: null})
    }
}

//获取模板标签数据
const getExcelHtml = (item,index) => {
    if (item.pkeyId !== 0) {
        wbsApi.getExcelHtml({
            pkeyId: item.pkeyId + ''
        }).then(({data}) => {
            const res = isString(data.data)?data.data:''
            if (res) {
                item.isTableForm = true
                HTableForm(res, item, index)
            } else {
                item.isTableForm = false
                window?.$message?.warning('清表内容是空的')
            }
        }).catch(() => {
            item.isTableForm = false
        })
    } else {
        item.isTableForm = false
        window?.$message?.warning('pkeyId为空')
    }
}

//渲染模板标签
const formData = ref([])

//设置表单对象的数量
const setFormDataNum = (datas) => {
    if(datas.length > 0) {
        datas.forEach(item => {
            formData.value.push({
                projectId: projectId.value,
                contractId: contractId.value
            })
        })
    }
}

//渲染表格表单
const HTableForm = (templateData,item,index) => {
    const app = createApp({
        data() {
            return {
                formData: formData.value[index],
            }
        },
        template: templateData,
        components: {ElInput,ElDatePicker},
        methods: {
            RightClick(a,b,c,d,e,f,event) {
                event.preventDefault();
                const key = event?.target?.getAttribute('keyname') || ''
                onRightClick(event,key,index)
            },
            getInformation(a,b,c) {

            },
        }
    })
    app.mount(`#table-form-${item.pkeyId}`)
    item.isTableFormRender = true
}

//树的菜单相关变量
const tableFormMenuShow = ref(false)
const tableFormItemNode = ref({})
const tableFormMenuX = ref(0);
const tableFormMenuY = ref(0);

//树的菜单数据
const tableFormMenu = ref([
    {label: '插入设计值/频率', key: "IDVF"},
    {label: '插入特殊字符', key: "special"},
    {label: '关联试验数据', key: "CTD"},
])

//鼠标右键事件
const onRightClick = (event,key,index) => {
    //取光标位置
    let specialDom = document.getElementById(key + "");
    let startPos = specialDom?.selectionStart, endPos = specialDom?.selectionEnd;
    //存储临时信息
    tableFormItemNode.value = {key, index, startPos, endPos}
    //取坐标
    nextTick().then(() => {
        tableFormMenuShow.value = true;
        tableFormMenuX.value = event.clientX;
        tableFormMenuY.value = event.clientY;
    });
}

//鼠标右键菜单被点击
const handleMenuSelect = (key) => {
    //const item = tableFormItemNode.value;
    tableFormMenuShow.value = false;
    if (key === 'IDVF') {
        IDVFModal.value = true
    } else if (key === 'special') {
        specialModalShow()
    } else if (key === 'CTD') {
        CTDModal.value = true
    }
}

const onClickoutside = () => {
    tableFormItemNode.value = {};
    tableFormMenuShow.value = false;
}

//单个保存
const tableFormSaveClick = (item,index) => {
    wbsApi.saveExcelBussData({
        pkeyId: item.pkeyId,
        classify: classify.value,
        ...formData.value[index]
    }).then(({data}) => {
        if(data.code === 200) {
            window?.$message?.success('保存成功')
        } else {
            window?.$message?.warning(data.msg || '保存失败')
        }
    })
}

//删除本表
const delClick = (item,index) => {
    wbsApi.removeBussTabInfo({
        pkeyid: item.pkeyId,
        classify: classify.value,
    }).then(({data}) => {
        if(data.code === 200) {
            window?.$message?.success('操作成功')
            emit('uploadData')
            emit('delTap', {item,index})
        } else {
            window?.$message?.warning(data.msg || '操作失败')
        }
    })
}

//复制本表
const copyClick = (item,index) => {
    emit('copyTap', {item,index})
}
//隐藏本表
const hideClick = (item,index) => {
    emit('hideTap', {item,index})
}
//预览
const previewClick = (item,index) => {
    emit('previewTap', {item,index})
}
//上传被点击
const uploadClick = (item,index) => {
    emit('uploadTap', {item,index})
}

//上传被点击
const getOffsetTop = (key) => {
    const dom = document.getElementById(key)
    emit('offsetTop', dom.offsetTop)
}

//插入设计值/频率
const IDVFModal = ref(false)
const formIDVFRef = ref(null)
const formIDVFModel = ref({
    designValue: '', frequency: ''
})
const formIDVFRules = {
    designValue: {
        required: true,
        trigger: ["blur", "input"],
        message: "请输入设计值"
    },
    frequency: {
        required: true,
        trigger: ["blur", "input"],
        message: "请输入频率"
    }
}

//插入特殊字符
const specialModal = ref(false)
const specialCharacters = ref([
    '&#57344;', "&#57345;", "&#57346;", "&#57347;", '&#8804;', '&#8805;', '&#8451;',
    '&#9312;', '&#9313;', '&#9314;', '&#9315;', '&#9316;', '&#9317;', '&#9318;', '&#9319;', '&#9320;', '&#9321;', '&#9322;', '&#9323;',
    '&#9324;', '&#9325;', '&#9326;', '&#9327;', '&#9328;', '&#9329;', '&#9330;', '&#9331;',
    "&#8544;", "&#8545;", "&#8546;", "&#8547;", "&#8548;", "&#8549;", "&#8550;", "&#8551;", "&#8552;", "&#8553;", "&#8554;", "&#8555;","K̅"
])
const specialRef = ref(null)
const specialValue = ref('')
const specialModalShow = () => {
    specialValue.value = ''
    specialModal.value = true
    nextTick(() => {
        specialRef.value?.focus();
    })
}
const specialClick = (event) => {
    inputInsertValue("specialId", event.target.innerText)
}
//输入框插入内容
const inputInsertValue = (Id,val) => {
    let specialDom = document.getElementById(Id + "").getElementsByTagName('input')[0];
    let startPos = specialDom?.selectionStart, endPos = specialDom?.selectionEnd;
    if (startPos || startPos === 0) {
        let specialVal = specialValue.value;
        specialValue.value = specialVal.substring(0, startPos) + val + specialVal.substring(endPos, specialVal.length)
        specialDom?.focus();
        //设置光标位置
        let posVal = startPos + val.length;
        nextTick(() => {
            specialDom?.setSelectionRange(posVal,posVal)
        })
    } else {
        specialValue.value += val;
        specialDom?.focus();
    }
}

//插入内容
const inputPosInsert = (dom,startPos,endPos,special,value) => {
    let val = value || '', specialVal = special || ''
    console.log(startPos,endPos)
    if (startPos || startPos === 0) {
        val = val.substring(0, startPos) + specialVal + val.substring(endPos, val.length)
        dom?.focus();
        //设置光标位置
        let posVal = startPos + specialVal.length;
        nextTick(() => {
            dom?.setSelectionRange(posVal,posVal)
        })
    } else {
        val += specialVal;
        dom?.focus();
    }
    return val
}

//确认插入
const specialNodeClick = () => {
    const item = tableFormItemNode.value;
    const form = formData.value[item.index]
    let keyDom = document.getElementById(item.key);
    const res = inputPosInsert(keyDom,item.startPos,item.endPos,specialValue.value,form[item.key])
    formData.value[item.index][item.key] = res
    specialModal.value = false
}

//关联试验数据
const CTDModal = ref(false)

</script>

<style lang="scss" scoped>
.data-fill-list-box {
    position: relative;
    .hc-collapse-item-header {
        flex: 1;
        position: relative;
        margin-left: 46px;
        display: flex;
        align-items: center;
        .item-title {
            flex: 1;
            position: relative;
            user-select: none;
            color: #50545E;
            font-size: 16px;
            font-weight: 400;
            cursor: pointer;
        }
        .hc-extra-text-box {
            position: relative;
            padding-right: 24px;
        }
    }
    .data-fill-list-item-content {
        position: relative;
        display: flex;
        height: calc(100vh - 386px);
        .data-fill-table-form-box {
            position: relative;
            padding: 24px 20px;
            height: 100%;
            overflow: auto;
            flex: 1;
            .hc-no-table-form {
                position: relative;
                height: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
                .table-form-no {
                    position: relative;
                    img {
                        width: 350px;
                    }
                    .desc {
                        text-align: center;
                        font-size: 20px;
                        color: #aaa;
                    }
                }
            }
        }
        .data-fill-table-tip-box {
            width: 240px;
            position: relative;
            border-left: 1px solid #E9E9E9;
            padding: 20px 15px 80px;
            .tip-title {
                font-size: 16px;
                margin-bottom: 10px;
                display: flex;
                align-items: center;
            }
            .tip-item {
                margin-bottom: 20px;
            }
            .table-tip-foot {
                position: absolute;
                bottom: 15px;
                right: 0;
                left: 0;
                display: flex;
                align-items: center;
                padding: 0 15px;
                .tip-left-btn {
                    flex: 1;
                    .dow-text {
                        cursor: pointer;
                        display: flex;
                        align-items: center;
                    }
                }
            }
        }
    }
}
.special-box {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid #eee;
    border-radius: 3px;
    height: 60px;
    cursor: default;
    user-select: none;
    transition: color .3s, background-color .3s;
    &:hover {
        color: var(--el-color-primary);
        background-color: var(--el-color-primary-light-3);
    }
    .font-EUDC {
        font-size: 30px;
        cursor: default;
    }
}
</style>

<style lang="scss">
.data-fill-list-box {
    .el-collapse {
        --el-collapse-header-height: 60px;
        border: 0;
        .el-collapse-item {
            margin: 0 0 16px;
            background-color: #f1f5f8;
            border: 1px solid #E9E9E9;
            border-radius: 4px;
        }
        .el-collapse-item__header {
            background-color: transparent;
            font-weight: 400;
            border-bottom: 0;
            cursor: default;
            font-size: 14px;
            .el-collapse-item__arrow {
                position: absolute;
                color: #50545E;
                cursor: pointer;
                left: 20px;
                margin: 0;
            }
        }
        .el-collapse-item.is-active .el-collapse-item__header.is-active {
            background-color: #E7EEF4;
        }
        .el-collapse-item__wrap {
            background-color: transparent;
            border-bottom: 0;
            .el-collapse-item__content {
                position: relative;
                padding-bottom: 0;
                font-size: 14px;
                color: #50545E;
                line-height: initial;
            }
        }
    }
    //设置表单样式
    .data-fill-table-form-box {
        td {
            padding: 6px;
            font-family: "EUDC", 宋体, v-sans, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol" !important;
            .el-input {
                background-color: #ffffff !important;
                border-radius: 3px;
                .el-input__wrapper {
                    background-color: inherit;
                }
                .el-input__wrapper.is-focus, .el-input__wrapper:hover {
                    box-shadow: 0 0 0 1.5px var(--el-input-focus-border-color) inset;
                    background-color: #eddac4;
                }
                //公式 #dcdcdc
                //焦点 #eddac4
            }
        }
    }
}
</style>
