<template>
  <lay-container style="padding: 20px">
    <lay-card>
      <div style="padding: 10px">
        <span style="font-size: 18px;vertical-align: center;margin-right: 20px">考评时间列表</span>
        <lay-button size="sm" border="green" @click="addShowMsd()">新增</lay-button>
      </div>
      <lay-table size="lg" ref="tableRef6" children-column-name="children" :columns="columns6"
                 :data-source="dataSource6">
        <template v-slot:evaluation_type="{data}">
          <span v-if="data.evaluation_type==1">年度</span>
          <span v-if="data.evaluation_type==2">季度</span>
          <span v-if="data.evaluation_type==3">月度</span>
        </template>
<!--        <template v-slot:evaluation_start_type="{data}">-->
<!--          <span v-if="data.evaluation_start_type==1">结束后</span>-->
<!--        </template>-->
        <template v-slot:operator="{data}">
          <lay-space size="lg">
            <span style="color: #00A394;cursor: pointer" @click="editShowMsd(data)">编辑</span>
            <lay-popconfirm trigger="click" content="确定要删除吗？" @confirm="delShowMsd(data)">
              <span style="color: #00A394;cursor: pointer">删除</span>
            </lay-popconfirm>
          </lay-space>
        </template>
      </lay-table>
    </lay-card>
    <lay-layer v-model="addShow" :title="addIsEdit==1?'新增考评时间':'编辑考评时间'" :type="4" :shade="true"
               :area="['950px','100%']" :btn="addButton">
      <lay-container fluid="true" style="padding: 20px">
        <lay-form :model="addData">
          <lay-form-item required label-width="150px" label="考评标题" prop="single_score_min">
            <lay-input placeholder="请输入标题" v-model="addData.title"></lay-input>
          </lay-form-item>
          <lay-form-item required label-width="150px" label="考评类型" prop="score_type">
            <lay-select v-model="addData.evaluation_type" placeholder="请选择">
              <lay-select-option :value="1" label="年度"></lay-select-option>
              <lay-select-option :value="2" label="季度"></lay-select-option>
              <lay-select-option :value="3" label="月度"></lay-select-option>
            </lay-select>
          </lay-form-item>
<!--          <lay-form-item required label-width="150px" label="考评开始类型" prop="single_score_max">-->
<!--            <lay-select v-model="addData.evaluation_start_type" placeholder="请选择">-->
<!--              <lay-select-option :value="1" label="结束后"></lay-select-option>-->
<!--            </lay-select>-->
<!--          </lay-form-item>-->
<!--          <lay-form-item required label-width="150px" label="时间（天）" prop="single_score_min">-->
<!--            <lay-input-number v-model="addData.time"></lay-input-number>-->
<!--          </lay-form-item>-->
          <lay-form-item required label-width="150px" label="考评开始时间" prop="single_score_min">
            <lay-date-picker type="datetime" v-model="addData.start_time" placeholder="考评开始时间"
                             allow-clear></lay-date-picker>
          </lay-form-item>
          <lay-form-item required label-width="150px" label="考评结束时间" prop="single_score_min">
            <lay-date-picker type="datetime" v-model="addData.end_time" placeholder="考评结束时间"
                             allow-clear></lay-date-picker>
          </lay-form-item>
          <lay-form-item required label-width="150px" label="考评范围" prop="score_type">
            <lay-tree
                :tail-node-icon="false"
                :data="groupList"
                :showCheckbox="true"
                v-model:checkedKeys="addData.user_group_id"
                :replaceFields="replaceFields"
                @check-change="getTreeKp">
            </lay-tree>
          </lay-form-item>
          <lay-form-item required label-width="150px" label="考评内容" prop="score_type">
            <lay-tree
                :tail-node-icon="false"
                :data="contentList"
                :showCheckbox="true"
                v-model:checkedKeys="addData.basic_rating_id"
                :replaceFields="contentFields"
                @check-change="getTree">
            </lay-tree>
          </lay-form-item>
          <lay-form-item required label-width="150px" label="规则描述" prop="scoring_criteria">
            <lay-textarea placeholder="请输入" v-model="addData.rule_description"></lay-textarea>
          </lay-form-item>
        </lay-form>
      </lay-container>
    </lay-layer>
  </lay-container>
</template>
<script setup lang="ts">
import {
  homeGetHierarchicalData,
  menuData,
  scheduleCreate, scheduleDelete,
  scheduleList, scheduleUpdate, userGroupData
} from '../../api/module/home'
import {ref, watch, onMounted, reactive} from 'vue'
import {layer} from '@layui/layer-vue'
import {verificationImg} from "@/api/module/commone";


