<template>
  <div>
    <MOSTY.PageTree :pageTitle="'年度目标指标'" :searchType="'01'" @getDeptId="getDeptId">
      <template #serach>
        <el-divider />
        <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 tabArr" :key="i" />
          </el-tabs>
        </div>
        <div class="header-divider"></div>
        <MOSTY.Search :searchArr="searchArr" @submit="onSearch" style="padding-top: 10px; overflow: hidden">
          <template #lable>
            <el-button type="primary" @click="handleCustom"
              v-if="!pageData.tableData.length && isSjAqglk && listQuery.deptCode === '00620001'">
              <el-icon>
                <CirclePlus />
              </el-icon>
              <span>制定</span>
            </el-button>
          </template>
        </MOSTY.Search>
        <!-- <MOSTY.Search
                    :searchArr="searchArr"
                    @submit="onSearch"
                    style="padding-top: 10px; overflow: hidden"
                >
                    <template #lable>
                        <el-button type="primary" @click="decomposeWindow = true">
                            <el-icon>
                                <CirclePlus />
                            </el-icon>
                            <span>分解</span>
                        </el-button>
                    </template>
                </MOSTY.Search> -->

        <el-divider />
        <!-- <div class="btnBox">
                    <el-button type="primary" @click="add">
                        <el-icon>
                            <CirclePlus />
                        </el-icon>
                        <span>新增</span>
                    </el-button>
                </div> -->
      </template>
      <template #table>
        <!-- 表格 -->
        <section class="eltab9 sectionTable" :style="{ height: `calc(100vh - ${tableTop}px)`, width: '100%' }">
          <template v-if="tableloading || pageData.tableData.length">
            <MOSTY.Table :table-columns="pageData.tableColumns" :tableData="paginatedData" :tableloading="tableloading"
              :tableHeight="'100%'" :isSelect="false" style="width: 100%" :isSort="true">
              <template #xtZhgxr="{ row }">
                <span> {{ row.xtZhgxr ? row.xtZhgxr : row.xtCjr }}</span>
              </template>
              <template #xtZhgxsj="{ row }">
                <span> {{ row.xtZhgxsj ? row.xtZhgxsj : row.xtCjsj }}</span>
              </template>
              <template #actions="{ row }">
                <div style="display: flex; width: 100%; align-items: center; justify-content: center">
                  <!-- 所属单位代码 = 当前登录所属单位代码 且 当前登录为安全科-->
                  <!-- <div>
                                        <span class="operedit" @click="handleXgbz(row)">
                                            <el-icon> <EditPen /> </el-icon>编辑</span
                                        >
                                        <el-popconfirm
                                            confirm-button-text="是"
                                            cancel-button-text="否"
                                            icon-color="red"
                                            title="确定要删除?"
                                            @confirm="handlesc(row)"
                                        >
                                            <template #reference>
                                                <span class="operdel" size="small">
                                                    <el-icon> <Delete /> </el-icon
                                                    >删除</span
                                                >
                                            </template>
</el-popconfirm>
<el-popconfirm confirm-button-text="复用" cancel-button-text="取消" icon-color="red"
  v-if="row.year < new Date().getFullYear()" title="确定要复用当前数据到成为本年度的年度目标/指标?" @confirm="reuse(row)">
  <template #reference>
                                                <span class="operedit" size="small">
                                                    <el-icon> <RefreshLeft /> </el-icon
                                                    >复用</span
                                                >
                                            </template>
