<script setup lang="ts">
import { ref, reactive, nextTick, onMounted, onActivated } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { Calendar } from "@element-plus/icons-vue";
import { getAssessmentDetails } from "@/api/assessment";
import dayjs from "dayjs";
// 获取医疗组的数据
import { postPageGroup } from "@/api/userGroup";
import { postAddAssessment, updateAssessment } from "@/api/assessment";
import { postListTreeWithUser } from "@/api/department";
import { getTemplateInfoAllList } from "@/api/templateInfo";
import ElPicker from "@/components/ELPicker/index.vue";
// 人员,医疗组,负责人
import {
  postUserList,
  postOrganizationUserPage,
  getLeaderList
} from "@/api/userSetting";
const $emit = defineEmits(["addHandClick"]);
const $props = defineProps({
  id: {
    type: String
  },
  bistatus: {
    type: Number,
    default: 1
  }
});
const params = reactive({
  id: $props.id
});

const dialogVisibleAdd = ref(false);
const btn = ref(true);
const btnShow = () => {
  btn.value = false;
};
// 季度 半年
const ElPickerRef = ref();
const form = reactive({
  name: "",
  cycle: "月度",
  cycleValue: "",
  assessmentType: null,
  scoreConversion: null,
  assessmentObjectList: [
    {
      assessmentObjectId: "",
      assessmentObjectName: "",
      assessmentModelId: "",
      assessmentModelName: ""
    }
  ]
});
const rules = reactive({
  name: [{ required: true, message: "请填写名称", trigger: "blur" }]
});
const formLeftRules = reactive({
  left: [{ required: true, message: "请选择考核指标", trigger: "blur" }],
  value: [{ required: true, message: "请选择被考核对象", trigger: "blur" }]
});
const formRightRules = reactive({
  left: [{ required: true, message: "请选择考核指标", trigger: "blur" }],
  right: [{ required: true, message: "请选择考核模板", trigger: "blur" }]
});
const handleClose = () => {
  btn.value = true;
};
// 添加部门保存
const saveDepartment = async () => {
  updateAssessmentApi();
};
const addNew = () => {
  form.assessmentObjectList.push({
    assessmentObjectId: "",
    assessmentObjectName: "",
    assessmentModelId: "",
    assessmentModelName: ""
  });
  // form.assessmentObjectList.left.push({ value: "" });
};
const deleteItem = (index: any) => {
  form.assessmentObjectList.splice(index, 1);
  // form.assessmentObjectList.right.splice(index, 1);
};
// 单选
const timeType = ref<any>("月度");
const quarterValue = ref(true);
const format = ref<any>("YYYY-MM");
const pickerType = ref<any>("month");
const handleRegionChange = (value: any) => {
  timeType.value = value;
  switch (value) {
    case "年度":
      format.value = "YYYY";
      pickerType.value = "year";
      break;
    case "月度":
      format.value = "YYYY-MM";
      pickerType.value = "month";

      break;
    case "日期":
      format.value = "YYYY-MM-DD";
      pickerType.value = "";

      break;
    case "季度":
      quarterValue.value = true;

      break;
    case "半年":
      quarterValue.value = false;

      break;
  }
};
const yearTime = ref<any>(dayjs(new Date()).format("YYYY"));
const decreaseYear = () => {
  yearTime.value = dayjs().year(yearTime.value).subtract(1, "year").year(); // 减一年
};
const increaseYear = () => {
  yearTime.value = dayjs().year(yearTime.value).add(1, "year").year(); // 加一年
};
const monthOne = item => {
  let start = "";
  let end = "";

  switch (item) {
    case "一季度":
      start = `${yearTime.value}-01-01`;
      end = `${yearTime.value}-03-31`;
      break;
    case "二季度":
      start = `${yearTime.value}-04-01`;
      end = `${yearTime.value}-06-30`;
      break;
    case "三季度":
      start = `${yearTime.value}-07-01`;
      end = `${yearTime.value}-09-30`;
      break;
    case "四季度":
      start = `${yearTime.value}-10-01`;
      end = `${yearTime.value}-12-31`;
      break;
    case "上半年":
      start = `${yearTime.value}-01-01`;
      end = `${yearTime.value}-06-30`;
      break;
    case "下半年":
      start = `${yearTime.value}-07-01`;
      end = `${yearTime.value}-12-31`;
      break;
  }
  form.cycleValue = `${yearTime.value}年${item}`;
  // return `从 ${start} 到 ${end}`; // 设置时间区间
};
// 部门人员与考核模板数据
const treeDept = ref([]);
const templateparams = reactive({
  page: 1,
  pageSize: 100
});
const resTmp = ref([]);
const postListTreeWithUserApi = async () => {
  const res = await postListTreeWithUser();
  const { data = [], code } = await getTemplateInfoAllList();
  resTmp.value = data;
  treeDept.value = [];
  treeDept.value = transformData(res.data);
};
const treeDept_person = ref([]);

