<template>
  <div class="CustomAdd">
    <div class="title">年度目标指标</div>
    <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>
    <div class="searchCtx">
      <MOSTY.Search :searchArr="searchArr" @submit="onSearch" style="padding-top: 10px; overflow: hidden" :needDefault="!canEdit">
        <template #lable>
          <template v-if="canEdit">
            <!-- 上一步 保存 重置 下发 -->
            <el-button type="primary" @click="handlePre">
              <span>返回上一步</span>
            </el-button>
            <el-button type="primary" @click="handleSave">
              <span>保存</span>
            </el-button>
            <el-button type="primary" @click="handleReset">
              <span>重置</span>
            </el-button>
            <el-button type="primary" @click="handleSub">
              <span>下发</span>
            </el-button>
            <el-button type="primary" @click="handleClose">
              <span>关闭</span>
            </el-button>
          </template>
          <template v-else>
            <!-- 查看定制情况 撤回 -->

            <!-- <el-button type="primary" @click="handleView">
                            <span>查看定制情况</span>
                        </el-button> -->
            <el-button v-if="canCancel" type="primary" @click="handleWithdraw">
              <span>撤回</span>
            </el-button>
            <el-button type="primary" @click="handleClose">
              <span>返回</span>
            </el-button>
          </template>
        </template>
      </MOSTY.Search>
    </div>
    <el-divider />
    <!-- 表格 -->
    <section class="eltab9 sectionTable" :style="{ height: `calc(100vh - ${tableTop}px)`, width: '100%' }">
      <MOSTY.Table
        :table-columns="pageData.tableColumns"
        :tableData="paginatedData"
        :tableloading="tableloading"
        :tableHeight="'100%'"
        :isSelect="false"
        style="width: 100%"
        :isSort="true"
      >
        <template #targetValue="{ row }">
          <!-- 预期值单位为数量\百分比 -->
          <span v-if="row.targetValueType === '1'">
            <!-- {{ row.expectValue + ' ' + row.targetMeasurementUnit}} -->
            {{ row.targetValue }}
          </span>
          <span v-else-if="row.targetValueType === '2'">
            <!-- {{ row.expectValue + ' ' + (row.targetMeasurementUnit || '%')}} -->
            {{ row.targetValue }}
          </span>
          <!-- 预期值单位为是否达标 -->
          <span v-else-if="row.targetValueType === '3'">
            <!-- {{
                            row.expectValue === "1" || srow.expectValue === 1
                                ? "达标"
                                : "未达标"
                        }} -->
            {{ row.targetValue }}
          </span>
          <span v-else>{{ row.targetValue }}</span>
        </template>
        <template v-for="item in dyColumns" #[item]="{ row }">
          <!-- <span style="color: red">{{ row.dynamicData[item] }}</span> -->
          <template v-if="canEdit">
            <!-- 预期值单位为数量 -->
            <el-input-number
              style="width: 90%; height: 95%"
              v-if="row.targetValueType === '1'"
              v-model="row.dynamicData[item]"
              placeholder="请输入预期值"
              size="small"
              :disabled="row.isFixed"
              :controls="false"
              :precision="0"
              :min="0"
            />
            <!-- 预期值为百分比 -->
            <el-input-number
              style="width: 90%; height: 95%"
              v-else-if="row.targetValueType === '2'"
              v-model="row.dynamicData[item]"
              placeholder="请输入预期值"
              size="small"
              :disabled="row.isFixed"
              :controls="false"
              :precision="0"
              :min="0"
              :max="100"
            />
            <!-- 预期值为是否达标 -->
            <el-select
              style="width: 90%; height: 95%"
              v-else-if="row.targetValueType === '3'"
              v-model="row.dynamicData[item]"
              placeholder="请选择预期值"
              size="small"
              :disabled="row.isFixed"
            >
              <el-option label="达标" :value="1" />
              <el-option label="未达标" :value="0" />
            </el-select>
            <!-- 如果有其他的，避免错误显示 -->
            <el-input-number
              style="width: 90%; height: 95%"
              v-else
              v-model="row.dynamicData[item]"
              placeholder="请输入预期值"
              size="small"
              :disabled="scope.row.isFixed"
              :controls="false"
              :precision="0"
              :min="0"
            />
          </template>
          <template v-else>
            {{ row.dynamicData[item] }}

            <!-- 预期值单位为数量\百分比 -->
            <!-- <span
                        v-if="row.targetValueType === '1'"
                    >
                        {{ row.dynamicData[item] + ' ' + row.targetMeasurementUnit}}
                    </span>
                    <span
                        v-else-if="row.targetValueType === '2'"
                    >
                        {{ row.dynamicData[item] + ' ' + (row.targetMeasurementUnit || '%')}}
                    </span> -->
            <!-- 预期值单位为是否达标 -->
            <!-- <span v-else-if="row.targetValueType === '3'">
                        {{
                            row.dynamicData[item] === "1" || srow.expectValue === 1
                                ? "达标"
                                : "未达标"
                        }}
                    </span>
                    <span v-else>{{ row.dynamicData[item] }}</span> -->
          </template>
        </template>
      </MOSTY.Table>
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange" @changeSize="handleSizeChange" />
      </div>
    </section>
  </div>
