<template>
    <div class="data-fill-list-box">
        <el-collapse v-model="ActiveKey" accordion @change="CollapseChange">
            <el-collapse-item
                v-for="(item, index) in listDatas"
                :id="`item-${index}-${item?.pkeyId}`"
                :key="item?.pkeyId"
                :disabled="item.isBussShow === 2"
                :name="`item-${index}-${item?.pkeyId}`"
            >
                <template #title>
                    <div class="hc-collapse-item-header">
                        <div class="real-fill-rate">
                            <!-- <div
                                class="tag"
                                :class="item.realFillRate >= 80 ? 'yes' : ''"
                            >
                                已填{{ item.realFillRate ?? 0 }}%
                            </div> -->
                            <el-tooltip
                                v-if="userInfo?.role_id?.split(',').includes('1123598816738675201') && item.isSync === 1 && item.isBussShow !== 2"
                                class="box-item"
                                effect="light"
                                content="表单保存后更新"
                                placement="top"
                            >
                                <span
                                    style="border:1px solid orange"
                                    class="h-5 w-5 inline-flex items-center justify-center border border-orange rounded-full bg-white text-xs text-orange"
                                >同</span>
                            </el-tooltip>
                            <el-tooltip
                                v-if="item.dateIsComplete === 2 && item.isBussShow !== 2"
                                class="box-item"
                                effect="light"
                                content="表单日期未完善"
                                placement="top"
                            >
                                <HcIcon name="error-warning" ui=" text-red" />
                            </el-tooltip>
                            <HcTooltip
                                v-if="isStatus !== 3"
                                keys="wbs_preview_table"
                            >
                                <el-link
                                    v-if="
                                        item.isBussShow === 2
                                            || item.isTabPdf === 1
                                            || item.pdfUrl === ''
                                            || item.pdfUrl === null
                                    "
                                    type="primary"
                                    disabled
                                >
                                    本 表 预 览
                                </el-link>
                                <el-link
                                    v-else
                                    type="primary"
                                    :disabled="tableFormPreviewLoading"
                                    @click.stop="previewClick(item)"
                                >
                                    本 表 预 览
                                </el-link>
                            </HcTooltip>
                        </div>
                        <div
                            v-if="
                                item.isBussShow === 1
                                    || item.isBussShow === null
                            "
                            class="item-title truncate text-lg"
                        >
                            {{ item.nodeName }}
                        </div>
                        <div
                            v-else
                            class="item-title truncate text-lg"
                            style="color: #a395d6"
                        >
                            {{ item.nodeName }}
                        </div>
                        <div class="hc-extra-text-box">
                            <HcTooltip
                                v-if="
                                    item.isCopeTab === 2 || item.isCopeTab === 3
                                "
                                keys="wbs_del_table"
                            >
                                <el-link
                                    type="danger"
                                    :disabled="
                                        item.isBussShow === 2
                                            || tableFormDelLoading
                                    "
                                    @click.stop="delClick(item, index)"
                                >
                                    删除本表
                                </el-link>
                            </HcTooltip>
                        
                            <el-link
                                v-if="
                                    treenodeDataInfo?.majorDataType === 8
                                        || treenodeDataInfo?.majorDataType === 9
                                "
                                :disabled="evaluateLoaing"
                                type="primary"
                                @click="evaluate(item)"
                            >
                                评定汇总
                            </el-link>
                            <el-link
                                v-if="isTemplateType"
                                
                                type="primary"
                                @click="autoClick(item)"
                            >
                                自动获取数据
                            </el-link>
                            <HcTooltip keys="wbs_copy_table">
                                <el-link
                                    v-if="
                                        item.isLinkTable === 1
                                            || item.isBussShow === 2
                                    "
                                    type="primary"
                                    disabled
                                >
                                    复制本表
                                </el-link>
                                <el-link
                                    v-else
                                    type="primary"
                                    :disabled="copyClickLoading"
                                    @click.stop="copyClick(item, index)"
                                >
                                    复制本表
                                </el-link>
                            </HcTooltip>
                            <HcTooltip keys="wbs_upload_table">
                                <el-link
                                    :type="
                                        item.tabFileType === 2
                                            ? 'success'
                                            : 'primary'
                                    "
                                    :disabled="isStatus == '3'"
                                    @click.stop="uploadClick(item, index)"
                                >
                                    <template v-if="item.tabFileType === 2">
                                        已上传
                                    </template>
                                    <template v-else>附件上传</template>
                                </el-link>
                            </HcTooltip>
                            <HcTooltip keys="wbs_hide_table">
                                <el-link
                                    v-loading="item?.tableFormHideLoading"
                                    type="primary"
                                    :disabled="item?.tableFormHideLoading"
                                    @click.stop="hideClick(item, index)"
                                >
                                    <template
                                        v-if="
                                            item.isBussShow === 1
                                                || item.isBussShow === null
                                        "
                                    >
                                        隐藏本表
                                    </template>
                                    <template v-else>显示本表</template>
                                </el-link>
                            </HcTooltip>
                        </div>
                    </div>
                </template>
                <div
                    :style="`height: calc(100vh - ${
                        draw_type ? '555px' : '222px'
                    });`"
                    class="data-fill-list-item-content"
                >
                    <div
                        v-if="item?.isWindow"
                        class="data-fill-table-form-box is-window"
                    >
                        <div class="hc-window-tip">
                            <div class="table-form-no">
                                <img :src="NoDataSvg" alt="">
                                <div class="desc">
                                    当前表单处于窗口模式，关闭相关窗口后恢复
                                </div>
                            </div>
                        </div>
                    </div>
                    <div v-else class="data-fill-table-form-box">
                        <TableFormItem
                            v-if="item.isTableRender"
                            :ref="(el) => setItemRefs(el, item)"
                            :classify="classifys"
                            :datas="changeFormDatas(item?.pkeyId, 'collapse')"
                            :kid="item?.pkeyId"
                            :node-name="item.nodeName"
                            :pid="`table-form-${item?.pkeyId}`"
                            :tid="treeId"
                            @excel-body-tap="excelTableFormClick($event)"
                            @render="tableFormRender($event, item, index)"
                            @right-tap="tableFormRightTap($event, index)"
                        />
                        <el-tooltip
                            :content="
                                item.isWindow
                                    ? '关闭窗口并恢复'
                                    : '当前表单窗口化'
                            "
                            :hide-after="0"
                            placement="top"
                        >
                            <div
                                class="form-window-icon"
                                @click.stop="windowClick(item, index)"
                            >
                                <template v-if="item.isWindow">
                                    <HcIcon name="fullscreen-exit" />
                                </template>
                                <template v-else>
                                    <HcIcon name="fullscreen" />
                                </template>
                            </div>
                        </el-tooltip>
                    </div>
                    <div class="data-fill-table-action">
                        <div
                            class="tip-action text-orange"
                            @click="actionTipModal = true"
                        >
                            <hc-icon fill name="information" ui="text-2xl" />
                        </div>
                        <div v-loading="downloadLoading" class="link-action">
                            <HcTooltip keys="wbs_download_table">
                                <el-link
                                    type="primary"
                                    :disabled="downloadLoading"
                                    @click="downModal(item)"
                                >
                                    下载导入模板
                                </el-link>
                            </HcTooltip>
                            <HcTooltip keys="wbs_import_table">
                                <el-link
                                    type="primary"
                                    @click="uploadFileClick(item)"
                                >
                                    导入表格数据
                                </el-link>
                            </HcTooltip>
                        </div>
                        <div class="btn-action">
                            <el-button
                                v-if="isEnableBulk"
                                type="warning"
                                size="small"
                                @click="enableBulkReplication"
                            >
                                关闭批量复制
                            </el-button>
                            <el-button
                                v-else
                                type="warning"
                                size="small"
                                @click="enableBulkReplication"
                            >
                                开启批量复制
                            </el-button>
                            <HcTooltip keys="wbs_save_table">
                                <el-button
                                    :disabled="!item?.isTableForm"
                                    :loading="tableFormSaveLoading"
                                    color="#3794FF"
                                    size="small"
                                    style="color: white"
                                    @click="tableFormSaveClick(item)"
                                >
                                    仅保存本表数据
                                </el-button>
                            </HcTooltip>
                        </div>
                    </div>
                </div>
            </el-collapse-item>
        </el-collapse>
    </div>

    <!-- 右键菜单 -->
    <HcContextMenu
        ref="contextMenuRef"
        :datas="tableFormMenu"
        @item-click="handleMenuSelect"
    />

    <!-- 上传文件 -->
    <hc-new-dialog
        v-model="uploadModal"
        :footer="false"
        title="上传文件"
        widths="38rem"
        @close="uploadModalClose"
    >
        <!-- isStatus == 3 -->
        <HcUpload
            :datas="uploadData"
            :file-list="fileListData"
            :is-canupload="false"
            :auto-upload="false"
            :is-list-file="true"
            @change="uploadChange"
            @close="uploadModalClose"
        />
    </hc-new-dialog>

    <!-- 操作提示 -->
    <hc-new-dialog
        v-model="actionTipModal"
        :footer="false"
        title="操作提示"
        widths="38rem"
        @close="actionTipModalClose"
    >
        <div class="data-fill-table-tip-box">
            <div class="tip-item text-gray-400">
                1、灰色框代表可通过系统识别计算，公式自动引用，可通过公式计算少量数据，(表头数据及简单)，也可只填写白色框数据
            </div>
            <div class="tip-item text-gray-400">
                2、系统支持键盘中，shift +
                tab键向上一个填报框切换，tab向下一个填报框切换。Shift + 上 ( ↑
                )、下 ( ↓ )、左 ( ← )、右 ( → )键，切换填报输入框焦点。
            </div>
            <div class="tip-item text-gray-400">
                3、先点击一下表单任一区域，再键盘按住 ⌘/ctrl +
                点击，选择输入框，变为绿色边框，选中成功。选择完毕后，键盘按
                ⌘/ctrl + c 复制所选中的数据， 再其它表内，或同一张表内，再次按住
                ⌘/ctrl + 点击，选择输入框。键盘按 ⌘/ctrl + v
                依次粘贴所选的数据。（目前仅支持输入框和文本框的操作）
            </div>
            <div class="tip-item text-orange-500">
                4、完善资料填写后记得一定要保存哦
            </div>
        </div>
    </hc-new-dialog>

    <!-- 插入设计值/频率 -->
    <hc-new-dialog
        v-model="designModal"
        :loading="designModalLoading"
        save-text="确认插入"
        title="插入设计值/频率"
        widths="600px"
        @close="closeDesignModal"
        @save="designModalSave"
    >
        <el-alert
            :closable="false"
            title="填写完设计值和频率，系统自动计算实测值"
            type="warning"
        />
        <el-form
            ref="formDesignRef"
            :model="formDesignModel"
            label-width="auto"
            size="large"
        >
            <div class="form-item-div mb-3 text-center">
                <el-radio-group v-model="formDesignModel.type" size="large">
                    <el-radio :value="1">公路工程</el-radio>
                    <el-radio :value="2" class="ml-4">水利水电</el-radio>
                </el-radio-group>
            </div>
            <el-form-item label="设计值">
                <!-- onkeyup="value = value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g,'$1')" -->
                <el-input
                    v-model="formDesignModel.design"
                    placeholder="如果设计值存在两个，则使用 '/' 连接，例如12/23"
                />
            </el-form-item>
            <el-form-item v-if="formDesignModel.type === 1" label="频率">
                <!--  onkeyup="value = value.replace(/^(0+)|[^\d]+/g,'')" -->
                <el-input
                    v-model="formDesignModel.size"
                    placeholder="如果设计值使用 '/' 连接，则频率也是用 '/' 连接，例如5/10"
                />
            </el-form-item>
            <el-form-item v-if="formDesignModel.type === 2" label="容量">
                <!--   onkeyup="value = value.replace(/^(0+)|[^\d]+/g,'')" -->
                <el-input
                    v-model="formDesignModel.capacity"
                    placeholder="如果容量存在两个，则使用 '*'，或者 '/' 连接例如2*4，5/7"
                />
            </el-form-item>
            <el-form-item label="合格点数">
                <el-input
                    v-model="formDesignModel.pass"
                    placeholder="如果设计值使用 '/' 连接，则合格点数也是用 '/' 连接，例如2/5"
                />
            </el-form-item>
            <el-form-item label="偏差范围">
                <el-input
                    v-model="formDesignModel.dev"
                    placeholder="如果设计值使用 '/' 连接，则偏差范围也是用 '/' 连接，例如±2/±3"
                />
            </el-form-item>
            <el-form-item label="方向">
                <el-radio-group
                    v-model="formDesignModel.direction"
                    size="large"
                >
                    <el-radio :value="1">横向</el-radio>
                    <el-radio :value="2" class="ml-4">纵向</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="侧表数据">
                <el-radio-group
                    v-model="formDesignModel.isCopyThisData"
                    size="large"
                >
                    <el-radio :value="false">不复制本表数据</el-radio>
                    <el-radio :value="true" class="ml-4">复制本表数据</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
    </hc-new-dialog>

    <!-- 插入特殊字符 -->
    <hc-new-dialog
        v-model="specialModal"
        :loading="specialModalLoading"
        save-text="确认插入"
        title="插入特殊字符"
        widths="600px"
        @close="specialModalClose"
        @save="specialNodeClick"
    >
        <HcSpecialDiaolg
            v-if="specialModal"
            ref="specialRef"
            @change="specialDiaolgChange"
        />
    </hc-new-dialog>

    <!-- 关联试验数据 -->
    <hc-new-dialog
        v-model="testModal"
        :footer="false"
        :loading="testModalLoading"
        is-table
        title="关联试验数据"
        widths="84%"
        @close="testModalClose"
    >
        <HcTestDiaolg
            v-if="testModal"
            :contract-id="contract_id"
            :project-id="projectId"
            :tenant-id="tenant_id"
            :wbs-id="wbsTemp_id"
            :wbs-type="wbs_type"
            @change="testTableRowName"
        />
    </hc-new-dialog>

    <!-- 选择要插入的数据 -->
    <hc-new-dialog
        v-model="insertDataShow"
        :loading="insertDataLoading"
        is-table
        save-text="保存"
        title="选择需要插入的数据"
        widths="84%"
        @close="cancelinsertData"
        @save="submitinsertData"
    >
        <HcTestData
            v-if="insertDataShow"
            ref="insertDataRef"
            :contract-id="contract_id"
            :project-id="projectId"
            :table-id="itinsertTableId"
            :tree-id="itinsertTreeId"
        />
    </hc-new-dialog>

    <!-- 关联试验文件 -->
    <hc-new-dialog
        v-model="fileModal"
        :loading="fileModalLoading"
        is-table
        save-text="保存"
        title="关联试验文件"
        widths="84%"
        @close="fileModalClose"
        @save="savefileModal"
    >
        <HcTestFile
            v-if="fileModal && !isUseTestTreeCy"
            ref="testFileRefs"
            :contract-id="contract_id"
            :project-id="projectId"
            :tenant-id="tenant_id"
            :tree-id="treeId"
            :wbs-id="wbsTemp_id"
            :wbs-type="wbs_type"
            :table-file-type="fileTypeModal.tableFileType"
        />
       
        <HcTestFileCy
            v-else
            ref="testFileRefsCy"
            :contract-id="contract_id"
            :project-id="projectId"
            :tenant-id="tenant_id"
            :tree-id="treeId"
            :wbs-id="wbsTemp_id"
            :wbs-type="wbs_type"
            :table-file-type="fileTypeModal.tableFileType"
        />
    </hc-new-dialog>

    <!-- 公式参数配置 -->
    <hc-new-dialog
        v-model="formulaModal"
        :loading="formulaModalLoading"
        save-text="保存"
        title="公式参数配置"
        widths="340px"
        @close="formulaModalClose"
        @save="formulaSaveClick"
    >
        <HcFormula
            v-if="formulaModal"
            ref="formulaRefs"
            :key-name="tableFormItemNode.KeyName"
            :contract-id="contractInfo"
            :formparent-id="formparentId"
            :pkey-id="tableFormItemNode.pkeyId"
            :project-id="projectId"
            :check-keys="checkKeys"
        />
    </hc-new-dialog>

    <!-- 查看表单 -->
    <template v-for="(item, index) in DragModalTableForm" :key="index">
        <HcDragModal
            :close-icon-arr="closeIconArr"
            :eid="item.pkeyId"
            :height="DragModalHeight"
            :is-show="item.isShow"
            :loading="item.loading"
            :loading-text="item.loadingText"
            :title="item.title"
            is-sort-top
            @close="TableFormClose(item, index)"
            @close-icon-tap="closeIconTap($event, item, index)"
        >
            <HcDragNode
                :more-menu="dragNodeMoreMenu"
                @menu-tap="dragNodeMoreMenuTap($event, item)"
            >
                <TableFormItem
                    :ref="(el) => setItemRefs(el, item)"
                    :classify="item.classify"
                    :datas="changeFormDatas(item?.pkeyId, 'window')"
                    :height="item.height"
                    :kid="item.pkeyId"
                    :node-name="item.title"
                    :pid="`table-form-${item?.pkeyId}`"
                    :scroll="false"
                    :tid="item.treeId"
                    :width="item.width"
                    @excel-body-tap="excelTableFormClick($event)"
                    @render="tableFormRender($event, item.item, item.index)"
                    @right-tap="tableFormRightTap($event, item.index)"
                />
            </HcDragNode>
        </HcDragModal>
    </template>
    <!-- 复制本表 -->
    <hc-new-dialog
        v-model="showcopyModal"
        :loading="copyClickModalLoading"
        save-text="确认复制"
        title="复制本表"
        widths="84%"
        @close="copyModalClose"
        @save="copySaveClick"
    >
        <HcCopy
            v-if="showcopyModal"
            ref="copyRefs"
            :contract-id="contract_id"
            :project-id="projectId"
            :classify="classifys"
            :tree_AutoExpandKeys="tree_AutoExpandKeys"
            :treenode-data-info="treenodeDataInfo"
            :copy-items="copyItems"
            :copy-modal-type="CopyModalType"
        />
        <template #footer>
            <div class="lr-dialog-footer">
                <div class="left flex items-center">
                    <div class="mr-4">复制方式:</div>
                    <el-radio-group v-model="CopyModalType">
                        <el-radio label="1">跨节点复制</el-radio>
                        <el-radio class="ml-4" label="2">本节点复制</el-radio>
                    </el-radio-group>
                </div>
                <div class="right">
                    <el-button size="large" @click="showcopyModal = false">
                        取消
                    </el-button>
                    <el-button
                        :loading="copyClickModalLoading"
                        hc-btn
                        type="primary"
                        @click="copySaveClick"
                    >
                        确认复制
                    </el-button>
                </div>
            </div>
        </template>
    </hc-new-dialog>

    <!-- 含水率 -->
    <hc-new-dialog
        v-model="waterModal"
        title="含水率"
        @close="waterModalClose"
        @save="waterSaveClick"
    >
        <HcWater
            v-if="waterModal"
            ref="waterRefs"
            :key-name="tableFormItemNode.KeyName"
            :contract-id="contract_id"
            :design-strength="designStrength"
            :p-key-id="tableFormItemNode.pkeyId"
        />
    </hc-new-dialog>

    <!-- 设置自动获取数据 -->
    <hc-dialog v-model="autoModalDialog" title="设置自动获取" @save="autoSaveClick">
        <el-form
            :model="autoModal"
            label-width="auto"
            size="large"
            label-position="left"
        >
            <el-form-item label="数据类型" prop="nodeType">
                <el-select v-model="autoModal.type" multiple block @change="autoChangeType">
                    <el-option
                        v-for="item in dataType"
                        :key="item.dictKey"
                        :label="item.dictValue"
                        :value="item.dictKey"
                    />   
                </el-select>
                <template v-if="isShowNum">
                    <el-input v-model="autoModal.customValue" block placeholder="高程偏差/顶面高差" class="mt-1" />
                </template>
            </el-form-item>
        </el-form>
    </hc-dialog>

    <!-- 插入编号 -->
    <hc-new-dialog
        v-model="pushCodeShow"
        :loading="pushCodeLoading"
        widths="55%"
        save-text="保存"
        title="插入编号"
       
        @close="cancelPushCode"
        @save="submitPushCode"
    >
        <HcPushCode
            v-if="pushCodeShow"
            ref="pushCodeRef"
            :key-val="tableFormItemNode.KeyName"
            :contract-id="contract_id"
            :project-id="projectId"
            :table-id="tableFormItemNode.pkeyId"
            :tree-id="treeId"
            :classify="classifys"
        />
    </hc-new-dialog>
    <!-- 测量偏差 -->
    <hc-new-dialog v-model="deviationShow" title="设置偏差范围" :loading="deviationLoading" @save="deviationSaveClick">
        <el-form
            ref="deviationForm"
            :model="deviationModal"
            label-width="auto"
            size="large"
            :inline="true"
            :rules="rules"
        >
            <div style="display: flex; align-items: center;">
                <el-form-item label=" " style="margin-right: 20px;">
                    <el-radio-group v-model="deviationModal.type" style="display: flex; flex-direction: column;">
                        <el-radio :value="1" style="margin-bottom: 8px;">高程偏差</el-radio>
                        <el-radio :value="2">平面偏差</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label=" " :prop="deviationModal.type === 1 ? 'g8pcfw' : 'g10pcfw'">
                    <el-input v-if="deviationModal.type === 1" v-model="deviationModal.g8pcfw" block placeholder="请输入高程偏差" />
                    <el-input v-else v-model="deviationModal.g10pcfw" block placeholder="请输入平面高差" />
                    <div v-if="deviationModal.type === 1" class="text-orange">格式要求：-n,n或者±n</div>
                    <div v-else class="text-orange">格式要求：0,n</div>
                </el-form-item>
            </div>
        </el-form>
    </hc-new-dialog>

    
    <!-- 选择试验附件类型 -->
    <hc-dialog v-model="fileTypeDialog" title="选择附件类型" :loading="fileTypeLoading" @save="fileTypeSaveClick">
        <el-form
            ref="fileTypeModalRef"
            :model="fileTypeModal"
            label-width="auto"
            size="large"
            label-position="left"
            :rules="fileTypeRules"
        >
            <el-form-item label="选择附件类型" prop="tableFileType">
                <el-select v-model="fileTypeModal.tableFileType" block>
                    <el-option
                        v-for="item in fileType"
                        :key="item.dictKey"
                        :label="item.label" :value="item.value"
                    />   
                </el-select>
            </el-form-item>
        </el-form>
    </hc-dialog>

    <!-- 清除所有数据 -->
    <hc-new-dialog v-model="clearShow" title="清除数据" widths="400px" :footer="false">
        <div class="text-center">
            <div>
                <el-button
                    :loading="clearLoading1"
                    hc-btn
                    type="primary"
                    @click="clearSaveClick(2)"
                >
                    清除所有表单的字段数据
                </el-button>
            </div>
            <div class="mt-2">
                <el-button
                    :loading="clearLoading2"
                    color="#419EFF"
                    hc-btn
                    style="color:white"
             
                    @click="clearSaveClick(1)"
                >
                    仅删除当前表单的字段数据
                </el-button>
            </div>
        </div>
    </hc-new-dialog>
</template>

<script setup>
import {
    nextTick,
    onActivated,
    onDeactivated,
    onMounted,
    onUnmounted,
    ref,
    watch,
} from 'vue'
import HTableForm from '~src/plugins/HTableForm'
import { useAppStore } from '~src/store'
import wbsApi from '~api/data-fill/wbs'
import HcUpload from '../components/HcUpload.vue'
import TableFormItem from './table-form-item.vue'
import HcSpecialDiaolg from './special-diaolg.vue'
import HcTestDiaolg from './test-diaolg.vue'
import HcTestData from './test-data.vue'
import HcPushCode from './push-code.vue'
import HcTestFile from './test-file.vue'
import HcTestFileCy from './test-file-cy.vue'
import HcFormula from './formula.vue'
import HcCopy from './test-copy.vue'
import NoDataSvg from '~src/assets/view/no-data.svg'
import HcWater from './water.vue'
import { getDictionary } from '~api/other'
import {
    arrIndex,
    deepClone,
    downloadBlob,
    getArrValue,
    getObjVal,
    getObjValue,
    isNullES,
    setPosRange,
} from 'js-fast-way'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import { HcDelMsg, HcUploadFileApi } from 'hc-vue3-ui'
import { toPdfPage } from '~uti/btn-auth'
import nodeBaseApi from '~api/data-fill/nodebaseinfo'
import thirdApi from '~api/tentative/detect/third'
import { formValidate } from 'js-fast-way'
import { getDictionaryData } from '~uti/tools'
//参数
const props = defineProps({
    datas: {
        type: Array,
        default: () => [],
    },
    classify: {
        type: [String, Number],
        default: '',
    },
    status: {
        type: [String, Number],
        default: '',
    },
    primaryKeyId: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
    drawType: {
        type: Boolean,
        default: false,
    },
    wbsTempId: {
        type: [String, Number],
        default: '',
    },
    tenantId: {
        type: [String, Number],
        default: '',
    },
    wbsType: {
        type: [String, Number],
        default: '',
    },
    treeAutoExpandKeys: {
        type: [Array],
        default: () => [],
    },
    treenodeDataInfo: {
        type: [Object],
        default: () => ({}),
    },
    newlistdata: {
        type: [Array],
        default: () => [],
    },
    contractInfo:{
        type: [String, Number],
        default: '',
    },
})

//事件
const emit = defineEmits(['renew', 'offsetTop', 'getList'])

//初始变量
const useAppState = useAppStore()

//全局变量
const userInfo = ref(useAppState.getUserInfo)
const projectId = ref(useAppState.projectId)
const contract_id = ref(props.contractId)
const treeId = ref(props.primaryKeyId)
const classifys = ref(props.classify)
const wbsTemp_id = ref(props.wbsTempId)
const tenant_id = ref(props.tenantId)
const wbs_type = ref(props.wbsType)
const isStatus = ref(parseInt(props.status))
const listDatas = ref([])
const draw_type = ref(props.drawType)
const tree_AutoExpandKeys = ref(props.treeAutoExpandKeys)
const treenodeDataInfo = ref(props.treenodeDataInfo)
const newlistdata = ref(props.newlistdata)
const isEnableBulk = ref(true)
// const isEnableBulk = ref(false)
const contractInfo = ref(props.contractInfo)
const isTemplateType = ref(useAppState.contractInfo?.templateType === 2)
//表单变量
const formDataList = ref([])
const formKeyIds = ref('')
const formparentId = ref('')

//处理ref
const itemRefs = ref([])
const setItemRefs = (el, { pkeyId }) => {
    if (el) {
        let index = arrIndex(itemRefs.value, 'pkeyId', pkeyId)
        if (index !== -1) {
            itemRefs.value[index].ref = el
        } else {
            itemRefs.value.push({
                pkeyId: pkeyId,
                ref: el,
            })
        }
    }
}

//处理表单的ref
const setSpliceItemRefs = async ({ pkeyId }) => {
    const refs = itemRefs.value
    let index = arrIndex(refs, 'pkeyId', pkeyId)
    if (index !== -1) {
        refs.splice(index, 1)
        itemRefs.value = refs
    }
}

const closeIconArr = [
    {
        key: 'reduction',
        icon: 'picture-in-picture-2',
        name: '还原到面板内，并自动展开面板',
    },
]

//组件参数变量
const apis = ref({
    dataInfo: wbsApi.getBussDataInfo,
    bussCols: wbsApi.getHtmlBussCols,
    excelHtml: wbsApi.getExcelHtml,
})

//深度监听数据
watch(
    () => props.datas,
    (datas) => {
        setFormDataNum(datas)
    },
    { deep: true },
)

//监听变量值
watch(
    () => [
        useAppState.projectId,
        props.contractId,
        props.wbsTempId,
        props.tenantId,
        props.wbsType,
        props.status,
        props.classify,
        props.primaryKeyId,
        props.newlistdata,
        props.treenodeDataInfo,
        props.contractInfo,
    ],
    ([
        pid,
        cid,
        temp_id,
        tid,
        type,
        status,
        class_id,
        tree_id,
        Newlistdata,
        TreenodeDataInfo,
        cinfo,
    ]) => {
        projectId.value = pid
        contract_id.value = cid
        wbsTemp_id.value = temp_id
        tenant_id.value = tid
        wbs_type.value = type
        isStatus.value = parseInt(status)
        classifys.value = class_id
        treeId.value = tree_id
        newlistdata.value = Newlistdata
        treenodeDataInfo.value = TreenodeDataInfo
        contractInfo.value = cinfo
    },
)

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

    
    setFormDataNum(props.datas)
    setTableFormMenu(useAppState.projectInfo)
    const { offsetHeight } = document.body
    DragModalHeight.value = offsetHeight - 200
    const isBulk = getStoreValue('isEnableBulk')
    isEnableBulk.value = isBulk ?? true
    HTableForm.setEnableBulk(isBulk)
    if (isBulk) setMountOnEventKey()
})

//处理变动的数据
const changeFormData = ref({
    window: [],
    collapse: [],
})
const changeFormDatas = (pkeyId, type) => {
    const changeData = changeFormData.value[type]
    const index = arrIndex(changeData, 'pkeyId', pkeyId)
    if (index !== -1) {
        return changeData[index]
    } else {
        return {}
    }
}

//设置变动的数据
const setChangeFormDatas = async (pkeyId, type) => {
    const refs = await getFormRef(pkeyId)
    const formData = refs?.getFormData()
    const changeData = changeFormData.value[type]
    const index = arrIndex(changeData, 'pkeyId', pkeyId)
    if (index !== -1) {
        changeData[index] = formData
    } else {
        changeData.push(formData)
    }
    changeFormData.value[type] = changeData
}

//展开事件
const ActiveKey = ref('')
const CollapseChange = (name) => {
 
       if (isEnableBulk.value) {
        setMountOnEventKey()
    
    }
    ActiveKey.value = name
    let index = getCollapseItemIndex(name)
    if (index > -1) {
        getOffsetTop(name)
        const item = listDatas.value[index]
        formKeyIds.value = setToString(item.pkeyId)
        formparentId.value = setToString(item.parentId)
        nextTick(() => {
            if (!item.isTableRender) {
                item.isTableRender = true
            }
        })
    } else {
        getOffsetTop()
        formKeyIds.value = ''
        formparentId.value = ''
    }
}

const setCollapseKey = (key) => {
    CollapseChange(key)
}

//初始设置
const setFormDataNum = (datas) => {
    itemRefs.value = []
    //ActiveKey.value = ''
    let newArr = []
    for (let i = 0; i < datas.length; i++) {
        newArr.push({ isCollapseLoad: false })
    }
    formDataList.value = newArr
    listDatas.value = deepClone(datas)
}

//渲染完成
const tableFormRender = (form, item, index) => {
    formDataList.value[index] = form
    formDataList.value[index].isCollapseLoad = form.isRenderForm
    item.isTableForm = form.isRenderForm
}

//菜单数据
const contextMenuRef = ref(null)
const tableFormMenu = ref([])
const tableFormItemNode = ref({}) //临时信息

//设置菜单权限数据
const setTableFormMenu = (info) => {
    let newArr = [],
    infos = getObjValue(info)
// 从infos对象中获取isOpenRandomNumber属性值,如果该属性不存在则返回0
// 用于控制是否开启随机数功能的开关
const isOpen = infos['isOpenRandomNumber'] ?? 0
    if (isTemplateType.value) {
        newArr.push({ label: '设置自动获取数据', key: 'auto' })
    }
    
    if (isOpen === 1 && isStatus.value !== 3) {
        newArr.push({ label: '插入设计值/频率', key: 'design' })
    }
    newArr.push({ label: '插入编号', key: 'pushCode' })
    newArr.push({ label: '测量偏差范围', key: 'deviation' })
    newArr.push({ label: '插入特殊字符', key: 'special' })
    newArr.push({ label: '关联试验数据', key: 'test' })
    newArr.push({ label: '关联试验文件', key: 'file' })
    newArr.push({ label: '公式参数', key: 'formula' })
    newArr.push({ label: '含水率', key: 'water' })


    if (isStatus.value !== 3) {
        newArr.push({ label: '清除所有数据', key: 'clear' }),
            newArr.push({ label: '清除字段数据', key: 'clearcur' })
    }


    tableFormMenu.value = newArr
}

//鼠标右键事件
const tableFormRightTap = (
    { event, KeyName, startPos, endPos, pkeyId },
    index,
) => {
    //存储临时信息
    tableFormItemNode.value = { KeyName, index, startPos, endPos, pkeyId }
    contextMenuRef.value?.showMenu(event, false) //展开菜单
}

const clearShow = ref(false)
const clearLoading = ref(false)
//公式参数批量设置
const checkKeys = ref([])

//鼠标右键菜单被点击
const handleMenuSelect = async ({ key }) => {
    if (key === 'design') {
        setInitDesignForm()
        designModalLoading.value = false
        designModal.value = true
    } else if (key === 'special') {
        specialModalShow()
    } else if (key === 'test') {
        testModalLoading.value = false
        testModal.value = true
    } else if (key === 'file') {
        fileModalLoading.value = false
        console.log('关联试验文件')
        fileTypeModal.value = []
        fileTypeDialog.value = true

        getFileType()
        // fileModal.value = true
        //    getIsUseTestTreeCy()
    } else if (key === 'formula') {
        formulaModalLoading.value = false
        formulaModal.value = true
        const { pkeyId } = tableFormItemNode.value
        const refs = await getFormRef(pkeyId)
        const copyVal = await refs?.getCetCopyKeyList()
   
        checkKeys.value = []
        if (copyVal.length > 0) {
            copyVal.forEach(item=>{
                  checkKeys.value.push(item.key)

            })
        }
   
        
    } else if (key === 'clear') {
   
       
        clearShow.value = true
      
    } else if (key === 'water') {
        console.log('含水率')
        const { pkeyId } = tableFormItemNode.value
        const refs = await getFormRef(pkeyId)
        const formData = refs?.getFormData()
        const strengthKeys = getStoreValue('strengthKeys') //获取设计强度值
        designStrength.value = formData[strengthKeys]
        if (designStrength.value) {
            waterModal.value = true
        } else {
            window.$message.warning('请先选择设计强度')
        }
    } else if (key === 'clearcur') {
        const { pkeyId } = tableFormItemNode.value
        const refs = await getFormRef(pkeyId)
        const curFormData = refs.getFormData()
        const curKeyName = tableFormItemNode.value.KeyName.split('_')[1]
        // 遍历对象的属性
        for (let key in curFormData) {
            // 检查是否是目标元素
            if (key.split('_')[1] === curKeyName) {
                // 替换值
                curFormData[key] = ''
            }
        }
        refs?.setFormData(curFormData)
    } else if (key === 'auto') {
        console.log('自动获取数据')
        
        
        autoModalDialog.value = true
        isShowNum.value = false
        autoModal.value = {
            
        }
        getMajorDataTypeOptions()
    } else if (key === 'pushCode') { 
        pushCodeShow.value = true
        
    } else if (key === 'deviation') {
         deviationShow.value = true
         getDeviationData()
    }
}
const clearLoading1 = ref(false)
const clearLoading2 = ref(false)
const clearSaveClick = async (type)=>{
 
    const { pkeyId, index } = tableFormItemNode.value
     const refs = await getFormRef(pkeyId)
        await HcDelMsg(async (resolve) => {
            const { error, code, msg } = await wbsApi.rmTabdataInfo({
                pkeyId: pkeyId,
                type:type,
            })
            if (!error && code === 200) {
                listDatas.value[index].isTableRender = false
                if (DragModalTableForm.value.length > 0) {
                    let draindex = arrIndex(
                        DragModalTableForm.value,
                        'pkeyId',
                        pkeyId,
                    )
                    DragModalTableForm.value[draindex].isTableRender = false
                }
                await refs?.getTableFormInfo(pkeyId)
                await nextTick()
                listDatas.value[index].isTableRender = true
                listDatas.value[index].isTableForm = true
                if (DragModalTableForm.value.length > 0) {
                    let draindex = arrIndex(
                        DragModalTableForm.value,
                        'pkeyId',
                        pkeyId,
                    )
                    DragModalTableForm.value[draindex].isTableForm = true
                    DragModalTableForm.value[draindex].isTableRender = true
                    listDatas.value[index].isWindow = false
                    DragModalTableForm.value.splice(draindex, 1)
                    await refs?.getTableFormInfo(pkeyId)
                    windowClick(listDatas.value[index], index)
                }
                window.$message.success(msg)
              clearShow.value = false

            } else {
                window.$message.error(msg)
                 clearShow.value = false
            }
           

            resolve() //关闭弹窗的回调
        })

}

//插入设计值
const designModal = ref(false)
const formDesignRef = ref(null)
const formDesignModel = ref()

//初始设计值/频率表单
const setInitDesignForm = () => {
    formDesignModel.value = {
        type: 1,
        design: '',
        size: '',
        dev: '',
        key: '',
        capacity: '',
        pass: '',
        pkId: '',
        direction: 1,
    }
}

//设计值频率计算
const designModalLoading = ref(false)
const designModalSave = async () => {
    const { pkeyId, KeyName } = tableFormItemNode.value
    if (pkeyId) {
        designModalLoading.value = true
        //const {design, size} = formDesignModel.value
        const { error, code, data } = await wbsApi.queryFormulaRange({
            ...formDesignModel.value,
            // dev: (!design && !size) ? '±5': '',
            key: KeyName,
            pkId: pkeyId,
        })
        //处理数据
        const res = getObjVal(data)
        if (!error && code === 200 && res) {
            try {
                const refs = await getFormRef(pkeyId)
                const itemFormData = refs?.getFormData()
                Object.keys(data).forEach((key) => {
                    itemFormData[key] = data[key]
                })
                refs?.setFormData(itemFormData)
                //执行保存
                await tableFormSaveClick(itemFormData)
                //关闭弹窗
                designModalLoading.value = false
                designModal.value = false
            } catch {
                designModalLoading.value = false
                window?.$message?.warning('插入失败，请刷新重试')
            }
        } else {
            designModalLoading.value = false
            window?.$message?.warning('插入失败')
        }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}
//关闭设计值/频率弹窗
const closeDesignModal = () => {
    designModal.value = false
    setInitDesignForm()
}

//插入特殊字符
const specialModal = ref(false)
const specialModalLoading = ref(false)
const specialModalShow = () => {
    specialFormValue.value = ''
    specialModalLoading.value = false
    specialModal.value = true
}

//监听特殊符号输入框的内容
const specialFormValue = ref('')
const specialDiaolgChange = (val) => {
    specialFormValue.value = val
}

//确认插入
const specialRef = ref(null)
const specialNodeClick = async () => {
    specialModalLoading.value = true
    const itemNode = tableFormItemNode.value
    const { KeyName, pkeyId } = itemNode
    try {
        const refs = await getFormRef(pkeyId)
        const itemFormData = refs?.getFormData()
        // eslint-disable-next-line no-unsafe-optional-chaining
        const { code, val, posVal } = await specialRef.value?.getSpecialNode(
            itemNode,
            itemFormData[KeyName],
        )
        if (code === 200 && val) {
            itemFormData[KeyName] = val
            refs?.setFormData(itemFormData)
            specialModalLoading.value = false
            specialModal.value = false
            await nextTick(() => {
                setPosRange(KeyName, posVal)
            })
        } else {
            specialModalLoading.value = false
        }
    } catch (e) {
        specialModalLoading.value = false
    }
}

//关闭插入特殊字符
const specialModalClose = () => {
    specialModalLoading.value = false
    specialModal.value = false
}

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

//关联试验数据被点击
const itinsertTableId = ref('')
const itinsertTreeId = ref('')
const testTableRowName = ({ row, treeId }) => {
    itinsertTableId.value = row.id
    itinsertTreeId.value = treeId
    insertDataLoading.value = false
    insertDataShow.value = true
}

//关闭弹窗
const testModalClose = () => {
    testModal.value = false
    testModalLoading.value = false
}

//选择要插入的实验数据
const insertDataShow = ref(false)
const insertDataLoading = ref(false)

//确定关联试验数据数据
const insertDataRef = ref(null)
const submitinsertData = async () => {
    insertDataLoading.value = true
    const itemNode = tableFormItemNode.value
    const { KeyName, pkeyId } = itemNode
    try {
        const refs = await getFormRef(pkeyId)
        const itemFormData = refs?.getFormData()
        // eslint-disable-next-line no-unsafe-optional-chaining
        const { code, val, posVal }
            = await insertDataRef.value?.submitinsertData(
                itemNode,
                itemFormData[KeyName],
            )
        if (code === 200 && val) {
            itemFormData[KeyName] = val
            refs?.setFormData(itemFormData)
            insertDataLoading.value = false
            insertDataShow.value = false
            testModal.value = false
            await nextTick(() => {
                setPosRange(KeyName, posVal)
            })
        }
    } catch {
        insertDataLoading.value = false
    }
}

//取消关联数据
const cancelinsertData = async () => {
    insertDataShow.value = false
    insertDataLoading.value = false
}

//关联试验文件
const fileModal = ref(false)
const testFileRefs = ref(null)
//确认关联文件
const fileModalLoading = ref(false)
const savefileModal = async () => {
    fileModalLoading.value = true
 
  
    if (!isUseTestTreeCy.value) {
          await testFileRefs.value?.savefileSubmit()
    } else {
        await testFileRefsCy.value?.savefileSubmit()
    }
    fileModalLoading.value = false
    fileModal.value = false
}
//判断与 是否使用成渝试验树
const isUseTestTreeCy = ref(false)
const getIsUseTestTreeCy = async ()=>{
     const { error, code, data } = await thirdApi.isCyAndTestModule({
        projectId: projectId.value,
        contractId:   contract_id.value,
 
     
    })
    if (!error && code === 200) {
       isUseTestTreeCy.value = data

    } else {
       isUseTestTreeCy.value = false
    }
}

//关闭弹窗
const fileModalClose = () => {
    fileModal.value = false
    fileModalLoading.value = false
}
const testFileRefsCy = ref(null)

//公式参数配置
const formulaModal = ref(false)
const formulaRefs = ref(null)

//保存
const formulaModalLoading = ref(false)
const formulaSaveClick = async () => {
    formulaModalLoading.value = true
    await formulaRefs.value?.panelSave()
    const { pkeyId } = tableFormItemNode.value
    const refs = await getFormRef(pkeyId)

    
    refs?.clearCheckKeyList()
    formulaModalLoading.value = false
    formulaModal.value = false

}

//关闭
const formulaModalClose = () => {
    formulaModal.value = false
    formulaModalLoading.value = false
}

//窗口化
const DragModalTableForm = ref([])
const DragModalHeight = ref(600)
const windowClick = async (item, indexs) => {
    const list = deepClone(DragModalTableForm.value)
    let index = arrIndex(list, 'pkeyId', item.pkeyId)
    if (!item.isWindow) {
        const formSize = getTableFormSize(item?.pkeyId)
        const newTableForm = {
            ...setInitDragModalTableForm(item, indexs),
            ...formSize,
        }
        await setChangeFormDatas(item?.pkeyId, 'window')
        item.isWindow = true
        //处理表单的ref
        await setSpliceItemRefs(item)
        //弹窗表单的排序
        if (index === -1) {
            list.push(newTableForm)
        } else if (index !== list.length - 1) {
            //检查是否在最上层，不在则置顶，可以解决多次点击时，频繁更改全局状态的问题
            list.splice(index, 1)
            list.push(newTableForm)
        }
        DragModalTableForm.value = list
        ActiveKey.value = ''
    } else {
        await setChangeFormDatas(item?.pkeyId, 'collapse')
        //处理表单的ref
        await setSpliceItemRefs(item)
        if (index !== -1) {
            list.splice(index, 1)
            DragModalTableForm.value = list
        }
        item.isWindow = false
    }
}

//初始拖动表单的内容
const setInitDragModalTableForm = (item, index) => {
    return {
        projectId: projectId.value,
        contractId: contract_id.value,
        wbsTempId: wbsTemp_id.value,
        tenantId: tenant_id.value,
        wbsType: wbs_type.value,
        classify: classifys.value,
        treeId: treeId.value,
        pkeyId: item.pkeyId,
        height: '100%',
        width: '100%',
        title: item.nodeName,
        isShow: true,
        index: index,
        item: item,
    }
}

//关闭窗口
const TableFormClose = async ({ pkeyId, index }, indexs) => {
    const list = deepClone(DragModalTableForm.value)
    //取表单的数据
    await setChangeFormDatas(pkeyId, 'collapse')
    //关闭窗口
    list.splice(indexs, 1)
    DragModalTableForm.value = list
    listDatas.value[index].isWindow = false
}

const dragNodeMoreMenu = [
    { key: 'save', icon: 'save-2', name: '保存' },
    { key: 'preview', icon: 'eye', name: '预览' },
]

//还原窗口
const closeIconTap = async (event, item, indexs) => {
    const { index, pkeyId } = item
    let KeyId = `item-${index}-${pkeyId}`
    await TableFormClose(item, indexs)
    ActiveKey.value = KeyId
}

//菜单被点击
const dragNodeMoreMenuTap = ({ key }, items) => {
    const { item } = items
    if (key === 'save') {
        if (item?.isTableForm) {
            tableFormSaveClick(item, items)
        } else {
            window.$message.warning('此表单暂无数据和文件')
        }
    } else if (key === 'preview') {
        if (
            item['isBussShow'] === 2
            || item['isTabPdf'] === 1
            || item['pdfUrl'] === ''
            || item['pdfUrl'] === null
        ) {
            window.$message.warning('此表单暂无可预览文件')
        } else {
            previewClick(item, items)
        }
    }
}

//删除本表
const tableFormDelLoading = ref(false)
const delClick = async ({ pkeyId }, index) => {
        HcDelMsg(async (resolve) => {
                if (pkeyId) {
                    if (isStatus.value !== 3) {
                        tableFormDelLoading.value = true
                        const { error, code, msg } = await wbsApi.removeBussTabInfo({
                            pkeyid: pkeyId,
                            classify: classifys.value,
                        })
                        tableFormDelLoading.value = false
                        if (!error && code === 200) {
                            window?.$message?.success('操作成功')
                            //判断是否存在窗口，如果存在，就删除窗口
                            delWindowRefs(pkeyId)
                            // renewData()
                            listDatas.value.splice(index, 1)
                        } else {
                            window?.$message?.error(msg || '操作失败')
                        }
                    } else {
                        window?.$message?.warning('已上报的资料，不允许删除')
                    }
                } else {
                    window?.$message?.warning('pkeyId为空')
                }
            resolve() //关闭弹窗的回调
        })
}
//复制本表相关
const showcopyModal = ref(false)
const copyRefs = ref(null)
const copyModalClose = () => {
    // copyModal.value=false
}
const CopyModalType = ref('1')

const copySaveClick = async () => {
    //本节点复制
    if (CopyModalType.value === '2') {
        const { pkeyId, isTableRender, isTableForm } = copyItems.value
        if (pkeyId) {
            if (isStatus.value !== 3) {
                if (!isTableRender) {
                    await copeBussTab(pkeyId)
                } else if (!isTableForm) {
                    window?.$message?.warning('暂无表单数据')
                } else if (isTableRender) {
                    copyClickLoading.value = true
                    const isSave = await saveExcelBussData(items, null, false)
                    if (isSave) {
                        await copeBussTab(pkeyId)
                    } else {
                        copyClickLoading.value = false
                        window?.$message?.warning('复制本表操作失败')
                    }
                } else {
                    window?.$message?.warning(
                        `数据异常了, isRenderTableForm: ${isTableRender}, isTableForm: ${isTableForm}, pkeyIds：${pkeyId}`,
                    )
                }
            } else {
                window?.$message?.warning('已上报的资料，不允许复制')
            }
        } else {
            window?.$message?.warning('pkeyId为空')
        }
    } else {
        window?.$message?.warning('暂无相关接口')
    }
}
//复制本表
const copyClickModalLoading = ref(false)
const copyClickLoading = ref(false)
const copyClick = async (items) => {
    const { pkeyId, isTableRender, isTableForm } = items
    if (pkeyId) {
        if (isStatus.value !== 3) {
            if (!isTableRender) {
                await copeBussTab(pkeyId)
            } else if (!isTableForm) {
                window?.$message?.warning('暂无表单数据')
            } else if (isTableRender) {
                copyClickLoading.value = true
                const isSave = await saveExcelBussData(items, null, false)
                if (isSave) {
                    await copeBussTab(pkeyId)
                } else {
                    copyClickLoading.value = false
                    window?.$message?.warning('复制本表操作失败')
                }
            } else {
                window?.$message?.warning(
                    `数据异常了, isRenderTableForm: ${isTableRender}, isTableForm: ${isTableForm}, pkeyIds：${pkeyId}`,
                )
            }
        } else {
            window?.$message?.warning('已上报的资料，不允许复制')
        }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}
const copyItems = ref([])
//跨节点复制弹窗
// const copyClick =  (items) => {
//     showcopyModal.value=true
//     copyItems.value=items

// }

//复制表的请求
const copeBussTab = async (pkeyId) => {
    copyClickLoading.value = true
    const { error, code, msg } = await wbsApi.copeBussTab({
        pkeyId: pkeyId,
    })
    copyClickLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success('操作成功')
        // renewData()
        getNewList()
    } else {
        window?.$message?.error(msg || '操作失败')
    }
}

//获取表单列表
const getNewList = () => {
    emit('getList')
    setTimeout(() => {
        let newObj = newlistdata.value
        let oldObj = listDatas.value
        const addedObject = newObj.find(
            (obj) => !oldObj.some((oldObj) => oldObj.pkeyId === obj.pkeyId),
        )
        let index = arrIndex(listDatas.value, 'id', addedObject.id) // 1
        listDatas.value.splice(index + 1, 0, addedObject)
    }, 1000)
}
//隐藏本表
const tableFormHideLoading = ref(false)
const hideClick = async (item, index) => {
    const { pkeyId, isBussShow } = item
    if (pkeyId) {
        if (isStatus.value !== 3) {
            item.tableFormHideLoading = true
            const bussShow = isBussShow === 2 ? 1 : 2 //状态(1显示 2隐藏)
            const { error, code, msg } = await wbsApi.showBussTab({
                pkeyId: pkeyId,
                status: bussShow,
                classify: classifys.value,
                nodeId: treeId.value,
            })
            item.tableFormHideLoading = false
            if (!error && code === 200) {
                window?.$message?.success('操作成功')
                if (isBussShow === 2) {
                    listDatas.value[index].isBussShow = 1
                } else {
                    listDatas.value[index].isBussShow = 2
                    setActiveKey('')
                }
                if (bussShow === 2) {
                    //判断是否存在窗口，如果存在，就删除窗口
                    delWindowRefs(pkeyId)
                }
                // renewData()
            } else {
                window?.$message?.error(msg || '操作失败')
            }
        } else {
            window?.$message?.warning('已上报的资料，不允许隐藏')
        }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}

//预览本表
const tableFormPreviewLoading = ref(false)
const previewClick = async (item, dragItem = null) => {
    tableFormPreviewLoading.value = true
    await getBussPdfInfo(item, dragItem)
    tableFormPreviewLoading.value = false
}

//上传变量
const uploadModal = ref(false)
const fileListData = ref([])
const uploadData = ref({})
//上传附件
const uploadClick = (items, index) => {
    const { pkeyId, isTableForm, isTableRender, isBussShow } = items
    const keyName = `item-${index}-${pkeyId}`
    if (pkeyId) {
        if (isTableForm) {
            uploadModal.value = true
            uploadData.value = {
                projectId: projectId.value,
                contractId: contract_id.value,
                classify: classifys.value,
                pkeyId: pkeyId,
                nodeId: treeId.value,
            }
            //获取文件列表
            getBussFileList(pkeyId)
        } else if (!isTableRender) {
            if (isBussShow !== 2) {
                CollapseChange(keyName)
                window?.$message?.warning('请再次点击上传')
            } else {
                console.log('隐藏表点击')
                uploadModal.value = true
                uploadData.value = {
                    projectId: projectId.value,
                    contractId: contract_id.value,
                    classify: classifys.value,
                    pkeyId: pkeyId,
                    nodeId: treeId.value,
                }
                //获取文件列表
                getBussFileList(pkeyId)
            }
        } else if (!isTableForm) {
            window?.$message?.warning('暂无表单数据')
        }
        // else {
        //     window?.$message?.warning('已上报的资料，不允许上传')
        // }
    } else {
        window?.$message?.warning('pkeyId为空')
    }
}

//获取文件列表
const getBussFileList = async (pkeyId) => {
    const { error, code, data } = await wbsApi.getBussFileList({
        pkeyid: pkeyId,
        classify: classifys.value,
    })
    if (!error && code === 200) {
        fileListData.value = getArrValue(data)
    } else {
        fileListData.value = []
    }
}

//上传文件
const uploadChange = async ({ type }) => {
    if (type === 'success') {
        uploadModal.value = false
        renewData()
    } else if (type === 'del') {
        renewData()
    }
}

//关闭上传附件窗口
const uploadModalClose = () => {
    uploadModal.value = false
}

//单个保存
const tableFormSaveLoading = ref(false)
const tableFormSaveClick = async (item, dragItem = null) => {
    if (isStatus.value !== 3) {
        tableFormSaveLoading.value = true
        const isSave = await saveExcelBussData(item, dragItem)
        if (isSave) {
            // await getBussPdfInfo(item, dragItem)
            tableFormSaveLoading.value = false
            renewData()
        } else {
            tableFormSaveLoading.value = false
        }
    } else {
        window?.$message?.warning('已上报的资料，不允许保存。')
    }
}

//保存表单数据
const inputTitle = ref('')
const saveExcelBussData = async (
    { pkeyId },
    dragItem = null,
    showTip = true,
) => {
    setDragModalLoading(dragItem, '保存中...', true)
    const refs = await getFormRef(pkeyId)
    const isRegExp = await refs?.isFormRegExp()
    if (isRegExp) {
        const formData = refs?.getFormData()
        const { error, code, msg, data } = await wbsApi.saveExcelBussData(formData)
        setDragModalLoading(dragItem)
        if (!error && code === 200) {
            if (showTip) {
                inputTitle.value = data || ''
                window?.$message?.success('保存成功')
            }
            return true
        } else {
            inputTitle.value = ''
            window.$message.error(msg || '操作失败')
            return false
        }
    } else {
        setDragModalLoading(dragItem)
        return false
    }
}

//预览PDF
const getBussPdfInfo = async ({ pkeyId }, dragItem = null, showTip = true) => {
    setDragModalLoading(dragItem, '获取pdf中...', true)
    const { error, code, data } = await wbsApi.getBussPdfInfo(
        {
            pkeyId: pkeyId,
        },
        false,
    )
    setDragModalLoading(dragItem)
    if (!error && code === 200) {
        if (data) {
            toPdfPage(data)
            //window.open(data, '_blank')
        } else if (showTip) {
            window?.$message?.warning('PDF错误')
        }
    } else {
        if (showTip) {
            window?.$message?.warning(data.msg || '获取PDF失败')
        }
    }
}

//通知数据更新
const renewData = () => {
    emit('renew', ActiveKey.value)
    ActiveKey.value = ''
}

//设置表单的加载状态
const setDragModalLoading = (dragItem, text = '保存中...', show = false) => {
    if (dragItem && show) {
        dragItem.loading = true
        dragItem.loadingText = text
    }
    if (dragItem && !show) {
        dragItem.loading = false
    }
}

//获取表单的ref
const getFormRef = async (pkeyId) => {
    const itemRef = getArrValue(itemRefs.value)
    if (itemRef.length <= 0) return ''
    const index = arrIndex(itemRef, 'pkeyId', pkeyId)
    if (index === -1) return ''
    const obj = getObjValue(itemRef[index])
    return obj?.ref
}

//删除打开的窗口
const delWindowRefs = (pkeyId) => {
    //判断是否存在窗口，如果存在，就删除窗口
    const list = DragModalTableForm.value
    const index = arrIndex(list, 'pkeyId', pkeyId)
    if (index !== -1) {
        list.splice(index, 1)
        DragModalTableForm.value = list
    }
}

//计算展开高度和滚动位置
const getOffsetTop = (key = '') => {
    if (key) {
        const dom = document.getElementById(key)
        if (!draw_type.value) {
            if (dom?.offsetTop >= 583 && key) {
                emit('offsetTop', dom?.offsetTop - 583)
            } else {
                emit('offsetTop', dom?.offsetTop)
            }
        } else {
            if (dom.offsetTop >= 424 && key) {
                emit('offsetTop', dom?.offsetTop - 424)
            } else {
                emit('offsetTop', dom?.offsetTop)
            }
        }
    } else {
        emit('offsetTop', 0)
    }
    ActiveKey.value = key
}

//获取折叠面板的索引
const getCollapseItemIndex = (name) => {
    const keys = name.split('-')
    if (keys.length > 0) {
        return keys[1]
    } else {
        return -1
    }
}

//获取表单的大小
const getTableFormSize = (pkeyId) => {
    let formId = `table-form-${pkeyId}`
    try {
        const { clientWidth, clientHeight }
            = document.getElementById(formId).children[0]
        return {
            width: clientWidth + 40 + 'px',
            height: clientHeight + 80 + 'px',
        }
    } catch {
        return {
            width: '100%',
            height: '100%',
        }
    }
}

//转字符串
const setToString = (val) => {
    return val ? val + '' : ''
}

//表单被点击
const presentId = ref('')
const excelTableFormClick = (key) => {
    presentId.value = key
}

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

    
    if (isEnableBulk.value) {
        setMountOnEventKey()
    
    }
})

//开启/关闭 批量复制
const enableBulkReplication = async () => {
    const res = !isEnableBulk.value
    HTableForm.setEnableBulk(res)
    if (res) {
        setMountOnEventKey()
    } else {
        HTableForm.unmountEventKey()
        const refs = await setOnFuncFormRef()
        refs?.setIsCtrlKey(false)
    }
    isEnableBulk.value = res
    setStoreValue('isEnableBulk', res)
}

//缓存时被移除
onDeactivated(() => {
    HTableForm.unmountEventKey()
})

//页面被卸载
onUnmounted(() => {
    HTableForm.unmountEventKey()
})

const setMountOnEventKey = () => {
    HTableForm.setOnEventKey({
        vEnableBulk: isEnableBulk.value,
        //按下ctrl键 或 control 键
        onCtrlDown: async () => {
            //window.$HcLog('全局按键', '按下ctrl键 或 control 键')
            const refs = await setOnFuncFormRef()
            refs?.setIsCtrlKey(true)
        },
        //按下复制快捷键
        onCtrlDownC: async (event) => {
            //window.$HcLog('全局按键', '按下复制快捷键')
            const refs = await setOnFuncFormRef()
            refs?.setCopyKeyList(event)
        },
        //按下粘贴快捷键
        onCtrlDownV: async (event) => {
            //window.$HcLog('全局按键', '按下粘贴快捷键')
            const refs = await setOnFuncFormRef()
            await refs?.setPasteKeyList(event)
        },
        //放开ctrl键 或 control 键
        onCtrlUp: async () => {
            //window.$HcLog('全局按键', '放开ctrl键 或 control 键')
            const refs = await setOnFuncFormRef()
            refs?.setIsCtrlKey(false)
        },
    })
}

//获取表单的ref
const setOnFuncFormRef = async () => {
    const pkeyId = presentId.value
    if (!isNullES(pkeyId)) {
        return await getFormRef(pkeyId)
    } else {
        return
    }
}

//获取已渲染的表单
const getFilterFormData = async () => {
    const formArr = formDataList.value
    return formArr.filter((item) => {
        return (item.pkeyId ?? '') !== '' && item.isCollapseLoad
    })
}

//获取表单数据
const getFormData = async () => {
    const formArr = await getFilterFormData()
    //获取表单数据
    let newArr = []
    for (let i = 0; i < formArr.length; i++) {
        const pkeyId = formArr[i].pkeyId
        const refs = await getFormRef(pkeyId)
        const form = refs?.getFormData()
        newArr.push({ ...form })
    }
    console.log('表单数据', newArr)
    return newArr
}

//获取表单效验数据
const getFormRegExpJson = async () => {
    const formArr = await getFilterFormData()
    const list = listDatas.value
    //获取表单数据
    let formRegExpJson = {}
    for (let i = 0; i < formArr.length; i++) {
        const pkeyId = formArr[i].pkeyId
        const refs = await getFormRef(pkeyId)
        const regExp = refs?.getRegExpJson()
        const nodeName = refs?.getNodeName()
        if (getObjVal(regExp)) {
            const index = arrIndex(list, 'pkeyId', pkeyId)
            formRegExpJson[pkeyId] = {
                ...regExp,
                itemId: `item-${index}-${pkeyId}`,
                nodeName: nodeName,
            }
        }
    }
    return formRegExpJson
}

//获取当前展开项
const getActiveKey = () => {
    return ActiveKey.value
}

//设置当前展开项
const setActiveKey = (key) => {
    return (ActiveKey.value = key)
}
//导入模板
const checkItem = ref({})
//打开文件选择框
const uploadFileClick = (item) => {
    checkItem.value = item
    HcUploadFileApi({
       // url: '/api/blade-manager/wbsTreeContract/import-excel',
        url: '/api/blade-manager/wbsTreeContract/import-excel-list',
        accept: '.png,.jpg,jpeg,.xls,.xlsx,.pdf,.doc,.docx',
        accept_tip: '图片(png、jpg、jpeg)<br/>Excel(xls、xlsx)<br/>PDF<br/>Word(doc、docx)',
        size: 80,
        multiple: false,
        params: { pKeyId: item.pkeyId },
        success: async (file, res) => {
            const refs = await getFormRef(item.pkeyId)
            refs?.setFormData(res.data)
            window.$message.success('文件上传成功')
        },
        error: () => {
            window.$message.error('文件上传失败')
        },
    })
}

const downloadLoading = ref(false)
const getdownloadExcel = async (pKeyId) => {
    downloadLoading.value = true
    const { error, disposition, res } = await wbsApi.downloadExcel({
        pKeyId: pKeyId,
    })
    //处理数据
    downloadLoading.value = false
    if (!error) {
        if (disposition) {
            downloadBlob(res, disposition)
        } else {
            window.$message?.error('数据异常')
        }
    }
}
//下载模板
const downModal = (item) => {
    const { pkeyId } = item
    getdownloadExcel(pkeyId)
}

//含水率弹窗
const waterModal = ref(false)
const waterModalClose = () => {
    waterModal.value = false
}
const waterRefs = ref(null)
const designStrength = ref('') //设计强度值
const waterSaveClick = async () => {
    let resdata = await waterRefs.value?.waterSave()
    const { pkeyId } = tableFormItemNode.value
    const refs = await getFormRef(pkeyId)
    refs?.setFormData(resdata)
    waterModal.value = false
}

//操作提示
const actionTipModal = ref(false)
const actionTipModalClose = () => {
    actionTipModal.value = false
}
//评定汇总---未测
const evaluateLoaing = ref(false)
const evaluate = async (item) => {
    const { projectId } = item
    evaluateLoaing.value = true
    const { error, code, msg, data } = await wbsApi.evaluateIsWater({
        projectId: projectId,
    })
    if (!error && code === 200) {
        getEvaluteData(data, item)
    } else {
        window?.$message?.error(msg || '操作失败')
    }
}

const getEvaluteData = async (isRes, item) => {
    const { pkeyId } = item

    evaluateLoaing.value = true
     const apiCall = isRes ? wbsApi.evaluateTotalNew : wbsApi.evaluateTotal
            const { error, code, msg } = apiCall({
            tablePkeyId: pkeyId,
        })
        evaluateLoaing.value = false
        if (!error && code === 200) {
            window?.$message?.success('操作成功')

            renewData()
        } else {
            window?.$message?.error(msg || '操作失败')
        }
}

//设置自动获取
const autoModalDialog = ref(false)
const autoModal = ref({
    type:'',
})
const dataType = ref([])
const getMajorDataTypeOptions = async () => {
    const { data } = await getDictionary({ code:'auto_retrieve' })
    dataType.value = data
   
}
const isShowNum = ref(false)
const autoChangeType = (val)=>{

isShowNum.value = String(val).includes('8')
}
const autoSaveClick = async ()=>{
    const { KeyName, pkeyId } = tableFormItemNode.value
    const refs = await getFormRef(pkeyId)
    const itemFormData = refs?.getFormData()
    let max
    let min

     if (isShowNum.value && !autoModal.value.customValue ) {
        window.$message?.error('高程偏差/顶面偏差')
        return
    }
    if (isShowNum.value && autoModal.value?.customValue.length > 0) {
const values = autoModal.value.customValue.split('/')
// 检查格式是否为 数字/数字
if (values.length !== 2) {
    window.$message?.error('请输入正确格式的高程偏差/顶面高差')
    return
}

// 检查两个值是否都是合法数字
const isValidNumber = (num) => !isNaN(num) && num.toString().trim().length > 0

if (!isValidNumber(values[0]) || !isValidNumber(values[1])) {
    window.$message?.error('请输入正确的数字格式')
    return
}

min = values[0]
max = values[1]
         min = autoModal.value.customValue.split('/')[0]
        max = autoModal.value.customValue.split('/')[1]
    } 


    const { error, code, msg, data } = await nodeBaseApi.getNodeBaseInfoByPkeyId(

        {
            nodeId: treeId.value,
            pkeyId: pkeyId,
            autoType:autoModal.value.type.join(','),
            max:max,
            min:min,
            paramName:KeyName,
        },
    )


    if (!error && code === 200) {
        console.log(data, 'data')
        itemFormData[KeyName] = data
        refs?.setFormData(itemFormData)
       window.$message?.success(msg || '操作成功')
       autoModalDialog.value = false

    
    } 
}
const autoClick = async (item)=>{
    console.log(item, 'item')

    const { pkeyId } = item
    // Close collapse panel
    ActiveKey.value = ''
    await nextTick()
    setTimeout(async () => {
        const refs = await getFormRef(pkeyId)
        const { error, code, msg, data } = await nodeBaseApi.getAllNodeBaseInfoByPkeyId(
                {
                nodeId: treeId.value,
                pkeyId: pkeyId,
                },
        )

        if (!error && code === 200) {
        console.log(data, 'data')
        refs?.setFormData(data)

        } 
    }, 1000)
}
//插入编号
const pushCodeShow = ref(false)
const pushCodeLoading = ref(false)
const cancelPushCode = () => {
    pushCodeShow.value = false
    pushCodeLoading.value = false
}
const submitPushCode = async ()=>{
    pushCodeLoading.value = true
    const data = await pushCodeRef.value?.saveBatchCode()
     pushCodeLoading.value = false

        if (data) {
            renewData()
            cancelPushCode()
        }
     
    
}
const pushCodeRef = ref(null)
//测量偏差
const deviationShow = ref(false)
const deviationLoading = ref(false)
const deviationModal = ref({ type:1 })
//获取偏差范围
const getDeviationData = async () => {
    const { pkeyId } = tableFormItemNode.value
    const { error, code, msg, data } = await wbsApi.getDeviationRange(
        { pKeyId: pkeyId },
    )
    if (!error && code === 200) {
        // 从数组中找出k为"g8pcfw"和"g10pcfw"的对象，并提取v值
        const g8pcfwObj = data.find(item => item.k === 'g8pcfw')
        const g10pcfwObj = data.find(item => item.k === 'G10pcfw')
        
        // 将找到的v值赋给deviationModal对应的属性
        deviationModal.value.g8pcfw = g8pcfwObj ? g8pcfwObj.v : ''
        deviationModal.value.g10pcfw = g10pcfwObj ? g10pcfwObj.v : ''
    } else {
        // 请求失败时清空这两个值
        deviationModal.value.g8pcfw = ''
        deviationModal.value.g10pcfw = ''
    }
}  
const validateDeviation = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入偏差值')) // 空值提示
    return
  }

  // 正则匹配：-n,n 或 ±n 格式
  const isValid = /^(-?\d+[，,]\d+|±\d+)$/.test(value)
  if (!isValid) {
    callback(new Error('格式错误！请输入 -n,n 或 ±n'))
  } else {
    callback() // 验证通过
  }
}

// 表单规则
const rules = {
  g8pcfw: [{ validator: validateDeviation, trigger: 'blur' }], // 高程偏差验证
  g10pcfw: [{ validator: validateDeviation, trigger: 'blur' }], // 平面偏差验证
}
const deviationForm = ref(null)
const deviationSaveClick = async ()=>{
        const validate = await formValidate(deviationForm.value, rules)
     if (!validate) {
        return false
     }
     const { pkeyId } = tableFormItemNode.value
     deviationLoading.value = true
        const { error, code, msg, data } = await wbsApi.setDeviationRange(
        {
            g8pcfw: deviationModal.value.g8pcfw,
            g10pcfw: deviationModal.value.g10pcfw,
            pKeyId: pkeyId,
           
        },
    )

  deviationLoading.value = false
    if (!error && code === 200) {
       window.$message?.success(msg || '操作成功')
      deviationShow.value = false
    
}
}

//选择附件类型
const fileTypeDialog = ref(false)
const fileTypeSaveClick = ()=>{
         fileModal.value = true
           getIsUseTestTreeCy()

}
const fileTypeModal = ref({
    tableFileType: '',
   
})
const fileTypeLoading = ref(false)
const fileType = ref([])
const getFileType = async ()=>{
      fileType.value = await getDictionaryData('table_file_type', true )
}
const fileTypeRules = {
      tableFileType: {
        required: true,
        trigger: 'blur',
        message: '请选择附件类型',
    },
  
}

// 暴露出去
defineExpose({
    getFormData,
    getFormRegExpJson,
    getActiveKey,
    setActiveKey,
    setCollapseKey,
})
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>

<style lang="scss">
@import "./style.scss";
</style>
