<template>
  <ModalPanel
    :visible="props.visible"
    :width="1200"
    :isDeptSelect="data.isDeptSelect"
    :title="t('添加人员')"
    @submit="submit"
    @close="close"
  >
    <template #header>
      <a-row class="header-box">
        <a-col span="24">
          <div class="inline-block pr-6"> <span class="required-dot">*</span>选择类型 </div>
          <a-select
            v-model:value="data.selectType"
            @change="handleTypeChange"
            style="width: calc(100% - 92px)"
          >
            <a-select-option :value="0">选择人员</a-select-option>
            <a-select-option :value="1">按组织批量选择</a-select-option>
          </a-select>
        </a-col>
      </a-row>
    </template>
    <template #left>
      <OrganizationalTree
        @select="handleSelect"
        @check="handleCheck"
        :isCheckable="data.isDeptSelect"
      />
    </template>
    <div v-if="!data.isDeptSelect" class="relative h-full">
      <!-- 已选 -->
      <Selected
        v-if="visible"
        type="user"
        :list="data.selectedList"
        @abolish="abolishChecked"
        :disabledIds="props.disabledIds"
      />
      <div class="absolute top-2 right-105px flex items-center"
        ><SearchBox @search="search" /><div
          class="h-6 pr-4"
          style="border-right: 1px solid #ddd"
        ></div
      ></div>
      <div class="list-page-box" v-if="visible && data.list.length > 0">
        <UserCard
          :class="data.selectedIds.includes(item.id) ? 'picked' : 'not-picked'"
          :disabled="props.disabledIds && props.disabledIds.includes(item.id) ? true : false"
          v-for="(item, index) in data.list"
          :key="index"
          :item="item"
          @click="checked(item)"
        >
          <template #check>
            <a-checkbox size="small" :checked="data.selectedIds.includes(item.id)" />
          </template>
        </UserCard>

        <div class="page-box">
          <a-pagination
            v-model:current="data.page.current"
            v-model:pageSize="data.page.pageSize"
            :total="data.page.total"
            show-less-items
            show-size-changer
            show-quick-jumper
        /></div>
      </div>
      <EmptyBox v-if="data.list.length == 0" />
    </div>
  </ModalPanel>
</template>

