<script setup>
import { getCurrentInstance, ref, onMounted, watch, reactive, toRefs, toRaw } from 'vue';
import { showFailToast, showToast } from 'vant';
import { useRouter } from 'vue-router';

const base_url = '/sgsafe/DeptPerformance';
const performance_url = '/sgsafe/SafePerformance';
const { proxy } = getCurrentInstance();
const router = useRouter();

const fetchData = reactive({
  deptLevel: '0',
  deptCode: '公司级'
});
const { deptLevel, deptCode } = toRefs(fetchData);
const currentLevelName = ref('');

// 查询当前用户控制权限
const defaultDeptLevel = ref('');
const defaultDeptCode = ref('');
const queryRoleCode = async () => {
  const url = performance_url + '/getDeptRole';
  const param = {};
  const res = await proxy.$axios.get(url, param);
  if (res.data.code === 0) {
    const responseStr = res.data.data.split('-');
    switch (responseStr[0]) {
      case '0':
        defaultDeptLevel.value = '0';
        defaultDeptCode.value = responseStr[1];
        break;
      default:
        defaultDeptLevel.value = '2';
        defaultDeptCode.value = responseStr[1];
        break;
    }
  } else {
    showFailToast('操作失败！' + res.data.msg);
  }
};

/* 预处理部门数组 */
const ensureLeafFlag = (tree, fieldNames = { children: 'children' }) => {
  const { children: childrenKey } = fieldNames;
  return tree.map(node => {
    const children = node[childrenKey];
    const hasValidChildren = Array.isArray(children) && children.length > 0;

    const newNode = {
      ...node,
      isLeaf: !hasValidChildren
    };

    if (!newNode.isLeaf) {
      newNode[childrenKey] = ensureLeafFlag(children, fieldNames);
    } else {
      // 可选：清理空 children
      delete newNode[childrenKey];
    }

    return newNode;
  });
};

// 获取默认值对应的名称
const findTextByValue = (tree, targetValue, fieldNames = {}) => {
  const { value: v = 'value', text: t = 'label', children: c = 'children' } = fieldNames;
  if (!Array.isArray(tree)) return;

  for (const node of tree) {
    if (node[v] === targetValue) return node[t];
    if (node[c]) {
      const found = findTextByValue(node[c], targetValue, fieldNames);
      if (found !== undefined) return found;
    }
  }
};
const getDefaultDeptName = () => {
  currentLevelName.value = findTextByValue(deptMenu.value, defaultDeptCode.value, {
    text: 'label',
    value: 'value',
    children: 'children'
  });
};

// 查询对应筛选菜单
const deptMenu = ref([]);
const queryDeptMenu = async () => {
  const url = performance_url + '/queryDeptMenu';
  const param = { deptLevel: deptLevel.value };
  const res = await proxy.$axios.post(url, param);
  if (res.data.code === 0) {
    deptMenu.value = res.data.data;
    deptMenu.value = ensureLeafFlag(deptMenu.value, {
      children: 'children'
    });
    console.log('deptMenu', deptMenu.value);
  } else {
    showToast({ message: '操作失败!' + res.data.msg, type: 'fail' });
  }
};