</el-popconfirm>
</div> -->
                  <span v-if="!row.canEdit" class="operesee" @click="handleck(row)">
                    <el-icon>
                      <Compass />
                    </el-icon>查看详情</span>
                  <span v-else class="operesee" @click="handleck(row)">
                    <el-icon>
                      <EditPen />
                    </el-icon>去制定</span>
                </div>
              </template>
            </MOSTY.Table>
            <div class="fenye">
              <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange"
                @changeSize="handleSizeChange" />
            </div>
          </template>
          <template v-else>
            <div class="noData">
              <span v-if="orgLevel === '11'"> 您尚未制定本年度年度总目标指标，请点击“制定”开始年度总目标指标 </span>
              <span v-else-if="['20', '21'].includes(orgLevel)"> 省局（公司）本年度还未制定全省年度目标指标分解表，待省局（公司）制定下发后再根据本单位实际情况进行制定
              </span>
              <span v-else-if="['30', '31'].includes(orgLevel)"> 上级单位本年度还未制定公司年度目标指标分解表，待上级单位制定下发后再根据本单位实际情况进行制定 </span>
              <span v-else-if="['40'].includes(orgLevel)"> 本单位今年度还未制定单位年度目标指标分解表，待单位制定下发后再根据本部门实际情况进行分解 </span>
              <span v-else> 暂无数据 </span>
            </div>
          </template>
        </section>
      </template>
    </MOSTY.PageTree>
    <!-- 目标指制定定 -->
    <Transition name="slide-right" mode="out-in" appear>
      <TargetCustom v-if="showCustom" :currentType="activeTab" :currentDeptCode="currentDeptCode"
        :currentDeptName="currentDeptName" @close="closeAll" @next="openCustomAdd" />
    </Transition>
    <!-- 目标指标 -->
    <Transition name="slide-right" mode="out-in" appear>
      <CustomAdd v-if="showCustomAdd" @pre="preToTargetCustom" @close="closeAll" @sub="getDataList" :canEdit="canEdit"
        :canCancel="canCancel" :currentDeptCode="currentDeptCodeUseToCustomAdd" :currentLevel="currentLevel"
        :listQueryType="listQuery.type" />
    </Transition>
  </div>

  <BreakDown :decomposeWindow="decomposeWindow" :deptCode="listQuery.deptCode"
    @setDecomposeWindowState="getDecomposeWindowState"></BreakDown>
</template>

<script setup>
// 引入
import { reactive, watch, ref, getCurrentInstance, onMounted, computed } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue"
import BreakDown from "./compon/breakDown.vue"
import { filterYear } from "@/utils/auth.js"
// import { useRouter } from "vue-router"
const { proxy } = getCurrentInstance()
import { getItem } from "@/utils/storage"
import { ElMessage } from "element-plus"
import * as MOSTY from "@/components/MyComponents/index"
import { filterqx } from "@/utils/auth.js"
// const router = useRouter()
import TargetCustom from "./compon/targetCustom.vue"
import CustomAdd from "./compon/customAdd.vue"
const showCustom = ref(false)
const showCustomAdd = ref(false)
const canEdit = ref(false) // 制定详情窗口是否是edit
const canCancel = ref(false)
const currentDeptCode = ref("")
const currentLevel = ref("")
const currentDeptCodeUseToCustomAdd = ref("")
const tableTop = ref(400) //表格高度
/** 是否省级安全管理科 */
const isSjAqglk = ref(filterqx("isSgs") == "1" && filterqx("isaqbm") == "1")
const searchArr = reactive([
  {
    showType: "select",
    prop: "year",
    defaultVal: new Date().getFullYear(),
    width: "250px",
    options: filterYear(5)
  }
])
const tabArr = [
  { label: "结果类目标指标", value: "100000" },
  { label: "过程类目标指标", value: "200000" }
]
const activeTab = ref("100000")
const onTabClick = tab => {
  // listQuery.pageCurrent = 1
  pageData.pageConfiger.currentPage = 1
  listQuery.type = activeTab.value
  getDataList()
}

const handleCustom = () => {
  showCustom.value = true
}

const { D_BZ_TARGET_ITEM_JSFS, D_BZ_SFDB } = proxy.$dict("D_BZ_TARGET_ITEM_JSFS", "D_BZ_SFDB")

const ssdept = getItem("deptId")
const tableloading = ref(false)
const isEdit = ref(false)

let decomposeWindow = ref(false)
const deptData = ref({})
const listQuery = reactive({
  deptCode: "",
  time: new Date().getFullYear() + "",
  type: "100000" // 100000:结果类目标指标 200000:过程类目标指标
})
const currentDeptName = ref("")

const pageData = reactive({
  tableColumns: [
    {
      title: "单位/部门名称",
      prop: "name"
    },
    {
      title: "制定情况",
      prop: "makeStatusExplain"
    },
    {
      title: "分解情况",
      prop: "splitStatusExplain"
    },
    {
      title: "操作",
      prop: "actions",
      slot: true
    }
  ],
  pageConfiger: {
    pageSize: 20,
    currentPage: 1,
    total: 0
  },
  tableData: []
})
const orgLevel = ref("")
onMounted(() => {
  // getIscz()
  orgLevel.value = ssdept.orgLevel
})
//列表查询
const onSearch = obj => {
  listQuery.time = obj.year + ""
  pageData.pageConfiger.currentPage = 1
  getDataList()
}

const getDecomposeWindowState = val => (decomposeWindow.value = val)

