<template>
  <div class="relative h-full flex-direction-column bg-white">
    <Header
      :title="title"
      :showBack="!isFirstEmployeePage"
      :showClose="showClose"
      :showCheckAll="showCheckAllBool"
      :isAllChecked="isAllCheckedBool"
      :isMultiple="isMultiple"
      @onBack="onPopStack"
      @onClose="onClose"
      @onChooseAll="onChooseAll"
    />
    <slot name="statement" />
    <WlSearch
      showType="default"
      @onClickDefault="onClickDefaultSearch"
    />
    <Structure
      @onClickFrameWork="onClickFrameWork"
      v-if="showStructure"
    />
    <div class="scroll-y flex-1">
      <ChooseList
        :list="currentData"
        :showLetter="isFirstEmployeePage"
        :letterData="letterData"
        :isMultiple="isMultiple"
        :checkedIds="selectedEmployeeIds"
        :checkedList="selectedEmployeeList"
        @onChange="onChangeChooseList"
      />
    </div>
    <EmployeeSearch
      v-model:show="employeeSearchVisible"
      :list="employeeData"
      :isMultiple="isMultiple"
      :checkedIds="selectedEmployeeIds"
      :checkedList="selectedEmployeeList"
      @onChange="onChangeChooseList"
    />
    <SeletorFooter
      v-if="isMultiple"
      v-model:list="selectedEmployeeList"
      @onConfirm="onConfirm"
      @onChoose="onHandleSelected"
    />
  </div>
</template>

<script lang="ts">
/*
 * @Author: Liao.xiuli
 * @Date: 2021-09-18 11:18:59
 * @Last Modified by: Liao.xiuli
 * @Last Modified time: 2024-03-27 13:34:23
 */
export default {
  name: "BCEmployeeSelector",
};
</script>

<script setup lang="ts">
import useStack from "./hooks/useStack";
import Store from "@mobileUI/store/index";
import { getDeptData } from "./api/index";
import { ref, computed, watch } from "vue";
import { setStoreData } from "@mobileUI/utils";
import useCheckAll from "././hooks/useCheckAll";
import Header from "./components/Header/index.vue";
import useEmployeeData from "./hooks/useEmployeeData";
import useSelectedData from "./hooks/useSelectedData";
import Structure from "./components/Structure/index.vue";
import ChooseList from "./components/ChooseList/index.vue";
import useHandleCheckStatus from "./hooks/useHandleCheckStatus";
import SeletorFooter from "./components/SeletorFooter/index.vue";
import WlSearch from "@mobileUI/components/WlSearch/src/index.vue";
import EmployeeSearch from "./components/EmployeeSearch/index.vue";
import {
  TEmployeeData,
  TFrameWorkData,
  TDepartmentData,
  TPositionType,
  TRenderData,
  TCheckedStatus,
  TDepartmentDataAddStatus,
} from "../type";
import { watchEffect } from "vue";

const { showCheckAll, isAllChecked } = useCheckAll();

const { stack, lastStackData, isFirstEmployeePage, onAddStack, onPopStack } = useStack();

const {
  treeData,
  letterData,
  employeeData,
  homeStaffData,
  onGetRenderData,
  onGetDepartmentData,
  onGetSubEmployeeData,
  onEmployeeDataAddAllDept,
  onEmployeeDataAddTopFive
} = useEmployeeData();

const {
  selectedEmployeeIds,
  selectedEmployeeList,
  onHandleSelected,
  onBatchAddSelectedList,
  onBatchRemoveSelectedList,
} = useSelectedData();

type TUseProps = {
  title?: string; //标题
  envData: TEnv.TEnvData;
  isMultiple?: boolean; //是否是多选
  chosedData?: string[]; //默认选择的员工数据
  showClose?: boolean; //是否显示关闭
  isFirstDeptPage?: boolean; //是否直接进组织架构选择页面
  showRecentChoose?: boolean; //是否显示最近常选
  requestParams: any; //接口请求参数
};