// 隐患
const hiddenDangerData = ref([]);
const queryHiddenDanger = async () => {
  const url = base_url + '/queryHiddenDanger';
  const rawData = toRaw(fetchData);
  rawData.startYear = currentYear.value;
  rawData.endYear = currentYear.value;
  if (currentQuarter.value) {
    switch (currentQuarter.value) {
      case 'Q1':
        rawData.startMonth = '1';
        rawData.endMonth = '4';
        break;
      case 'Q2':
        rawData.startMonth = '4';
        rawData.endMonth = '7';
        break;
      case 'Q3':
        rawData.startMonth = '7';
        rawData.endMonth = '10';
        break;
      case 'Q4':
        rawData.startMonth = '10';
        rawData.endYear = String(Number.parseInt(currentYear.value) + 1);
        rawData.endMonth = '1';
        break;
    }
  } else if (currentMonth.value) {
    rawData.startMonth = currentMonth.value;
    rawData.endMonth = String((Number(currentMonth.value) + 1) % 12);
    if (rawData.endMonth === '0') {
      rawData.endMonth = '12';
    }
    if (rawData.startMonth === '12') {
      rawData.endYear = String(Number.parseInt(currentYear.value) + 1);
    }
  } else {
    rawData.endYear = String(Number.parseInt(currentYear.value) + 1);
  }
  const param = { json: JSON.stringify(rawData) };
  const res = await proxy.$axios.post(url, param);
  if (res.data.code === 0) {
    hiddenDangerData.value = res.data.data;
  } else {
    showToast({ message: '操作失败！' + res.data.msg, type: 'fail' });
  }
};

const refreshHiddenDanger = () => {
  currentYear.value = new Date().getFullYear();
  currentQuarter.value = '';
  currentMonth.value = '';
  queryHiddenDanger();
};

// 履职
const performDutiesData = ref([]);
const queryPerformDuties = async () => {
  const url = base_url + '/queryPerformDuties';
  const param = { json: JSON.stringify(toRaw(fetchData)) };
  const res = await proxy.$axios.post(url, param);
  if (res.data.code === 0) {
    performDutiesData.value = res.data.data;
  } else {
    showToast({ message: '操作失败！' + res.data.msg, type: 'fail' });
  }
};

// 培训计划及记录
const trainRecordData = ref([]);
const queryTrainRecord = async () => {
  const url = base_url + '/queryTrainRecord';
  const param = { json: JSON.stringify(toRaw(fetchData)) };
  const res = await proxy.$axios.post(url, param);
  if (res.data.code === 0) {
    trainRecordData.value = res.data.data;
  } else {
    showToast({ message: '操作失败！' + res.data.msg, type: 'fail' });
  }
};

// 应急演练
const emergencyDrillsData = ref([]);
const queryEmergencyDrills = async () => {
  const url = base_url + '/queryEmergencyDrills';
  const param = { json: JSON.stringify(toRaw(fetchData)) };
  const res = await proxy.$axios.post(url, param);
  if (res.data.code === 0) {
    emergencyDrillsData.value = res.data.data;
  } else {
    showToast({ message: '操作失败！' + res.data.msg, type: 'fail' });
  }
};

// 切换事业部/班组
const switchSelected = async () => {
  await queryDeptMenu();
  getDefaultDeptName();
  deptCode.value = defaultDeptCode.value;
  switch (activeName.value) {
    case 'first':
      await queryHiddenDanger();
      break;
    case 'second':
      await queryPerformDuties();
      break;
    case 'third':
      await queryTrainRecord();
      break;
    case 'fourth':
      await queryEmergencyDrills();
      break;
  }
};

// 模拟 cascader change（Vant 无 cascader，此处简化处理）
const handleChange = (value) => {
  deptCode.value = value;
  currentLevelName.value = value; // 假设 value 就是部门名
};

const activeName = ref('first');
const handleClick = async (tab) => {
  await queryDeptMenu();
  getDefaultDeptName();
  deptLevel.value = defaultDeptLevel.value;
  deptCode.value = defaultDeptCode.value;
  switch (activeName.value) {
    case 'first':
      await queryHiddenDanger();
      break;
    case 'second':
      await queryPerformDuties();
      break;
    case 'third':
      await queryTrainRecord();
      break;
    case 'fourth':
      await queryEmergencyDrills();
      break;
  }
};