const transformData_person = (
  data,
  newDeptCodeKey = "userCodeNew",
  newDeptNameKey = "userNameNew"
) => {
  return data.map(item => {
    const newItem = { ...item };
    newItem.children = [
      ...(newItem.childrenUserRes || []).map(child => ({
        ...child
      }))
    ];
    delete newItem.childrenUserRes;
    delete newItem.childrenRes;

    // 重命名属性
    newItem.children = newItem.children.map(child => {
      const newChild = { ...child };
      newChild.userNameNew = child.realName;
      newChild.userCodeNew = child.userCode;
      return newChild;
    });

    // 递归处理子节点
    if (newItem.children && newItem.children.length) {
      newItem.children = transformData_person(
        newItem.children,
        newDeptCodeKey,
        newDeptNameKey
      );
    }
    return newItem;
  });
};
// 获取人员的数据
const getPersonList = async () => {
  const res = await postListTreeWithUser();
  let treeList = res.data.map(item => {
    return {
      childrenRes: item.childrenRes,
      childrenUserRes: item.childrenUserRes,
      userCodeNew: item.deptCode,
      userNameNew: item.deptName
    };
  });
  treeDept_person.value = transformData_person(treeList);
};

postListTreeWithUserApi();
function transformData(arr) {
  return arr.map(item => {
    const {
      deptName: userName,
      deptCode: userCode,
      childrenRes,
      ...rest
    } = item;

    return {
      userName,
      userCode,
      childrenRes: childrenRes ? transformData(childrenRes) : [],
      ...rest
    };
  });
}
// 详情
const treeDeptList = ref([]);
const optionValue = ref([]);
// 考核对象
const assessmentObjectList = ref([]);
// 考核模板
const assessmentModelList = ref([]);

const getAssessmentDetailsApi = async () => {
  const { data, code, msg } = await getAssessmentDetails({ id: params.id });
  if (code === 200) {
    Object.assign(form, data);
    console.log(123123, form.assessmentObjectList);
    // 用于存放分组后的数组
    let groupedData = [];
    // 用于存储每个 `assessmentModelId` 的组
    let modelIdMap = {};
    // 遍历数据，将数据按 `assessmentModelId` 分组
    if (form.assessmentObjectList && form.assessmentObjectList.length > 0) {
      form.assessmentObjectList.forEach(item => {
        const modelId = item.assessmentModelId;
        // 如果该 modelId 已存在，则将数据加入对应的组
        if (!modelIdMap[modelId]) {
          modelIdMap[modelId] = [];
        }
        modelIdMap[modelId].push(item);
      });
    }
    // 将分组后的数据转为二维数组
    for (let modelId in modelIdMap) {
      groupedData.push(modelIdMap[modelId]);
    }
    // 打印结果
    console.log(groupedData, 2222);
    assessmentObjectList.value = groupedData;
    if (form.assessmentObjectList && form.assessmentObjectList.length > 0) {
      form.assessmentObjectList.map(item => {
        assessmentModelList.value.push({
          assessmentModelId: item.assessmentModelId,
          assessmentModelName: item.assessmentModelName
        });
      });
    }
    assessmentModelList.value = Array.from(
      new Map(
        assessmentModelList.value.map(item => [item.assessmentModelId, item])
      ).values()
    );
    if (form.assessmentObjectList) {
      form.assessmentObjectList.map(item => {
        optionValue.value.push(item.assessmentObjectId);
      });
    }

    if (form.assessmentType === 1) {
      postListTreeWithUserApi();
    } else if (form.assessmentType === 0) {
      getPersonList();
    } else if (form.assessmentType === 2) {
      const yiliao = await postPageGroup({
        pageNumber: 1,
        pageSize: 1000
      });
      treeDeptList.value = yiliao.data.records;
    }
  } else {
    ElMessage.error(msg);
  }
};
getAssessmentDetailsApi();
// 修改
const updateAssessmentApi = async () => {
  const { code, msg } = await updateAssessment({ id: params.id, ...form });
  if (code === 200) {
    btn.value = true;
    ElMessage.success("修改成功");
  } else {
    ElMessage.error(msg);
  }
};
onMounted(() => {
  console.log("onMountedsdada", $props.id);
});
</script>