</template>

<script setup>
import * as MOSTY from "@/components/MyComponents/index"
import { reactive, ref, onMounted, computed, getCurrentInstance, watch } from "vue"
import { filterYear } from "@/utils/auth.js"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { ElMessage } from "element-plus"
const { proxy } = getCurrentInstance()
const tableTop = ref(400) //表格高度
const props = defineProps({
  canEdit: {
    type: Boolean,
    default: true
  },
  currentDeptCode: {
    type: String,
    default: ""
  },
  currentLevel: {
    type: String,
    default: ""
  },
  canCancel: {
    type: Boolean,
    default: true
  },
  listQueryType: {
    type: String,
    default: "100000" // 100000:结果类目标指标 200000:过程类目标指标
  }
})
const isDept = computed(() => {
  return ["01", "02", "03"].includes(props.currentLevel)
})
const dyColumns = ref([]) // 存放动态列表头字段
const emit = defineEmits(["pre", "sub", "view", "withdraw", "close"])
const searchArr = reactive([
  {
    showType: "select",
    prop: "year",
    defaultVal: new Date().getFullYear(),
    width: "250px",
    options: filterYear(5),
    disabled: computed(() => props.canEdit)
  }
])
const tableloading = ref(false)
const activeTab = ref("100000")
const listQuery = reactive({
  deptCode: computed(() => props.currentDeptCode),
  time: new Date().getFullYear() + "",
  type: computed(() => activeTab.value) // 100000:结果类目标指标 200000:过程类目标指标
})
const tabArr = [
  { label: "结果类目标指标", value: "100000" },
  { label: "过程类目标指标", value: "200000" }
]