const getCascader = (node) => {
  console.log(node)
}
const selectedKpIds = ref([]);
const getTreeKp = (node) => {
  if (node.isChecked) {
    // 选中逻辑：合并父链和子节点ID（原有逻辑）
    const relatedIds = collectRelatedIds(node);
    selectedKpIds.value = [...new Set([...selectedKpIds.value, ...relatedIds])];
  } else {
    // 取消选中逻辑分两步处理 --------------------------

    // 第一步：移除当前节点及其所有子节点的ID
    const childIds = collectChildIds(node);
    selectedKpIds.value = selectedKpIds.value.filter(id => !childIds.includes(id));

    // 第二步：检查父节点是否需要移除（逐级向上）
    let parent = node.parentNode;
    while (parent) {
      // 判断父节点是否还有被选中的子节点
      const hasOtherCheckedChild = parent.children.some(
          child => child.id !== node.id && selectedKpIds.value.includes(child.id)
      );

      if (!hasOtherCheckedChild) {
        // 无其他选中子节点，移除父节点ID
        selectedKpIds.value = selectedKpIds.value.filter(id => id !== parent.id);
      } else {
        // 有其他选中子节点，终止向上检查
        break;
      }

      parent = parent.parentNode; // 继续检查更上层父节点
    }
  }
}
const selectedIds = ref([]);
// 处理取消选中时的逻辑优化
const getTree = (node) => {
  console.log(node)
  if (node.isChecked) {
    // 选中逻辑：合并父链和子节点ID（原有逻辑）
    const relatedIds = collectRelatedIds(node);
    selectedIds.value = [...new Set([...selectedIds.value, ...relatedIds])];
  } else {
    // 取消选中逻辑分两步处理 --------------------------

    // 第一步：移除当前节点及其所有子节点的ID
    const childIds = collectChildIds(node);
    selectedIds.value = selectedIds.value.filter(id => !childIds.includes(id));

    // 第二步：检查父节点是否需要移除（逐级向上）
    let parent = node.parentNode;
    while (parent) {
      // 判断父节点是否还有被选中的子节点
      const hasOtherCheckedChild = parent.children.some(
          child => child.id !== node.id && selectedIds.value.includes(child.id)
      );

      if (!hasOtherCheckedChild) {
        // 无其他选中子节点，移除父节点ID
        selectedIds.value = selectedIds.value.filter(id => id !== parent.id);
      } else {
        // 有其他选中子节点，终止向上检查
        break;
      }

      parent = parent.parentNode; // 继续检查更上层父节点
    }
  }
};
const collectRelatedIds = (node) => {
  const ids = new Set();

  // 向上收集父节点及自身
  let current = node;
  while (current) {
    ids.add(current.id);
    current = current.parentNode;
  }

  // 向下收集所有子节点
  const stack = [node];
  while (stack.length > 0) {
    const currentNode = stack.pop();
    ids.add(currentNode.id);
    if (currentNode.children) {
      stack.push(...currentNode.children);
    }
  }

  return Array.from(ids);
};
// 辅助函数：仅收集当前节点及子节点ID（不包含父节点）
const collectChildIds = (node) => {
  const ids = new Set();
  const stack = [node];
  while (stack.length > 0) {
    const currentNode = stack.pop();
    ids.add(currentNode.id);
    if (currentNode.children) {
      stack.push(...currentNode.children);
    }
  }
  return Array.from(ids);
};
//列表内容
const dataSource6 = ref([]);
const addShow = ref(false)
//1 add  2 edit
const addIsEdit = ref(1)
const addData = reactive({
  evaluation_type: null,
  evaluation_start_type: null,
  start_time: null,
  end_time: null,
  time: 0,
  rule_description: '',
  user_group_id: [],
  basic_rating_id: [],
  title:'',
})
onMounted(() => {
  getHierarchicalData()
  getGroupList();
  getContentList();
})
const contentFields = {
  title: 'project_name',
  id: 'id',
  children: 'children'
}
const contentList = ref([]);
const getContentList = () => {
  homeGetHierarchicalData({}).then((res) => {
    console.log(res)
    if (res.code == 1) {
      contentList.value = res.data;
    } else {
      layer.msg(res.msg, {icon: 2})
    }
  })
}
const replaceFields = {
  title: 'name',
  id: 'id',
  children: 'children'
}
const groupList = ref([]);
const getGroupList = () => {
  userGroupData({}).then((res) => {
    console.log(res)
    if (res.code == 1) {
      groupList.value = res.data;
    } else {
      layer.msg(res.msg, {icon: 2})
    }
  })
}
const getHierarchicalData = () => {
  scheduleList({}).then((res) => {
    console.log(res)
    if (res.code == 1) {
      dataSource6.value = res.data;
    } else {
      layer.msg(res.msg, {icon: 2})
    }
  })
}
const addShowMsd = () => {
  addShow.value = true;
  addIsEdit.value = 1;
  addData.id = 0;
  addData.evaluation_type = null;
  addData.time = 0;
  addData.evaluation_start_type = null;
  addData.start_time = null;
  addData.end_time = null;
  addData.rule_description = '';
  addData.user_group_id = [];
  addData.basic_rating_id = [];
  addData.title = '';
}
const editShowMsd = (data) => {
  console.log(data);
  addShow.value = true;
  addData.id = data.id;
  addData.evaluation_type = parseInt(data.evaluation_type);
  addData.time = data.time;
  addData.evaluation_start_type = parseInt(data.evaluation_start_type);
  addData.start_time = data.start_time;
  addData.end_time = data.end_time;
  addData.rule_description = data.rule_description;
  addData.title = data.title;

  addData.user_group_id = data.user_group_id.split(',').map(Number);
  addData.basic_rating_id = data.basic_rating_id.split(',').map(Number);

  selectedIds.value = addData.basic_rating_id;
  selectedKpIds.value = addData.user_group_id;


  console.log(addData)
  addIsEdit.value = 2;
}
const delShowMsd = async (data) => {
  var res = await scheduleDelete({id: data.id});
  console.log(res)
  if (res.code == 1) {
    layer.msg('删除成功！', {icon: 1})
    getHierarchicalData();
  } else {
    layer.msg(res.msg, {icon: 2})
  }
}
const columns6 = [
  {
    title: "考评标题",
    width: "150px",
    key: "title"
  },
  {
    title: "考评类型",
    width: "90px",
    customSlot: 'evaluation_type',
    key: "evaluation_type"
  },
  // {
  //   title: "考评开始类型",
  //   width: "90px",
  //   customSlot: 'evaluation_start_type',
  //   key: "evaluation_start_type"
  // },
  // {
  //   title: "时间（天）",
  //   width: "100px",
  //   key: "time",
  // },
  {
    title: "规则描述",
    width: "100px",
    key: "rule_description",
    ellipsisTooltip: true,
  },
  {
    title: "考评开始时间",
    width: "100px",
    key: "start_time"
  },
  {
    title: "考评结束时间",
    width: "100px",
    key: "end_time",

  },
  {
    title: '操作',
    width: '100px',
    customSlot: 'operator',
    key: 'operator',
    align: 'center',
    fixed: 'right'
  }
]
const addButton = ref([
  {
    text: "确认",
    callback: async () => {
      console.log(addData);
      console.log(selectedIds.value)
      console.log(selectedKpIds.value)
      if (addData.title=='') {
        layer.msg('请输入标题！', {icon: 2, time: 1000})
        return;
      }
      if (addData.evaluation_type == null || addData.evaluation_type == '') {
        layer.msg('请选择考评类型！', {icon: 2, time: 1000})
        return;
      }
      if (addData.time <= 0) {
        layer.msg('请填写时间（天）！', {icon: 2, time: 1000})
        return;
      }
      if (addData.evaluation_start_type == null) {
        layer.msg('请选择考评开始类型！', {icon: 2, time: 1000})
        return;
      }
      if (addData.start_time == null) {
        layer.msg('请选择考评开始时间！', {icon: 2, time: 1000})
        return;
      }
      if (addData.end_time == null) {
        layer.msg('请选择考评结束时间！', {icon: 2, time: 1000})
        return;
      }
      if (addData.rule_description == '') {
        layer.msg('请填写规则描述！', {icon: 2, time: 1000})
        return;
      }
      addData.user_group_id = selectedKpIds.value.join(',');
      addData.basic_rating_id = selectedIds.value.join(',');
      if (addData.user_group_id == '') {
        layer.msg('请选择考评范围！', {icon: 2, time: 1000})
        return;
      }
      if (addData.basic_rating_id == '') {
        layer.msg('请选择考评内容！', {icon: 2, time: 1000})
        return;
      }
      console.log(addData);
      if (addIsEdit.value == 1) {
        var res = await scheduleCreate(addData);
      } else {
        var res = await scheduleUpdate(addData);
      }
      console.log(res)
      if (res.code == 1) {
        layer.msg('提交成功！', {icon: 1})
        addShow.value = false;
        getHierarchicalData();
      } else {
        layer.msg(res.msg, {icon: 2})
      }
    }
  },
  {
    text: "取消",
    callback: () => {
      addShow.value = false;
    }
  }
])
</script>
<style>
.layui-table-header .layui-table-cell {
  background-color: #ECF8FA !important;
}
</style>