const props = withDefaults(defineProps<TUseProps>(), {
  title: "员工选择器",
  envData: null,
  isMultiple: true,
  chosedData: null,
  showClose: true,
  isFirstDeptPage: false,
  showRecentChoose: false,
  requestParams: null,
});

const employeeSearchVisible = ref(false);

const currentData = computed(() => {
  return useHandleCheckStatus(
    lastStackData.value,
    selectedEmployeeIds.value,
    selectedEmployeeList.value
  );
});

//是否显示组织架构
const showStructure = computed(() =>
  isFirstEmployeePage.value
  && currentData.value.length > 0
  && !props.isFirstDeptPage);

//是否显示全选
const showCheckAllBool = computed(() => showCheckAll(stack.value));

//是否全选
const isAllCheckedBool = computed(() => isAllChecked(currentData.value));

const emit = defineEmits<{
  (e: "onClose");
  (e: "onConfirm", val: TRenderData | TRenderData[]);
}>();

const onClose = () => emit("onClose");

const onConfirm = () => emit("onConfirm", selectedEmployeeList.value);

const onChangeChooseList = (
  item: TRenderData,
  type?: TPositionType,
  checkedStatus?: TCheckedStatus
) => {
  if (item.renderType === "employee") {
    if (props.isMultiple) {
      //如果是选择的最近常选的话
      if (item.key.startsWith("zjcx-")) {
        const result = onEmployeeDataAddTopFive(item as TEmployeeData);
        //兼容dept接口返回所有员工不包含最近常选的员工，然后直接将item放到选择列表里
        result ? onHandleSelected(result) : onHandleSelected(item as TEmployeeData);
      } else {
        onHandleSelected(onEmployeeDataAddAllDept(item as TEmployeeData));
      }
    } else {
      emit("onConfirm", item);
    }
  } else if (item.renderType === "department") {
    if (["title", "radio"].includes(type)) {
      //如果获取整个公司的人员的话传空
      const parentId = !!(item as TDepartmentData).parentIds ? item.id : "";
      //部门选择的话需要将当前部门对应的人员加到selectedList里
      //如果半选/未选，就要将部门下的员工全部加到selectedEmployeeList
      const list = onGetSubEmployeeData(parentId);
      checkedStatus === "checked" ? onBatchRemoveSelectedList(list) : onBatchAddSelectedList(list);
    } else if (type === "arrow") {
      onAddStack((item as TDepartmentDataAddStatus).children);
    }
  }
};

const onClickDefaultSearch = () => {
  employeeSearchVisible.value = true;
};

const onChooseAll = (bool) => {
  const parentIds = currentData.value[0]?.parentIds;
  const parentId = parentIds && parentIds.length > 0 ? parentIds[0] : "";
  const list = onGetSubEmployeeData(parentId);
  bool ? onBatchAddSelectedList(list) : onBatchRemoveSelectedList(list);
};

const onClickFrameWork = (item: TFrameWorkData) => {
  //id为2表示是组织架构
  if (item.id === "2") onAddStack(treeData.value);
};

const init = async () => {
  const result = await getDeptData(props.requestParams);
  const list = result?.data?.data_list ?? [];
  onGetDepartmentData(list);
  if (props.isFirstDeptPage) {
    onAddStack(treeData.value);
  } else {
    await onGetRenderData(props.showRecentChoose);
    onAddStack(homeStaffData.value);
  }
};

let unStoreWatch = null;
unStoreWatch = watch(() => props.envData, () => {
  if (props.envData) {
    setStoreData(Store as TEnv.TEnvData, props.envData);
    //初始化操作
    init();
    unStoreWatch && unStoreWatch();
  };
}, { immediate: true });

const unwatch = watchEffect(() => {
  //默认选中传入员工id，在employeeData做查询来显示在选中列表里
  if (!props.chosedData?.length || !employeeData.value?.length) return;
  const filterList = employeeData.value.filter((res: TEmployeeData) => props.chosedData.includes(res.id))
  onBatchAddSelectedList(filterList);
  unwatch();
});
</script>
