<template>
    <MOSTY.PageTree
        ref="pageTreeRef"
        :pageTitle="'目标/指标库'"
        searchType="02"
        :isShowLeftTree="filterqx('isSgs') == '1' && activeTab != '01' && isShowLeftTree"
        @getDeptId="getDeptId"
        @collapse="collapse"
    >
        <template #serach>
            <el-divider />
            <div
                style="display: flex; justify-content: space-between; align-items: center"
            >
                <div class="tab-container">
                    <el-tabs v-model="activeTab" type="card" @tab-click="onTabClick">
                        <el-tab-pane
                            :label="item.label"
                            :name="item.value"
                            v-for="(item, i) in tabList"
                            :key="i"
                        />
                    </el-tabs>
                </div>
                <div class="btnBox">
                    <!-- 只有省安全部门才能增删改 -->
                    <el-button v-if="isSjAqglk" type="primary" @click="add">
                        <!-- v-if="ssdept.orgBizType == '04'" -->
                        <el-icon>
                            <CirclePlus />
                        </el-icon>
                        <span>新增</span>
                    </el-button>
                    <el-button
                        type="primary"
                        @click="downloadTemplate('00', '目标/指标指标上传模板')"
                    >
                        <!-- v-if="ssdept.orgBizType == '04'" -->
                        <el-icon>
                            <Download />
                        </el-icon>
                        <span>模板下载</span>
                    </el-button>
                    <!-- <el-button type="primary" @click="uploadFile">
            <el-icon>
              <UploadFilled />
            </el-icon>
            <span>批量上传</span>
          </el-button> -->
                    <el-button
                        type="primary"
                        @click="export2Excel"
                        :loading="exportLoading"
                    >
                        <el-icon>
                            <Download />
                        </el-icon>
                        <span>导出</span>
                    </el-button>
                    <!-- 文件上传小东西 -->
                    <input
                        type="file"
                        style="display: none"
                        @change="changeFile"
                        ref="fileBtn"
                    />
                </div>
            </div>
            <div class="header-divider"></div>
            <MOSTY.Search
                style="padding-top: 10px; overflow: hidden"
                :style="{ maxHeight: isOpensearch ? 'initial' : '45px' }"
                :searchArr="searchArr"
                @submit="onSearch"
                @reset="searchReset"
            >
                <template #searbox>
                    <div style="width: 100%">
                        <el-select
                            v-model="listQuery.targetNationalKeyFocus"
                            style="width: 250px; margin-right: 20px"
                            clearable
                            placeholder="是否国家局重点关注"
                        >
                            <el-option
                                v-for="item in D_BZ_SF"
                                :key="item"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                        <el-input
                            style="width: 250px"
                            v-model="listQuery.targetName"
                            clearable
                            placeholder="请输入指标名称"
                        ></el-input>
                    </div>
                </template>
                <template #lable>
                    <div class="search-toggle" @click="handleClickOpen">
                        <span>{{ isOpensearch ? "收起" : "展开" }}筛选</span>
                        <el-icon class="arrow-icon" :class="{ active: isOpensearch }">
                            <DArrowLeft />
                        </el-icon>
                    </div>
                </template>
            </MOSTY.Search>
            <el-divider />
        </template>
        <template #table>
            <section
                ref="sectionRef"
                :style="{ height: `calc(100vh - ${tableTop}px)`, width: '100%' }"
            >
                <MOSTY.Table
                    :table-columns="pageData.tableColumns"
                    :tableData="pageData.tableData"
                    :tableloading="tableloading"
                    :tableHeight="'100%'"
                    :isSelect="false"
                    style="width: 100%"
                    :isSort="false"
                    actionsW="250"
                >
                    <template #targetValueType="{ row }">
                        <dict-tag
                            :options="D_BZ_TARGET_ITEM_JSFS"
                            :value="row.targetValueType"
                            :tag="false"
                        />
                    </template>
                    <template #targetNature="{ row }">
                        <dict-tag
                            :options="D_BZ_ZBXZ"
                            :value="row.targetNature"
                            :tag="false"
                        />
                    </template>
                    <!-- targetValueType 1: 数值,2:百分比 3:达标 -->
                    <template #targetValue="{ row }">
                        <dict-tag
                            v-if="row.targetValueType == '3'"
                            :options="D_BZ_SFDB"
                            :value="row.targetValue"
                            :tag="false"
                        />
                        <span v-else>{{ row.targetValue ? row.targetValue : "--" }}</span>
                    </template>
                    <template #targetType="{ row }">
                        <span>{{ targetTxtObj[row.targetType] || "" }}</span>
                    </template>

                    <template #targetNationalKeyFocus="{ row }">
                        <span>{{
                            { 1: "是", 2: "否" }[row.targetNationalKeyFocus]
                        }}</span>
                    </template>
                    <template #state="{ row }">
                        <span :style="{ color: row.state == '0' ? 'red' : '' }">{{
                            row.state == "0" ? "否" : "是"
                        }}</span>
                    </template>
                    <template #level="{ row }">
                        <dict-tag :options="D_BZ_MBZBJB" :value="row.level" :tag="true" />
                    </template>
                    <template #actions="{ row }">
                        <!-- v-if="ssdept.orgBizType == '04'" -->
                        <span v-if="isSjAqglk" class="operedit" @click="handlexg(row)">
                            <el-icon> <EditPen /> </el-icon>编辑</span
                        >
                        <el-popconfirm
                            v-if="isSjAqglk"
                            confirm-button-text="是"
                            cancel-button-text="否"
                            icon-color="red"
                            title="确定要删除?"
                            @confirm="handledelete(row)"
                        >
                            <template #reference>
                                <!-- v-if="ssdept.orgBizType == '04'" -->
                                <span span class="operdel" size="small">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                    删除</span
                                >
                            </template>
                        </el-popconfirm>
                        <el-popconfirm
                            v-if="isSjAqglk && row.state == '0'"
                            confirm-button-text="是"
                            cancel-button-text="否"
                            icon-color="red"
                            title="确定要入库?"
                            @confirm="goStorage(row)"
                        >
                            <template #reference>
                                <span class="operedit" size="small">
                                    <el-icon>
                                        <EditPen />
                                    </el-icon>
                                    入库</span
                                >
                            </template>
                        </el-popconfirm>
                        <span class="operesee" @click="handleSee(row)">
                            <el-icon> <View /> </el-icon>查看</span
                        >
                    </template>
                </MOSTY.Table>
            </section>
            <div class="fenye">
                <MOSTY.Pages
                    :pageConfiger="pageData.pageConfiger"
                    @changeNo="handleCurrentChange"
                    @changeSize="handleSizeChange"
                />
            </div>
        </template>
    </MOSTY.PageTree>
    <!-- 新增、修改详情 -->
    <div v-if="addDiaShow" class="dialod">
        <el-dialog
            :title="title"
            v-model="addDiaShow"
            stripe
            width="880px"
            top="10%"
            :before-close="handleClose"
        >
            <div class="config">
                <el-form
                    ref="ruleFormRef"
                    :model="ruleForm"
                    :rules="rules"
                    label-width="165px"
                    :disabled="loadType == '2'"
                    style="display: block"
                    :inline="true"
                >
                    <el-form-item label="目标/指标类别:" prop="targetType">
                        <MOSTY.DictTree
                            :zdbh="'D_BZ_MBZBFL'"
                            v-model="ruleForm.targetType"
                            :placeholder="'请选择目标/指标类别'"
                            style="width: 217px"
                        />
                    </el-form-item>
                    <el-form-item label="指标编号:" prop="targetNo">
                        <el-input
                            style="width: 217px"
                            clearable
                            v-model="ruleForm.targetNo"
                            maxlength="50"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="指标名称:" prop="targetName">
                        <el-input
                            v-model="ruleForm.targetName"
                            clearable
                            style="width: 630px"
                            maxlength="50"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="计算/统计规则:" prop="targetValueType">
                        <!-- <el-select v-model="ruleForm.targetValueType" clearable style="width: 217px;"
              @change="targetValueTypeChange">
              <el-option v-for="item in D_BZ_TARGET_ITEM_JSFS" :key="item" :label="item.label" :value="item.value" />
            </el-select> -->
                        <MOSTY.DictRidioAndSelect
                            style="width: 217px"
                            selectType="select"
                            :dictData="D_BZ_TARGET_ITEM_JSFS"
                            v-model="ruleForm.targetValueType"
                            @onChange="targetValueTypeChange"
                        />
                    </el-form-item>
                    <el-form-item label="预期值:" prop="targetValue">
                        <el-input
                            v-if="ruleForm.targetValueType != '3'"
                            v-model="ruleForm.targetValue"
                            :max="100"
                            type="number"
                            style="width: 217px"
                        >
                            <template #append v-if="ruleForm.targetValueType == '2'"
                                >%</template
                            >
                        </el-input>
                        <!-- <el-select v-else v-model="ruleForm.targetValue" disabled clearable style="width: 217px;">
              <el-option v-for="item in D_BZ_SFDB" :key="item" :label="item.label" :value="item.value" />
            </el-select> -->
                        <MOSTY.DictRidioAndSelect
                            v-else
                            style="width: 217px"
                            selectType="select"
                            :dictData="D_BZ_SFDB"
                            v-model="ruleForm.targetValue"
                        />
                    </el-form-item>
                    <el-form-item label="统计周期:" prop="targetStatisticalPeriod">
                        <el-input
                            style="width: 217px"
                            clearable
                            v-model="ruleForm.targetStatisticalPeriod"
                            maxlength="50"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="计量单位:" prop="targetMeasurementUnit">
                        <el-input
                            style="width: 217px"
                            clearable
                            v-model="ruleForm.targetMeasurementUnit"
                            maxlength="50"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="数据来源/佐证依据:" prop="targetDataSource">
                        <el-input
                            style="width: 630px"
                            type="textarea"
                            :rows="2"
                            clearable
                            v-model="ruleForm.targetDataSource"
                            :maxlength="300"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="指标释义:" prop="targetExplanation">
                        <el-input
                            style="width: 630px"
                            type="textarea"
                            :rows="2"
                            clearable
                            v-model="ruleForm.targetExplanation"
                            :maxlength="300"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="指标性质:" prop="targetNature">
                        <!-- <el-select style="width: 217px;" v-model="ruleForm.targetNature" placeholder="请选择指标性质">
              <el-option v-for="item in D_BZ_ZBXZ" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select> -->
                        <MOSTY.DictRidioAndSelect
                            style="width: 217px"
                            selectType="select"
                            :dictData="D_BZ_ZBXZ"
                            placeholder="请选择指标性质"
                            v-model="ruleForm.targetNature"
                        />
                    </el-form-item>
                    <el-form-item label="级别:" prop="level">
                        <!-- <el-select v-model="ruleForm.level" clearable style="width: 217px;" collapse-tags>
              <el-option v-for="item in leveOpt" :key="item" :label="item.label" :value="item.value" />
            </el-select> -->
                        <MOSTY.DictRidioAndSelect
                            style="width: 217px"
                            selectType="select"
                            :dictData="leveOpt"
                            placeholder="请选择指标性质"
                            v-model="ruleForm.level"
                        />
                    </el-form-item>

                    <el-form-item
                        label="是否国家局重点关注:"
                        prop="targetNationalKeyFocus"
                    >
                        <!-- <el-select v-model="ruleForm.targetNationalKeyFocus" clearable style="width: 217px;">
              <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value" />
            </el-select> -->
                        <MOSTY.DictRidioAndSelect
                            style="width: 217px"
                            selectType="select"
                            :dictData="D_BZ_SF"
                            placeholder="请选择指标性质"
                            v-model="ruleForm.targetNationalKeyFocus"
                        />
                    </el-form-item>
                    <el-form-item label="序号:" prop="xh">
                        <el-input-number
                            style="width: 217px"
                            clearable
                            v-model="ruleForm.xh"
                            step="1"
                            :precision="0"
                            :min="1"
                            :max="99999999"
                            maxlength="50"
                        ></el-input-number>
                    </el-form-item>

                    <!-- <el-form-item v-if="ruleForm.sfgl == '1' && userId == '000000'" label="sql语句:">
            <el-input v-model="ruleForm.sql" clearable style="width: 602px" type="textarea"
              :autosize="{ minRows: 4, maxRows: 15 }"></el-input>
          </el-form-item> -->
                </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button
                        type="primary"
                        v-if="loadType != '2'"
                        @click="handleSave(ruleFormRef)"
                        :loading="loading"
                    >
                        <el-icon>
                            <DocumentChecked />
                        </el-icon>
                        <span>保存</span>
                    </el-button>
                    <el-button @click="handleClose" type="primary">
                        <el-icon>
                            <DocumentDelete />
                        </el-icon>
                        <span>关闭</span>
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
    // 引入
    import {
        reactive,
        watch,
        onMounted,
        getCurrentInstance,
        ref,
        nextTick,
        computed
    } from "vue"
    import { ElMessage } from "element-plus"
    import { getItem } from "@/utils/storage"
    import * as MOSTY from "@/components/MyComponents/index"
    import { getApi, postApi, uploadfilApi } from "@/api/tobAcco_api.js"
    import { filterqx } from "@/utils/auth.js"
    const { proxy } = getCurrentInstance()
    const {
        D_BZ_TARGET_ITEM_JSFS,
        D_BZ_SF,
        D_BZ_SFDB,
        D_BZ_MBZBJB,
        D_BZ_MBZBFL,
        D_BZ_ZBXZ
    } = proxy.$dict(
        "D_BZ_TARGET_ITEM_JSFS",
        "D_BZ_SF",
        "D_BZ_SFDB",
        "D_BZ_MBZBJB",
        "D_BZ_MBZBFL",
        "D_BZ_ZBXZ"
    )
    const tableloading = ref(false)
    import { downloadTemplate } from "@/utils/tools.js"
    import { exportXlsx } from "@/excel/Export2Excel.js"

    const ssdept = getItem("deptId")
    const userId = getItem("USERID")
    const addDiaShow = ref(false)
    const ruleFormRef = ref()
    const loadType = ref("0")
    const fileBtn = ref()
    const title = ref("") //弹窗标题
    const loading = ref(false) //新增保存按钮截流
    //表单数据
    const ruleForm = ref({
        /** 目标值类型  1: 数值,2:百分比 3:达标 */
        targetValueType: "",
        xh: 1 //默认1
    })
    const tableTop = ref(440) //表格高度
    const pageTreeRef = ref()
    const isOpensearch = ref(false) //是否展开筛选
    const exportLoading = ref(false) //导出按钮截流
    const isShowLeftTree = ref(true) //是否显示左侧树,用来触发生命周期，以清空组织机构树数据
    /** 是否省级安全管理科 */
    const isSjAqglk = ref(filterqx("isSgs") == "1" && filterqx("isaqbm") == "1")
    /**当前激活项 */
    const activeTab = ref(
        filterqx("isSgs") == "1" ? "01" : filterqx("isgs") == "1" ? "02" : "03"
    )
    const tabArr = [
        { label: "省级", value: "01" },
        { label: "市级", value: "02" },
        { label: "县级", value: "03" }
    ]

    const tabList = computed(() => {
        return tabArr.filter((item) => {
            if (item.value == "01" && filterqx("isSgs") == "1") {
                return true
            } else if (
                item.value == "02" &&
                (filterqx("isgs") == "1" || filterqx("isSgs") == "1")
            ) {
                return true
            } else if (
                item.value == "03" &&
                (filterqx("isxgs") == "1" ||
                    filterqx("isgs") == "1" ||
                    filterqx("isSgs") == "1")
            ) {
                return true
            }
        })
    })
    const targetTxtObj = ref({})

    //规则校验
    const rules = reactive({
        targetType: [
            { required: true, message: "目标/指标类别不能为空", trigger: "blur" }
        ],
        targetNo: [{ required: true, message: "指标编号不能为空", trigger: "blur" }],
        targetName: [{ required: true, message: "指标名称不能为空", trigger: "blur" }],
        targetMeasurementUnit: [
            { required: true, message: "计量单位不能为空", trigger: "blur" }
        ],
        targetValue: [
            { required: true, message: "请输入目标/指标值", trigger: "blur" },
            {
                validator: (rule, value, callback) => {
                    if (!value) {
                        callback(new Error("请输入目标/指标值"))
                    } else if (
                        (value < 0 || value > 100) &&
                        ruleForm.value.targetValueType == "2"
                    ) {
                        callback(new Error("只能输入0-100的数字"))
                    } else if (
                        value.length > 10 &&
                        ruleForm.value.targetValueType == "1"
                    ) {
                        callback(new Error("数字大小超出限制，长度为10"))
                    } else {
                        callback()
                    }
                },
                trigger: "blur"
            }
        ],
        targetStatisticalPeriod: [
            { trigger: "blur", required: true, message: "统计周期不能为空" }
        ],
        targetValueType: [
            { trigger: "blur", required: true, message: "计算/统计规则不能为空" }
        ],
        targetDataSource: [
            { trigger: "blur", required: true, message: "数据来源/佐证依据不能为空" }
        ],
        targetExplanation: [
            { required: true, message: "指标释义不能为空", trigger: "blur" }
        ],
        targetNature: [{ required: true, message: "指标性质不能为空", trigger: "blur" }],
        level: [{ required: true, message: "级别不能为空", trigger: "blur" }],
        targetNationalKeyFocus: [
            { required: true, message: "是否国家局重点关注不能为空", trigger: "blur" }
        ],
        xh: [{ required: true, message: "序号不能为空", trigger: "blur" }]
    })
    // 数据
    const typevalue = ref("")
    // 分页
    const listQuery = ref({
        pageCurrent: 1,
        pageSize: 20
    })
    const searchArr = reactive([
        {
            showType: "input",
            prop: "keywords",
            width: "250px",
            placeholder: "请输入关键字"
        },
        {
            showType: "selectTree",
            prop: "targetType",
            width: "250px",
            placeholder: "请选择目标/指标类别",
            options: "D_BZ_MBZBFL"
        },
        // {
        //   showType: "select",
        //   prop: "level",
        //   width: '250px',
        //   placeholder: "请选择级别",
        //   options: D_BZ_MBZBJB
        // },
        {
            showType: "input",
            prop: "targetNo",
            width: "250px",
            placeholder: "请输入指标编号"
        }
        // {
        //   showType: "select",
        //   prop: "targetNationalKeyFocus",
        //   width: '250px',
        //   placeholder: "请选择是否国家局重点关注",
        //   options: D_BZ_SF
        // },
        // 指标名称
        // {
        //   showType: "input",
        //   prop: "targetName",
        //   width: '250px',
        //   placeholder: "请输入指标名称"
        // }
    ])
    // 表格数据
    const tableData = ref([])
    const sectionRef = ref(null)
    const orgname = ref("")
    /** 级别(省市县)下拉 */
    const leveOpt = computed(() => {
        if (!D_BZ_MBZBJB.value?.length) return []
        /** 省公司账户 */
        const province = filterqx("isSgs") == "1"
        /**市 */
        const city = filterqx("isgs") == "1"
        const county = filterqx("isxgs") == "1"
        if (province) return D_BZ_MBZBJB.value
        if (city) return D_BZ_MBZBJB.value.filter((item) => item.value != "01")
        if (county)
            return D_BZ_MBZBJB.value.filter(
                (item) => item.value != "01" && item.value != "02"
            )
        return D_BZ_MBZBJB.value
    })
    //是否有更新权限
    const isEdit = ref(false)
    const pageData = reactive({
        tableColumns: [
            {
                title: "序号",
                prop: "xh" // targetType
            },
            {
                title: "所属单位",
                prop: "orgname" // targetType
            },
            {
                title: "类别",
                prop: "targetType", // targetType
                slot: true
            },
            {
                title: "指标编号",
                prop: "targetNo"
            },
            {
                title: "指标名称",
                prop: "targetName"
            },
            {
                title: "计量单位",
                prop: "targetMeasurementUnit"
            },

            {
                title: "预期值",
                prop: "targetValue" // 1: 数值,2:百分比 3:达标
            },
            {
                title: "统计周期",
                prop: "targetStatisticalPeriod"
                // slot: true
            },

            {
                title: "计算/统计规则",
                prop: "targetValueType",
                slot: true
            },
            // {
            //   title: "数据来源/佐证依据",
            //   prop: "targetDataSource"
            // },
            {
                title: "指标释义",
                prop: "targetExplanation"
            },
            {
                title: "指标性质",
                prop: "targetNature",
                slot: true
            },

            {
                title: "重点关注",
                prop: "targetNationalKeyFocus",
                slot: true
            },

            {
                title: "添加人",
                prop: "xtCjr"
            },
            {
                title: "是否入库",
                prop: "state",
                slot: true
            },
            {
                title: "操作",
                prop: "actions",
                fixed: "right",
                slot: true
            }
        ],
        pageConfiger: {
            pageSize: 20,
            pageCurrent: 1,
            total: 0
        },
        tableData: []
    })

    const targetValueTypeChange = () => {
        let val = ruleForm.value.targetValueType
        if (val == "1") {
            ruleForm.value.targetValue = "0"
        } else if (val == "3") {
            ruleForm.value.targetValue = "1"
        } else {
            ruleForm.value.targetValue = ""
        }
    }
    /** 组织机构树更改 */
    const getDeptId = (val) => {
        listQuery.value.orgid = val.id
        orgname.value = val.orgname
        listQuery.value.pageCurrent = 1
        getTabList()
        // store.state.user.currentDeptName = val.orgname
    }
    const onSearch = (obj = {}) => {
        listQuery.value.keywords = obj.keywords || ""
        listQuery.value.targetType = obj.targetType || ""
        listQuery.value.targetNo = obj.targetNo || ""
        // listQuery.value.targetName = obj.targetName || ''
        // listQuery.value.targetNationalKeyFocus = obj.targetNationalKeyFocus || ''

        listQuery.value.pageCurrent = 1
        getTabList()
    }
    const searchReset = () => {
        // 这两个在外面所以要额外清空
        listQuery.value.targetName = ""
        listQuery.value.targetNationalKeyFocus = ""
    }
    /**
     * 设置目标字典对象
     */
    const setDicObj = () => {
        getApi({ zdbh: "D_BZ_MBZBFL" }, "/mosty-base/sysDict/getDictTree").then((res) => {
            let dicArr = res ? res.itemList : []
            dicArr = Array.isArray(dicArr) ? dicArr : []
            const obj = {}
            dicArr.forEach((item) => {
                obj[item.dm] = item.zdmc
                if (item.itemList && item.itemList.length > 0) {
                    item.itemList.forEach((subItem) => {
                        obj[subItem.dm] = `${item.zdmc} / ${subItem.zdmc}`
                        if (subItem.itemList && subItem.itemList.length > 0) {
                            subItem.itemList.forEach((subSubItem) => {
                                obj[
                                    subSubItem.dm
                                ] = `${item.zdmc} / ${subItem.zdmc} / ${subSubItem.zdmc}`
                            })
                        }
                    })
                }
            })
            targetTxtObj.value = obj
        })
    }
    const setTableWidth = () => {}
    onMounted(() => {
        const orgLevel = ssdept.orgLevel.substring(0, 1)
        // 判断权限
        if ((orgLevel == "1" || orgLevel == "2") && ssdept.orgBizType == "04") {
            isEdit.value = true
        }
        getTabList() // 省公司登录时 组织机构树会触发
        setDicObj()
    })

    // 导入模板数据
    const uploadFile = () => {
        nextTick(() => {
            fileBtn.value.click()
        })
    }
    // 获取文件
    const changeFile = () => {
        nextTick(() => {
            let file = fileBtn.value.files[0]
            if (!file) {
                return
            }
            let data = new FormData()
            data.append("file", file)
            uploadfilApi(data, `/mosty-jcgl/target/batchUpload`)
                .then(() => {
                    ElMessage.success("批量上传成功")
                    listQuery.pageCurrent = 1
                    getTabList()
                })
                .finally(() => {
                    fileBtn.value.value = ""
                })
        })
    }
    const onTabClick = (tab) => {
        listQuery.value.orgid = "" // 组织机构树清空
        orgname.value = ""
        pageTreeRef.value?.clearTreeSelect?.()
        listQuery.pageCurrent = 1
        getTabList()
    }
    /** 设置表格高度 */
    function setTableTop() {
        nextTick(() => {
            if (sectionRef.value) {
                let top = sectionRef.value.getBoundingClientRect?.()?.top || 0
                tableTop.value = top + 65
            }
        })
    }
    //获取表格数据
    function getTabList() {
        tableloading.value = true
        const params = {
            ...listQuery.value,
            level: activeTab.value
        }
        postApi(params, "/mosty-jcgl/target/getTargetList")
            .then((res) => {
                res.records.forEach((el) => {
                    if (el.targetValueType === "2" && !el.targetValue.includes("%")) {
                        el.targetValue = el.targetValue + "%"
                    } else if (el.targetValueType === "3") {
                        el.targetValue = "达标"
                    }
                })
                pageData.tableData = res.records
                pageData.pageConfiger.total = res.total
            })
            .finally(() => {
                pageData.tableData.value = []
                tableloading.value = false
                setTableTop()
            })
    }
    //获取数据详情
    function getTabXq(id) {
        ruleForm.value = {}
        getApi({}, `/mosty-jcgl/target/getTargetById/${id}`).then((res) => {
            if (res) {
                if (res.targetValue && res.targetValue.includes("%")) {
                    res.targetValue = res.targetValue.split("%")[0]
                }
                ruleForm.value = res
                ruleForm.value.xh = res.xh ? +res.xh : 0
                // ruleForm.value.level = res.level ? res.level.split(',') : []
            }
        })
    }

    //新增目标/指标子项
    function add() {
        tableloading.value = false
        title.value = "目标/指标子项新增"
        addDiaShow.value = true
        ruleForm.value = { xh: 1, level: activeTab.value }
    }
    const handlexg = (row) => {
        getTabXq(row.id)
        loadType.value = "1"
        title.value = "目标/指标子项修改"
        addDiaShow.value = true
    }
    const handleSee = (row) => {
        getTabXq(row.id)
        loadType.value = "2"
        title.value = "目标/指标子项详情"
        addDiaShow.value = true
    }
    //删除数据
    const handledelete = (row) => {
        postApi({}, "/mosty-jcgl/target/getTargetSC/{id}?id=" + row.id).then(() => {
            ElMessage.success("删除成功")
            getTabList()
        })
    }
    //入库数据
    const goStorage = (row) => {
        postApi({}, "/mosty-jcgl//target/warehousing/{id}?id=" + row.id).then(() => {
            ElMessage.success("入库成功")
            getTabList()
        })
    }

    //关闭
    const handleClose = () => {
        if (!ruleFormRef.value) return
        if (loadType.value != "2") {
            proxy.$modal
                .confirm("离开会丢失页面中修改的内容，确认离开吗？")
                .then(() => {
                    loadType.value = "0"
                    addDiaShow.value = false
                    // 关闭上一次的表单校验
                    ruleFormRef.value.clearValidate()
                })
                .catch(() => {
                    // catch error
                })
        } else {
            loadType.value = "0"
            addDiaShow.value = false
            // 关闭上一次的表单校验
            ruleFormRef.value.clearValidate()
        }
    }

    //保存
    const handleSave = async (formEl) => {
        if (!formEl) return
        await formEl.validate((valid, fields) => {
            if (valid) {
                loading.value = true
                const params = { ...ruleForm.value }
                // params.level = Array.isArray(params.level) ? params.level.toString() : ''
                if (ruleForm.value.id) {
                    postApi(params, "/mosty-jcgl/target/getTargetXG")
                        .then(() => {
                            ElMessage.success("修改成功")
                            addDiaShow.value = false
                            loading.value = false
                            getTabList()
                        })
                        .catch((err) => {
                            loading.value = false
                        })
                } else {
                    params.orgcode = listQuery.value.orgid || null
                    params.orgname = orgname.value || null
                    postApi(params, "/mosty-jcgl/target/getTargetXZ")
                        .then(() => {
                            ElMessage.success("新增成功")
                            addDiaShow.value = false
                            loading.value = false
                            getTabList()
                        })
                        .catch((err) => {
                            loading.value = false
                        })
                }
            } else {
                ElMessage.warning("请输入必填项!")
            }
        })
    }

    //分页
    const handleSizeChange = (val) => {
        listQuery.value.pageSize = val
        pageData.pageConfiger.pageSize = val
        getTabList()
    }
    const handleCurrentChange = (val) => {
        listQuery.value.pageCurrent = val
        pageData.pageConfiger.pageCurrent = val
        getTabList()
    }
    //导出表格
    const export2Excel = async () => {
        let title = {
            xh: "序号",
            orgname: "所属单位",
            // targetType: "目标/指标类别",
            targetTypeName: "目标/指标类别",
            targetNo: "指标编号",
            targetName: "指标名称",
            targetMeasurementUnit: "计量单位",
            targetValue: "预期值",
            targetStatisticalPeriod: "统计周期",
            targetValueType: "计算/统计规则",
            targetDataSource: "数据来源/佐证依据",
            targetExplanation: "指标释义",
            targetNature: "指标性质",
            targetNationalKeyFocus: "是否国家局重点关注",
            level: "级别"
        }

        const params = {
            ...listQuery.value,
            level: activeTab.value,
            pageCurrent: 1,
            pageSize: 10000
        }
        exportLoading.value = true
        try {
            let res = await postApi(params, "/mosty-jcgl/target/getTargetList")
            exportLoading.value = false
            let tableList = Array.isArray(res?.records) ? res.records : []
            if (!tableList.length) {
                ElMessage.warning("暂无数据可导出！")
                return
            }
            tableList.forEach((el) => {
                if (el.targetValueType === "2" && !el.targetValue.includes("%")) {
                    el.targetValue = el.targetValue + "%"
                }
                el.targetTypeName = targetTxtObj.value[el.targetType] || ""
                el.targetNationalKeyFocus = el.targetNationalKeyFocus == "1" ? "是" : "否"
                el.state = el.state == "0" ? "否" : "是"
                el.level = proxy.$getDictVal(el.level, D_BZ_MBZBJB)
            })

            let tablename = "目标、指标库.xlsx"
            exportXlsx(title, tableList, "目标、指标库", tablename, "目标、指标库")
        } catch (error) {
            ElMessage.warning("导出失败，请稍后再试！")
            exportLoading.value = false
        }
    }

    function collapse(isCollapse) {
        // tableOffsetLeft.value = isCollapse ? 400 : 300
    }
    const handleClickOpen = () => {
        isOpensearch.value = !isOpensearch.value
        setTableTop()
    }