const onTabClick = tab => {
  pageData.pageConfiger.currentPage = 1
  // listQuery.type = activeTab.value
  getDataList()
}
const handlePre = () => {
  const temp = {
    type: activeTab.value,
    deptCode: listQuery.deptCode,
    isDept: isDept.value,
    isDistribution: false,
    dataList: pageData.tableData
  }
  postApi(temp, "/mosty-jcgl/safety/index/replaceDistribution").finally(() => {
    emit("pre")
  })
}
// 保存
const handleSave = () => {
  console.log("保存")
  const temp = {
    type: activeTab.value,
    deptCode: listQuery.deptCode,
    isDept: isDept.value,
    isDistribution: false,
    dataList: pageData.tableData
  }
  postApi(temp, "/mosty-jcgl/safety/index/replaceDistribution").then(res => {
    ElMessage.success("保存成功")
    emit("close")
  })
}
const handleReset = () => {
  console.log("重置")
  // 从深拷贝的值中重置
  pageData.tableData = JSON.parse(JSON.stringify(defaultVal.tableData))
}
// 下发
const handleSub = () => {
  proxy.$modal
    .confirm("确认下发已制定的目标指标吗？")
    .then(() => {
      const temp = {
        type: activeTab.value,
        deptCode: listQuery.deptCode,
        isDept: isDept.value,
        isDistribution: true,
        dataList: pageData.tableData
      }
      postApi(temp, "/mosty-jcgl/safety/index/replaceDistribution").then(res => {
        ElMessage.success("下发成功")
        emit("close")
        emit("sub")
      })
    })
    .catch(() => {
      // catch error
    })
}
// 撤回
const handleWithdraw = () => {
  const temp = listQuery
  proxy.$modal
    .confirm("确认撤回已制定的目标指标吗？")
    .then(() => {
      postApi(temp, "/mosty-jcgl/safety/index/cancel").then(res => {
        ElMessage.success("撤回成功")
        emit("close")
        emit("sub")
      })
    })
    .catch(() => {
      // catch error
    })
}
const handleClose = () => {
  emit("close")
}
//列表查询
const onSearch = obj => {
  listQuery.time = obj.year + ""
  pageData.pageConfiger.currentPage = 1
  getDataList()
}
// 用于存初始值的变量
const defaultVal = {}
// 获取列表表头
function getTableColumns() {
  return postApi(listQuery, "/mosty-jcgl/safety/index/listDistributionHeader").then(res => {
    dyColumns.value = []
    pageData.tableColumns = res || []
    console.log(`output->pageData.tableColumns`, pageData.tableColumns)
    // 获取表头，并给表头设置宽度
    pageData.tableColumns.forEach((el, index) => {
      el.suntab.forEach(item => {
        item.width = index === 0 ? 120 : 200
        if (index === 1) {
          dyColumns.value.push(item.prop)
        }
      })
    })
    console.log(`output->dyColumns.value`, dyColumns.value)
  })
}
//获取列表数据
function getDataListApi() {
  tableloading.value = true
  postApi(listQuery, "/mosty-jcgl/safety/index/listDistribution")
    .then(res => {
      if (res.length) {
        pageData.tableData = res
        pageData.tableData.forEach(item => {
          dyColumns.value.forEach(el => {
            item.dynamicData[el] = +item.dynamicData[el] || 0
          })
        })
        pageData.pageConfiger.total = res.length
      } else {
        pageData.tableData = []
        pageData.pageConfiger.total = 0
      }
      console.log(`output->pageData.tableData`, pageData.tableData)
      // 深拷贝
      defaultVal.tableData = JSON.parse(JSON.stringify(pageData.tableData))
    })
    .finally(() => {
      tableloading.value = false
    })
}
// 获取表头和列表
async function getDataList() {
  await getTableColumns()
  getDataListApi()
}
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)
})
const pageData = reactive({
  tableColumns: [],
  pageConfiger: {
    pageSize: 20,
    currentPage: 1,
    total: 0
  },
  tableData: []
})
//分页
const handleSizeChange = val => {
  pageData.pageConfiger.pageSize = val
  pageData.pageConfiger.currentPage = 1
}
const handleCurrentChange = val => {
  pageData.pageConfiger.currentPage = val
}
onMounted(() => {
  activeTab.value = props.listQueryType
  getDataList()
})
</script>

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

.CustomAdd {
  width: 100%;
  overflow-x: hidden !important;
  // border: 1px solid var(--el-color-primary);
  position: absolute;
  height: calc(100vh - 150px);
  background-color: #fff;
  overflow-x: auto;
  z-index: 999;
  top: 0;

  .title {
    height: 39px;
    line-height: 39px;
    font-size: 18px;
    color: var(--el-color-primary);
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 10px;
  }
  .header-divider {
    width: calc(100% + 20px);
    height: 10px !important;
    background-color: #efefef;
    margin-left: -10px;
  }
  .searchCtx {
    padding: 0 15px;
  }
  .sectionTable {
    position: relative;
  }
}
.sectionTable {
  :deep(.el-input__inner) {
    text-align: center;
  }
}
</style>