const currentYear = ref(new Date().getFullYear());
const yearList = [
  { text: String(currentYear.value - 2), value: String(currentYear.value - 2) },
  { text: String(currentYear.value - 1), value: String(currentYear.value - 1) },
  { text: String(currentYear.value), value: String(currentYear.value) }
];
const currentMonth = ref('');
const monthList = [
  { text: '1', value: '1' },
  { text: '2', value: '2' },
  { text: '3', value: '3' },
  { text: '4', value: '4' },
  { text: '5', value: '5' },
  { text: '6', value: '6' },
  { text: '7', value: '7' },
  { text: '8', value: '8' },
  { text: '9', value: '9' },
  { text: '10', value: '10' },
  { text: '11', value: '11' },
  { text: '12', value: '12' }
];
const currentQuarter = ref('');
const quarterList = [
  { text: 'Q1', value: 'Q1' },
  { text: 'Q2', value: 'Q2' },
  { text: 'Q3', value: 'Q3' },
  { text: 'Q4', value: 'Q4' }
];

const updateQuarter = () => {
  currentMonth.value = '';

  queryHiddenDanger();
};

const updateMonth = () => {
  currentQuarter.value = '';

  queryHiddenDanger();
};

const switchQuery = () => {
  switch (activeName.value) {
    case 'first':
      queryHiddenDanger();
      break;
    case 'second':
      queryPerformDuties();
      break;
    case 'third':
      queryTrainRecord();
      break;
    case 'fourth':
      queryEmergencyDrills();
      break;
  }
};

watch(() => [deptCode.value, deptLevel.value], () => {
  switchQuery();
});

/* 部门层级相关 */
const openCascader = () => {
  showBottom.value = true;
};

const showBottom = ref(false);
const cascadeValue = ref();
const onFinish = ({ selectedOptions }) => {
  currentLevelName.value = selectedOptions[selectedOptions.length - 1].label;
};

const handleConfirm = () => {
  showBottom.value = false;
  console.log('cascadeValue', cascadeValue.value);
  fetchData.deptCode = cascadeValue.value;
  switchQuery();
};

onMounted(async () => {
  await queryRoleCode();
  deptLevel.value = defaultDeptLevel.value;
  deptCode.value = defaultDeptCode.value;
  await queryDeptMenu();

  cascadeValue.value = defaultDeptCode.value;
  fetchData.deptCode = defaultDeptCode.value;
  getDefaultDeptName();
  await queryHiddenDanger();
  await queryPerformDuties();
  await queryTrainRecord();
  await queryEmergencyDrills();
});
</script>