<script setup lang="ts">
  import { computed, onMounted, reactive, watch } from 'vue';
  import OrganizationalTree from '/@/components/SelectOrganizational/src/OrganizationalTree.vue';
  import UserCard from '/@/components/SelectOrganizational/src/card/UserCard.vue';
  import Selected from '/@/components/SelectOrganizational/src/Selected.vue';
  import { ModalPanel, EmptyBox, SearchBox } from '/@/components/ModalPanel/index';
  import { getUserList, getUserMulti } from '/@/api/system/user';
  import { UserInfo } from '/@/api/system/user/model';
  import { cloneDeep } from 'lodash-es';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  const emits = defineEmits(['change', 'changeNames', 'close']);

  const props = defineProps({
    selectedIds: {
      type: Array as PropType<string[]>,
    },
    selectedList: {
      type: Array as PropType<any>,
    },
    disabledIds: {
      type: Array as PropType<string[]>,
      default: () => [],
    },
    multiple: Boolean,
    visible: Boolean,
  });

  let data: {
    multiSelect: boolean;
    page: { current: number; total: number; pageSize: number };
    list: Array<UserInfo>;
    selectedList: Array<UserInfo>;
    selectedIds: Array<string>;
    searchConfig: {
      keyword: string;
      deptId: string;
    };
    selectType: number;
    isDeptSelect: boolean;
    departmentIds: Array<string>;
  } = reactive({
    multiSelect: false,
    page: {
      current: 1,
      total: 0,
      pageSize: 12,
    },
    selectedIds: [],
    list: [],
    selectedList: [],
    searchConfig: {
      keyword: '',
      deptId: '',
    },
    selectType: 0,
    isDeptSelect: false,
    departmentIds: [],
  });

  const paramRef = computed(() => {
    return {
      limit: data.page.current,
      size: data.page.pageSize,
      departmentId: data.searchConfig.deptId,
      keyword: data.searchConfig.keyword,
    };
  });

  watch(
    () => [data.page.current, data.page.pageSize],
    () => {
      getList();
    },
  );
  onMounted(() => {
    show();
  });
  async function show() {
    data.selectedIds = [];
    data.selectedList = [];
    data.page.current = 1;
    data.page.total = 0;
    data.searchConfig.deptId = '';

    await getList();
    if (props.selectedList && Array.isArray(props.selectedList)) {
      data.selectedList = cloneDeep(props.selectedList);
      data.selectedIds = props.selectedList.map((ele) => {
        return ele.id;
      });
    } else {
      if (props.selectedIds && Array.isArray(props.selectedIds)) {
        data.selectedIds = cloneDeep(props.selectedIds);
      }
      await getSelectedList();
    }
  }
  function submit() {
    if (data.isDeptSelect) {
      emits('change', data.departmentIds, data.selectType);
    } else {
      emits('change', data.selectedIds, data.selectType);
      changeSelectedNames();
    }
    close();
  }
  function close() {
    data.list = [];
    data.selectedIds = [];
    data.selectedList = [];
    emits('close', false);
  }
  function checked(item) {
    if (
      props.disabledIds &&
      Array.isArray(props.disabledIds) &&
      props.disabledIds.includes(item.id)
    ) {
      return;
    }
    if (props.multiple && props.multiple == true) {
      if (data.selectedIds.includes(item.id)) {
        data.selectedIds.splice(
          data.selectedIds.findIndex((itemId) => itemId === item.id),
          1,
        );
        data.selectedList.splice(
          data.selectedList.findIndex((ele) => ele.id === item.id),
          1,
        );
      } else {
        data.selectedIds.push(item.id);
        data.selectedList.push(item);
      }
    } else {
      if (data.selectedIds.includes(item.id)) {
        data.selectedIds = [];
        data.selectedList = [];
      } else {
        data.selectedIds = [item.id];
      }
    }
  }

  async function getList() {
    data.list = [];
    data.page.total = 0;
    let res = await getUserList(paramRef.value);
    if (res.total) {
      data.page.total = res.total;
    }
    if (res.list.length > 0) {
      res.list.forEach((ele) => {
        let item = {
          name: ele.name, //姓名
          id: ele.id, //ID
          code: ele.code, //code
          gender: !isNaN(ele.gender) ? ele.gender : -1, //性别
        };
        data.list.push(item);
      });
    }
  }
  function search(keyword: string) {
    data.page.current = 1;
    data.searchConfig.keyword = keyword;
    getList();
  }
  function handleSelect(deptId = '') {
    if (data.isDeptSelect) return;
    data.page.current = 1;
    data.searchConfig.deptId = deptId;
    getList();
  }

  function handleCheck(ids = []) {
    data.departmentIds = ids;
  }
  async function getSelectedList() {
    let users = await getUserMulti(data.selectedIds.join(','));
    if (users.length > 0) {
      users.forEach((ele) => {
        data.selectedList.push({
          name: ele.name, //姓名
          id: ele.id, //ID
          code: ele.code, //code
          gender: !isNaN(ele.gender) ? ele.gender : -1, //性别
        });
      });
      changeSelectedNames();
    }
  }
  function changeSelectedNames() {
    let userNames = data.selectedList
      .map((ele) => {
        return ele.name;
      })
      .join(',');
    emits('changeNames', userNames);
  }
  function abolishChecked(id: string) {
    data.selectedList = data.selectedList.filter((ele) => {
      return ele.id != id;
    });
    data.selectedIds.splice(
      data.selectedIds.findIndex((itemId) => itemId === id),
      1,
    );
  }

  function handleTypeChange(val) {
    data.isDeptSelect = !!val;
  }
</script>
<style lang="less" scoped>
  .header-box {
    padding: 16px;
    display: flex;
    align-items: center;
    font-size: 14px;
    border-bottom: 1px solid #ddd;

    .required-dot {
      color: #ff4d4f;
      margin-right: 5px;
    }
  }
</style>