<template>
  <div class="w-[500px] m-auto">
    <el-form
      :model="form"
      label-width="auto"
      style="max-width: 600px"
      :rules="rules"
      label-position="top"
    >
      <el-form-item label="考核名称" prop="name">
        <el-input v-model="form.name" :disabled="btn" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="考核周期">
        <el-radio-group
          v-model="form.cycle"
          disabled
          @change="handleRegionChange"
        >
          <el-radio value="月度" size="large">月度</el-radio>
          <el-radio value="季度" size="large">季度</el-radio>
          <el-radio value="半年" size="large">半年</el-radio>
          <el-radio value="年度" size="large">年度</el-radio>
          <el-radio value="日期" size="large">日期</el-radio>
        </el-radio-group>
        <el-date-picker
          v-if="
            timeType === '月度' || timeType === '日期' || timeType === '年度'
          "
          v-model="form.cycleValue"
          disabled
          :type="pickerType"
          :format="format"
          placeholder="请选择"
        />
        <el-dropdown
          v-else-if="timeType === '季度' || timeType === '半年'"
          trigger="click"
        >
          <span class="el-dropdown-link navbar-bg-hover select-none">
            <el-input
              v-model="form.cycleValue"
              style="width: 240px"
              placeholder="请选择"
              :prefix-icon="Calendar"
              disabled
            />
          </span>
          <template #dropdown>
            <el-dropdown-menu class="setting" style="width: 300px">
              <div class="flex justify-between align-center text-base mt-4">
                <div
                  class="cursor-pointer ml-4 text-xs pt-2"
                  @click="decreaseYear"
                >
                  <el-icon>
                    <DArrowLeft />
                  </el-icon>
                </div>
                <div>{{ yearTime }}</div>
                <div
                  class="cursor-pointer mr-4 text-xs pt-2"
                  @click="increaseYear"
                >
                  <el-icon>
                    <DArrowRight />
                  </el-icon>
                </div>
              </div>
              <div
                v-if="quarterValue"
                class="flex justify-center align-center mt-5 mb-5"
              >
                <el-dropdown-item @click="monthOne('一季度')">
                  一季度
                </el-dropdown-item>
                <el-dropdown-item @click="monthOne('二季度')">
                  二季度
                </el-dropdown-item>
                <el-dropdown-item @click="monthOne('三季度')">
                  三季度
                </el-dropdown-item>
                <el-dropdown-item @click="monthOne('四季度')">
                  四季度
                </el-dropdown-item>
              </div>
              <div v-else class="flex justify-around align-center mt-5 mb-5">
                <el-dropdown-item @click="monthOne('上半年')">
                  上半年
                </el-dropdown-item>
                <el-dropdown-item @click="monthOne('下半年')">
                  下半年
                </el-dropdown-item>
              </div>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-form-item>
      <el-form-item label="是否支持得分换算" prop="scoreConversion">
        <el-radio-group v-model="form.scoreConversion" disabled>
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="被考核类型">
        <el-select
          v-model="form.assessmentType"
          placeholder="请选择被考核类型"
          disabled
        >
          <el-option label="员工" :value="0" />
          <el-option label="部门" :value="1" />
          <el-option label="医疗" :value="2" />
          <el-option label="部门负责人" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item
        label="被考核对象与模板设置"
        prop="form1"
        label-position="top"
      >
        <div class="w-full flex">
          <div class="w-1/3">
            <el-form
              label-position="top"
              :model="form.assessmentObjectList"
              :rules="formLeftRules"
            >
              <el-form-item label="被考核对象" prop="left">
                <div class="w-full mt-1 flex flex-wrap">
                  <!-- 人员，负责人 -->
                  <!-- <el-select
                    v-if="form.assessmentType == 0 || form.assessmentType == 3"
                    v-model="optionValue"
                    multiple
                    disabled
                  >
                    <el-option
                      v-for="(it, id) in form.assessmentObjectList"
                      :key="id"
                      :label="it.assessmentObjectName"
                      :value="it.assessmentObjectId"
                    />
                  </el-select> -->
                  <div
                    v-for="(item, index) in assessmentObjectList"
                    :key="index"
                    class="text-gray-400 w-full flex flex-wrap object mt-1"
                  >
                    <div v-for="(it, id) in item" :key="id" class="h-6">
                      {{ it.assessmentObjectName }},
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </div>
          <div class="w-1/2 ml-7">
            <el-form
              label-position="top"
              :model="form.assessmentObjectList"
              :rules="formRightRules"
            >
              <el-form-item label="考核模板" prop="right">
                <div class="w-full flex flex-wrap mt-1">
                  <!-- <el-select
                    v-model="item.assessmentModelId"
                    disabled
                    placeholder="请选择"
                    filterable
                    style="width: 180px"
                  >
                    <el-option
                      v-for="itemTmp in form.assessmentObjectList"
                      :key="itemTmp.assessmentModelId"
                      :label="itemTmp.assessmentModelName"
                      :value="itemTmp.assessmentModelId"
                    />
                  </el-select> -->
                  <div
                    v-for="(item, index) in assessmentModelList"
                    :key="index"
                    class="text-gray-400 w-full flex flex-wrap object mt-1"
                  >
                    <div>{{ item.assessmentModelName }}</div>
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <el-button
      v-if="btn"
      class="float-right mt-4"
      type="warning"
      :disabled="bistatus == 0"
      @click="btnShow"
      >编辑</el-button
    >
    <div v-else class="float-right mt-4">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveDepartment"> 确认 </el-button>
    </div>
  </div>
</template>

<style scoped>
.aaa {
  font-size: 12px;

  div {
    overflow: hidden;

    /* 隐藏超出的部分 */
    text-overflow: ellipsis;

    /* 显示省略号 */
    white-space: nowrap;

    /* 防止文本换行 */
    div {
      font-weight: 500;
      border: 1px solid gray;
      border-radius: 5px;
    }
  }
}

.object {
  font-size: 12px;
  font-weight: 500;
  border: 1px solid gray;
  border-radius: 5px;
}
</style>