<template>
  <div class="layout-container">
    <van-tabs v-model:active="activeName" @change="handleClick" color="#1989fa">
      <van-tab title="隐患" name="first">
        <div class="query-form">
          <div class="form-item">
            <van-field
              label="具体部门："
              v-model="currentLevelName"
              @click="openCascader"
            />
          </div>
        </div>
        <div class="query-form">
          <div class="form-item">
            <span class="label">部门层级：</span>
            <van-radio-group v-model="deptLevel" direction="horizontal" @change="switchSelected">
              <van-radio v-if="defaultDeptLevel !== '2'" name="0">事业部</van-radio>
              <van-radio name="2">班组</van-radio>
            </van-radio-group>
          </div>
        </div>
        <div class="query-form">
          <div class="form-item">
            <span class="label">年度：</span>
            <van-dropdown-menu>
              <van-dropdown-item
                v-model="currentYear"
                :options="yearList"
                @change="queryHiddenDanger"
              />
            </van-dropdown-menu>
          </div>
          <div class="form-item">
            <span class="label">季度：</span>
            <van-dropdown-menu>
              <van-dropdown-item
                ref="quarterRef"
                v-model="currentQuarter"
                :options="quarterList"
                @change="updateQuarter"
              />
            </van-dropdown-menu>
          </div>
          <div class="form-item">
            <span class="label">月度：</span>
            <van-dropdown-menu>
              <van-dropdown-item
                ref="monthRef"
                v-model="currentMonth"
                :options="monthList"
                @change="updateMonth"
              />
            </van-dropdown-menu>
          </div>
          <div class="form-item">
            <van-button type="primary" size="small" @click="refreshHiddenDanger">重置</van-button>
          </div>
        </div>

        <van-list>
          <van-cell-group>
            <van-cell
              v-for="(row, index) in hiddenDangerData"
              :key="index"
              :title="row.deptName"
              clickable
              class="card-like-cell"
            >
              <template #label>
                <div class="stats-row">
                  <span class="stat-item">发现: {{ row.total }}</span>
                  <span class="stat-item stat-item-highlight">完成: {{ row.finished }}</span>
                  <span class="stat-item">未完成: {{ row.continued }}</span>
                </div>
              </template>
            </van-cell>
          </van-cell-group>
        </van-list>
      </van-tab>

      <!-- 履职 -->
      <van-tab title="履职" name="second">
        <div class="query-form">
          <div class="form-item">
            <van-field
              label="具体部门"
              v-model="currentLevelName"
              @click="openCascader"
            />
          </div>
        </div>
        <div class="query-form">
          <div class="form-item">
            <span class="label">部门层级：</span>
            <van-radio-group v-model="deptLevel" direction="horizontal" @change="switchSelected">
              <van-radio v-if="defaultDeptLevel !== '2'" name="0">事业部</van-radio>
              <van-radio name="2">班组</van-radio>
            </van-radio-group>
          </div>
        </div>
        <van-list>
          <van-cell-group>
            <van-cell
              v-for="(row, index) in performDutiesData"
              :key="index"
              :title="row.deptName"
              clickable
              class="card-like-cell"
            >
              <template #label>
                <div class="stats-row">
                  <span class="stat-item stat-item-highlight">平均分: {{ row.avgScore }}</span>
                  <span class="stat-item">本年: {{ row.yearCount }}</span>
                  <span class="stat-item">本月: {{ row.monthCount }}</span>
                  <span class="stat-item">本周: {{ row.weekCount }}</span>
                </div>
              </template>
            </van-cell>
          </van-cell-group>
        </van-list>
      </van-tab>

      <!-- 培训计划 -->
      <van-tab title="培训计划" name="third">
        <div class="query-form">
          <div class="form-item">
            <van-field
              label="具体部门"
              v-model="currentLevelName"
              @click="openCascader"
            />
          </div>
        </div>
        <div class="query-form">
          <div class="form-item">
            <span class="label">部门层级：</span>
            <van-radio-group v-model="deptLevel" direction="horizontal" @change="switchSelected">
              <van-radio v-if="defaultDeptLevel !== '2'" name="0">事业部</van-radio>
              <van-radio name="2">班组</van-radio>
            </van-radio-group>
          </div>
        </div>
        <van-list>
          <van-cell-group>
            <van-cell
              v-for="(row, index) in trainRecordData"
              :key="index"
              :title="row.deptName"
              clickable
              class="card-like-cell"
            >
              <template #label>
                <div class="stats-row">
                  <span class="stat-item">计划: {{ row.total }}</span>
                  <span class="stat-item stat-item-highlight">完成: {{ row.finished }}</span>
                  <span class="stat-item">学时: {{ row.hours }}</span>
                </div>
              </template>
            </van-cell>
          </van-cell-group>
        </van-list>
      </van-tab>

      <!-- 应急演练 -->
      <van-tab title="应急演练" name="fourth">
        <div class="query-form">
          <div class="form-item">
            <van-field
              label="具体部门"
              v-model="currentLevelName"
              @click="openCascader"
            />
          </div>
        </div>
        <div class="query-form">
          <div class="form-item">
            <span class="label">部门层级：</span>
            <van-radio-group v-model="deptLevel" direction="horizontal" @change="switchSelected">
              <van-radio v-if="defaultDeptLevel !== '2'" name="0">事业部</van-radio>
              <van-radio name="2">班组</van-radio>
            </van-radio-group>
          </div>
        </div>

        <van-list>
          <van-cell-group>
            <van-cell
              v-for="(row, index) in emergencyDrillsData"
              :key="index"
              :title="row.deptName"
              clickable
              class="card-like-cell"
            >
              <template #label>
                <div class="stats-row">
                  <span class="stat-item">计划: {{ row.total }}</span>
                  <span class="stat-item stat-item-highlight">完成: {{ row.finished }}</span>
                </div>
              </template>
            </van-cell>
          </van-cell-group>
        </van-list>
      </van-tab>
    </van-tabs>
  </div>

  <van-popup :close-on-click-overlay="false" :lazy-render="false" v-model:show="showBottom" position="bottom">
    <div class="popup-container">
      <!-- 操作按钮 - 固定在顶部 -->
      <div class="action-buttons-container">
        <div @click="showBottom = false">取消</div>
        <div>部门选择</div>
        <div style="color: #007bff" @click="handleConfirm">确定</div>
      </div>
      <div class="cascade-container">
        <van-cascader
          v-model="cascadeValue"
          title="请选择具体部门"
          :options="deptMenu"
          :swipeable="true"
          :columns-num="3"
          @finish="onFinish"
          :field-names="{
            text: 'label',
            value: 'value',
            children: 'children'
          }"
        />
      </div>
    </div>
  </van-popup>

