<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 { postAddAssessment, updateAssessment } from "@/api/assessment";
import { postListTreeWithUser } from "@/api/department";
import { getTemplateInfoList } 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
  }
});
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,
  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 getTemplateInfoList(templateparams);
  resTmp.value = data.records;
  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);
  console.log(treeDept_person.value, "人员获取的值");
};

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 getAssessmentDetailsApi = async () => {
  const { data, code, msg } = await getAssessmentDetails({ id: params.id });
  if (code === 200) {
    Object.assign(form, data);
    console.log(form, "获取的值");
    if (form.assessmentType === 1) {
      postListTreeWithUserApi();
    } else if (form.assessmentType === 0) {
      getPersonList();
    } else if (form.assessmentType === 2) {
      const yiliao = await postOrganizationUserPage({
        organizationType: "group",
        pageNumber: 1,
        pageSize: 1000
      });
      treeDeptList.value = yiliao.data.records;
      console.log("获取的医疗组的值", treeDeptList.value);
    }
  } 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="被考核类型">
        <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
                  v-for="(item, index) in form.assessmentObjectList"
                  :key="index"
                  class="w-full mt-1"
                >
                  <el-tree-select
                    v-if="form.assessmentType === 1"
                    v-model="item.assessmentObjectId"
                    :data="treeDept"
                    :render-after-expand="false"
                    show-checkbox
                    disabled
                    :props="{
                      label: 'userName',
                      value: 'userCode',
                      children: 'childrenRes'
                    }"
                    style="width: 180px"
                  />
                  <!-- 员工多个 -->
                  <el-tree-select
                    v-if="form.assessmentType === 0"
                    v-model="item.assessmentObjectId"
                    :data="treeDept_person"
                    :render-after-expand="false"
                    show-checkbox
                    disabled
                    style="width: 180px"
                    :props="{
                      label: 'userNameNew',
                      value: 'userCodeNew',
                      children: 'children'
                    }"
                  />

                  <!-- 医疗组，负责人 -->
                  <el-select
                    v-if="form.assessmentType != 0 && form.assessmentType != 1"
                    v-model="item.assessmentObjectId"
                    disabled
                  >
                    <el-option
                      v-for="(it, id) in treeDeptList"
                      :key="id"
                      :label="it.realName"
                      :value="it.userCode"
                    />
                  </el-select>
                </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
                  v-for="(item, index) in form.assessmentObjectList"
                  :key="index"
                  class="w-full flex mt-1"
                >
                  <el-select
                    v-model="item.assessmentModelId"
                    disabled
                    placeholder="请选择"
                    filterable
                    style="width: 180px"
                  >
                    <el-option
                      v-for="itemTmp in resTmp"
                      :key="itemTmp.id"
                      :label="itemTmp.tpName"
                      :value="itemTmp.id"
                    />
                  </el-select>
                </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"
      @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>
