<script setup lang="ts">
import { ref, reactive, nextTick, watch } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { Calendar } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { postAddAssessment } from "@/api/assessment";
import {
  postListTreeWithUser,
  postListTree,
  postListTreeWithUserApi,
  treeDept
} from "@/api/department";
import { encryption } from "@/utils/encrypt";
// 人员,医疗组,负责人
import {
  postUserList,
  postOrganizationUserPage,
  getLeaderList
} from "@/api/userSetting";
// 医疗组
import { getTemplateInfoList } from "@/api/templateInfo";
// 获取医疗组的数据
import { postPageGroup } from "@/api/userGroup";
import ElPicker from "@/components/ELPicker/index.vue";
const $emit = defineEmits(["addHandClick"]);
const dialogVisibleAdd = ref(false);
const titleHeader = ref<any>("发起考核");
// 季度 半年
const ElPickerRef = ref();
const form = reactive({
  name: "",
  cycle: "月度",
  cycleValue: "",
  assessmentType: null,
  listArr: [
    {
      assessmentObjectId: "",
      idList: [],
      assessmentObjectName: "",
      assessmentModelId: "",
      assessmentModelName: ""
    }
  ]
});
const rules = reactive({
  name: [{ required: true, message: "请输入考核名称", trigger: "blur" }],
  cycle: [{ required: true, message: "请选择考核周期", trigger: "change" }]
});
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 formRef = ref();
const handleClose = () => {
  formRef.value.clearValidate(); // 清除验证错误
  formRef.value.resetFields(); // 重置表单字段
  dialogVisibleAdd.value = !dialogVisibleAdd.value;
  ElMessage({
    message: "已关闭"
  });
  // ElMessageBox.confirm("确认关闭弹窗吗？")
  //   .then(() => {})
  //   .catch(() => {
  //     // catch error
  //   });
};
const arrList = ref([]); // 考核对象与模版设置
const transformArrayFormat = data => {
  return data
    .map(item => {
      return item.idList.map((id, index) => {
        return {
          assessmentObjectId: item?.assessmentObjectId[index],
          assessmentObjectName: item?.assessmentObjectName[index],
          assessmentModelId: item?.assessmentModelId,
          assessmentModelName: item?.assessmentModelName
        };
      });
    })
    .flat();
};
// 添加部门保存
const saveDepartment = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      if (!form.cycleValue) {
        ElMessage.error("请选择考核周期的具体时间");
        return false;
      }
      console.log("考核周期", form.listArr);
      form.assessmentObjectList = transformArrayFormat(form.listArr);
      if (timeType.value == "月度") {
        form.cycleValue = dayjs(new Date(form.cycleValue)).format("YYYY-MM");
      }
      if (timeType.value == "年度") {
        form.cycleValue = dayjs(new Date(form.cycleValue)).format("YYYY");
      }
      if (timeType.value == "日期") {
        form.cycleValue = dayjs(new Date(form.cycleValue)).format("YYYY-MM-DD");
      }
      form.assessmentObjectList = form.assessmentObjectList.filter(
        item => item.assessmentObjectId && item.assessmentObjectName
      );
      delete form.listArr;
      const { code, msg } = await postAddAssessment(form);
      if (code === 200) {
        ElMessage({
          message: "添加成功",
          type: "success"
        });
        $emit("addHandClick");
        dialogVisibleAdd.value = false;
      } else {
        // ElMessage.error(msg);
      }
    }
  });
};
const open = (item: any, index: string) => {
  // postListTreeWithUserApi();
  assessmentTypeShow.value = true;
  Object.assign(form, {
    name: "",
    cycle: "月度",
    cycleValue: "",
    assessmentType: null,
    listArr: [
      {
        idList: [],
        assessmentObjectId: null,
        assessmentObjectName: null,
        assessmentModelId: null,
        assessmentModelName: null
      }
    ]
  });
  if (item) {
    titleHeader.value = index;
  }
  dialogVisibleAdd.value = true;
};
const addNew = () => {
  form.listArr.push({
    assessmentObjectId: "",
    idList: [],
    assessmentObjectName: "",
    assessmentModelId: "",
    assessmentModelName: ""
  });
  arrList.value.push([]);
  // form.assessmentObjectList.left.push({ value: "" });
};
const deleteItem = (index: any) => {
  form.listArr.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;
  console.log("timeType.value", timeType.value);
  switch (value) {
    case "年度":
      form.cycleValue = "";
      format.value = "YYYY";
      pickerType.value = "year";
      break;
    case "月度":
      form.cycleValue = "";
      format.value = "YYYY-MM";
      pickerType.value = "month";

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

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

      break;
    case "半年":
      form.cycleValue = "";
      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 treeDeptList = ref([]);
const templateparams = reactive({
  page: 1,
  pageSize: 100
});
const resTmp = ref([]);

// 医疗 -- 部门负责人
const selectRefs = ref();
const handChange = index => {
  const arr = treeDeptList.value.filter(item => {
    return form.listArr[index].idList.includes(item.groupCode);
  });
  form.listArr[index].assessmentObjectId = arr.map(item => item.groupCode);
  form.listArr[index].assessmentObjectName = arr.map(item => item.groupName);
};
const handChange1 = index => {
  const arr = treeDeptList.value.filter(item => {
    return form.listArr[index].idList.includes(item.userCode);
  });
  form.listArr[index].assessmentObjectId = arr.map(item => item.userCode);
  form.listArr[index].assessmentObjectName = arr.map(item => item.realName);
};

const assessmentTypeRef = ref();
const handleRreeSelect = index => {
  const arr = assessmentTypeRef.value[index].getCheckedNodes().filter(item => {
    return item.children.length == 0;
  });
  if (form.assessmentType === 0) {
    // 更新选中的 idList
    // form.listArr[index].idList = filteredNodes;
    // let aa = [];
    // form.listArr[index].idList.map(item => {
    //   if (item.substring(0, 4) == "user") {
    //     aa.push(item);
    //   }
    // });
    // console.log(11111, aa);
    // form.listArr[index].idList = aa;
    form.listArr[index].assessmentObjectId = arr.map(item => {
      if (item.value.substring(0, 4) == "user") {
        return item.value;
      }
    });
    form.listArr[index].assessmentObjectName = arr.map(item => {
      if (item.value.substring(0, 4) == "user") {
        return item.label;
      }
    });
  } else {
    form.listArr[index].assessmentObjectId = arr.map(item => {
      return item.value;
    });
    form.listArr[index].assessmentObjectName = arr.map(item => {
      return item.label;
    });
  }
};
const handleSelect = index => {
  form.listArr[index].assessmentModelName = form.listArr[index].am.tpName;
  form.listArr[index].assessmentModelId = form.listArr[index].am.id;
};
const aaaa = a => {
  console.log(a);
};
// 考核类型
const dpetTree = ref();
// 转换函数 --- 部门
const convertDepartmentDataRecursive = data => {
  return data.map(department => {
    const { deptCode, deptName, childrenRes } = department;
    return {
      value: deptCode,
      label: deptName,
      children:
        childrenRes.length > 0
          ? childrenRes.map(child => convertDepartmentDataRecursive([child])[0])
          : []
    };
  });
};
// 转换函数 --- 人员
const convertDepartmentDataRecursive_Person = data => {
  return data.map(department => {
    const { userNameNew, userCodeNew, children } = department;
    return {
      value: userCodeNew,
      label: userNameNew,
      children:
        children.length > 0
          ? children.map(
              child => convertDepartmentDataRecursive_Person([child])[0]
            )
          : []
    };
  });
};
const treeDeptListOkay = ref([]);
const assessmentTypeShow = ref(true);
const assessmentTypeApi = async value => {
  assessmentTypeShow.value = false;
  // 人员,医疗组,负责人
  const { data, code } = await getTemplateInfoList(templateparams);
  resTmp.value = data.records;
  switch (value) {
    case 0:
      postListTreeWithUserApi();
      break;
    case 1:
      const { data, code } = await postListTree();
      dpetTree.value = convertDepartmentDataRecursive(data);
      break;
    case 2:
      const yiliao = await postPageGroup({
        pageNumber: 1,
        pageSize: 1000
      });
      treeDeptList.value = yiliao.data.records;
      break;
    case 3:
      const fuzhere = await getLeaderList({
        type: "dept"
      });
      treeDeptList.value = fuzhere.data;
  }
};
const monthTime = ref("");
defineExpose({
  open
});
const handChangeTree = value => {
  console.log(1122131, value);
  // if (Array.isArray(value)) {
  //   value.forEach(item => {
  //     if (item.substring(0, 4) != "user") {
  //       return delete item;
  //     }
  //   });
  // }
};
const idList = ref([]);
</script>

<template>
  <div>
    <el-dialog v-model="dialogVisibleAdd" :title="titleHeader" width="500">
      <el-form
        ref="formRef"
        :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" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="考核周期" prop="cycle">
          <el-radio-group v-model="form.cycle" @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"
            :type="pickerType"
            :format="format"
            placeholder="请选择"
            @change="aaaa"
          />
          <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"
              />
            </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="请选择被考核类型"
            @change="assessmentTypeApi"
          >
            <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.listArr"
                :rules="formLeftRules"
              >
                <el-form-item label="被考核对象" prop="left">
                  <div
                    v-for="(item, index) in form.listArr"
                    :key="index"
                    class="w-full mt-1"
                  >
                    <el-tree-select
                      v-if="form.assessmentType === 0"
                      ref="assessmentTypeRef"
                      v-model="item.idList"
                      multiple
                      :data="convertDepartmentDataRecursive_Person(treeDept)"
                      :render-after-expand="false"
                      show-checkbox
                      style="width: 180px"
                      @change="handChangeTree"
                      @check-change="handleRreeSelect(index)"
                    />
                    <el-tree-select
                      v-if="form.assessmentType === 1"
                      ref="assessmentTypeRef"
                      v-model="item.idList"
                      :data="dpetTree"
                      show-checkbox
                      multiple
                      style="width: 180px"
                      :render-after-expand="false"
                      @check-change="handleRreeSelect(index)"
                    />
                    <el-select
                      v-if="form.assessmentType == 2"
                      ref="selectRefs"
                      v-model="item.idList"
                      multiple
                      @change="handChange(index)"
                    >
                      <el-option
                        v-for="(it, id) in treeDeptList"
                        :key="id"
                        :label="it.groupName"
                        :value="it.groupCode"
                      />
                    </el-select>
                    <el-select
                      v-if="form.assessmentType == 3"
                      ref="selectRefs"
                      v-model="item.idList"
                      multiple
                      @change="handChange1(index)"
                    >
                      <el-option
                        v-for="it in treeDeptList"
                        :key="it.userCode"
                        :label="it.realName"
                        :value="it.userCode"
                      />
                    </el-select>
                    <el-select v-if="assessmentTypeShow" multiple />
                  </div>
                </el-form-item>
              </el-form>
            </div>
            <div class="w-1/2 ml-7">
              <el-form
                label-position="top"
                :model="form.listArr"
                :rules="formRightRules"
              >
                <el-form-item label="考核模板" prop="right">
                  <div
                    v-for="(item, index) in form.listArr"
                    :key="index"
                    class="w-full flex mt-1"
                  >
                    <el-select
                      v-model="item.am"
                      placeholder="请选择"
                      filterable
                      style="width: 180px"
                      value-key="id"
                      @change="handleSelect(index)"
                    >
                      <el-option
                        v-for="itemTmp in resTmp"
                        :key="itemTmp.id"
                        :label="itemTmp.tpName"
                        :value="itemTmp"
                        style="width: 180px"
                      />
                    </el-select>
                    <div
                      v-if="index !== 0"
                      class="ml-7 cursor-pointer w-1"
                      @click="deleteItem(index)"
                    >
                      <el-text type="danger">
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </el-text>
                    </div>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <template #label>
            <div class="cursor-pointer w-14" @click="addNew">
              <el-text type="primary">
                <el-icon> <Plus /> </el-icon>添加
              </el-text>
            </div>
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="saveDepartment"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