const getDeptId = val => {
  deptData.value = {
    orgCode: val.id.replace("XN", ""),
    orgName: val.orgname.replace("（本级）", ""),
    orgLevel: val.orglevel
  }
  console.log(val, 'val')
  listQuery.deptCode = val.orgcode
  // 没有就赋值一次
  if (!currentDeptCode.value) currentDeptCode.value = val.orgcode
  if (!currentDeptName.value) currentDeptName.value = deptData.value.orgName
  getDataList()
}
const paginatedData = computed(() => {
  const { currentPage, pageSize } = pageData.pageConfiger
  // 非数组或空数据直接返回空
  if (!Array.isArray(pageData.tableData) || pageData.tableData.length === 0) {
    return []
  }
  // 计算起始和结束索引
  const start = (currentPage - 1) * pageSize
  const end = start + pageSize
  // 切片获取当前页数据
  return pageData.tableData.slice(start, end)
})
//获取列表数据
function getDataList() {
  tableloading.value = true
  postApi(listQuery, "/mosty-jcgl/safety/index/listStatus")
    .then(res => {
      if (res.length) {
        pageData.tableData = res
        pageData.pageConfiger.total = res.length
      } else {
        pageData.tableData = []
        pageData.pageConfiger.total = 0
      }
    })
    .finally(() => {
      tableloading.value = false
    })
}

// 从查看详情打开customAdd
const handleck = val => {
  currentDeptName.value = val.name
  console.log(`output->currentDeptName.value`, currentDeptName.value)
  currentDeptCode.value = val.code
  currentDeptCodeUseToCustomAdd.value = val.code
  canCancel.value = val.canCancel
  // 查看详情
  if (!val.canEdit) {
    canEdit.value = false
    showCustomAdd.value = true
  } else {
    // 去制定
    handleCustom()
  }
}
// 关闭制定目标及制定详情
const closeAll = () => {
  showCustom.value = false
  showCustomAdd.value = false
}
// 从下一步打开customAdd
const openCustomAdd = e => {
  canEdit.value = true // 列表可编辑
  currentDeptCodeUseToCustomAdd.value = currentDeptCode.value
  console.log(`output->e`, e)
  currentLevel.value = e
  showCustomAdd.value = true
}
// 返回到目标制定
const preToTargetCustom = () => {
  showCustomAdd.value = false
}
// 点击查看制定情况
const handleView = () => {
  showCustomAdd.value = false
  closeAll()
  // 查询制定情况
}

//分页
const handleSizeChange = val => {
  pageData.pageConfiger.currentPage = 1
  pageData.pageConfiger.pageSize = val
}
const handleCurrentChange = val => {
  pageData.pageConfiger.currentPage = val
}
</script>

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

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

.el-dialog__headerbtn {
  margin-top: -6px !important;
}

.el-dialog__headerbtn .el-dialog__close {
  font-size: 27px !important;
}

.xzmb_box {
  margin-top: 10px;

  >div {
    width: 100%;

    .titles {
      text-align: center;
      font-size: 18px;
      font-weight: 800;
      line-height: 35px;
    }
  }
}

.tabHeight {
  height: calc(100vh - 559px);
}

.btn {
  padding: 10px;
  float: right;
}

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

.noData {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, 0);
  color: #505050;
}

.sectionTable {
  position: relative;
}

/* 定义过渡动画关键帧 */
@keyframes slideInFromRight {
  from {
    transform: translateX(100%);
    /* 从右侧完全移出视口 */
    opacity: 0;
  }

  to {
    transform: translateX(0);
    /* 回到初始位置 */
    opacity: 1;
  }
}

@keyframes slideOutToRight {
  from {
    transform: translateX(0);
    opacity: 1;
  }

  to {
    transform: translateX(100%);
    /* 移出到右侧视口外 */
    opacity: 0;
  }
}

/* Transition 自动匹配的类名，与 name="slide-right" 对应 */
.slide-right-enter-active {
  animation: slideInFromRight 0.3s ease-out;
}

.slide-right-leave-active {
  animation: slideOutToRight 0.3s ease-in;
}

/* 进入/离开的起始状态，可省略（动画关键帧已包含），但写了更清晰 */
.slide-right-enter-from,
.slide-right-leave-to {
  transform: translateX(100%);
  opacity: 0;
}

.slide-right-enter-to,
.slide-right-leave-from {
  transform: translateX(0);
  opacity: 1;
}
</style>