</template>

<style scoped>
.layout-container {
  background-color: #fff;
  height: 86.8vh;
  overflow-y: auto;
  padding: 10px;
}

.query-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px 0;
  align-items: center;
}

.form-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.label {
  font-size: 14px;
  white-space: nowrap;
}

/* Vant 下拉菜单默认宽度较小，可适当调整 */
:deep(.van-dropdown-menu__item) {
  min-width: 80px;
}

:deep(.van-cell) {
  padding: 0 5px;
}

.popup-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f8fafd;
}

/* 选择器容器 */
.cascade-container {
  flex: 1;
  overflow: hidden;
  background: rgb(255, 255, 255);
}

/* 确保 van-cascade 占满剩余空间 */
.cascade-container :deep(.van-cascader) {
  height: 100%;
}

.cascade-container :deep(.van-cascader__content) {
  height: calc(100% - 44px);
  /* 减去标题栏高度 */
}

/* 为 van-cascader 选项添加分割线 */
.cascade-container :deep(.van-cascader__option) {
  border-bottom: 1px solid #e4e4e4;
}

.cascade-container :deep(.van-cascader__option:last-child) {
  border-bottom: none;
}

/* 操作按钮样式 - 固定在顶部 */
.action-buttons-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  z-index: 10;
}


.card-like-cell {
  --van-cell-background: #ffffff;
  --van-cell-font-size: 16px;
  --van-cell-title-line-height: 1.4;
  --van-cell-label-line-height: 1.3;
  min-height: 56px;

  /* 关键：卡片样式 */
  border: 1px solid #f0f0f0; /* 极浅边框 */
  border-radius: 6px; /* 微圆角，移动端友好 */
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03); /* 超轻微阴影，提升层次 */
  margin-bottom: 8px; /* 行间距（可选，若必须 ≤5px 则改为 5px） */

  /* 内部留白控制 */
  padding: 8px 12px !important; /* Vant cell 默认 padding 覆盖，总内边距合理 */
}

/* 去掉 Vant 默认的下划线（因为已有边框） */
.card-like-cell::after {
  display: none !important;
}

/* 统计信息 */
.stats-row {
  display: flex;
  gap: 8px;
  margin-top: 4px;
  color: #666;
  font-size: 13px;
}

.stat-item {
  background-color: #f8f9fa;
  padding: 2px 6px;
  border-radius: 3px;
  white-space: nowrap;
}

.stat-item-highlight {
  color: #e6a23c;
  font-weight: 500;
}

/*.stat-item:nth-child(3) {
  color: #e6a23c;
  font-weight: 500;
}*/

/* 点击态：加深背景，保留反馈 */
.card-like-cell:active {
  background-color: #f9f9f9;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
</style>