</script>

<style lang="scss" scoped>
    @import "@/views/dutyBook/jgryandzz/talentPool/tabContainer.scss";

    .tab-container {
        margin-top: 0px;
    }

    .search-toggle {
        width: 110px;
        margin-left: 10px;
        margin-right: 10px;
        margin-top: 6px;
        white-space: nowrap;
        color: #0f3916;

        .arrow-icon {
            margin-top: 2px;
            transition: all 0.2s;
            transform: rotate(90deg);

            &.active {
                transform: rotate(270deg);
            }
        }
    }

    .zy-right {
        width: 100%;
    }

    .dialod {
        ::v-deep .el-form-item__content {
            flex-wrap: nowrap !important;
        }

        .config {
            .el-form {
                margin-top: 10px;
                display: block;
            }

            .el-form-item {
                text-align: center;
            }
        }

        .titleBox {
            align-items: center;
            margin: 0;
            padding: 0;
            height: 39px;
            border: 1px solid rgb(32, 75, 54);
            padding: 20px;
        }

        .el-form-item__content {
            flex-wrap: nowrap;
        }

        .el-collapse {
            border-color: var(--el-color-primary);
            height: 460px;
        }
    }

    .btnBox {
        display: flex;
        align-items: center;
        // justify-content: flex-end;
        // margin-bottom: 12px;
    }

    .header-divider {
        width: calc(100% + 20px);
        height: 10px;
        background-color: #efefef;
        margin-left: -10px;
    }
</style>
