<template>
  <div :style="{ width: width }" @click="show" :key="Math.random().toString(36).slice(-8)">
    <slot></slot>

    <ModalPanel
      :visible="data.visible"
      :width="1200"
      :title="t('添加人员')"
      @submit="submit"
      @close="close"
    >
      <template #left v-if="!isSetTransferUser">
        <OrganizationalTree @select="handleSelect" />
      </template>
      <div class="relative h-full">
        <!-- 已选 -->
        <Selected
          v-if="data.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="data.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
              @change="getList"
          /></div>
        </div>
        <EmptyBox v-if="data.list.length == 0" />
      </div>
    </ModalPanel>
  </div>
</template>

<script setup lang="ts">
  import { computed, onMounted, reactive } from 'vue';
  import OrganizationalTree from './OrganizationalTree.vue';
  import UserCard from './card/UserCard.vue';
  import Selected from './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';
  import { getTransferUser } from '/@/api/workflow/task';
  const { t } = useI18n();
  const emits = defineEmits(['change', 'changeNames', 'close']);
  const props = withDefaults(
    defineProps<{
      selectedIds: Array<string> | string;
      disabledIds?: Array<string>;
      multiple?: Boolean;
      visible?: Boolean;
      disabled?: Boolean;
      isShow?: Boolean;
      width?: string;
      isSetTransferUser?: Boolean;
      taskId?: string;
    }>(),
    {
      selectedIds: () => {
        return [];
      },
      disabledIds: () => {
        return [];
      },
      disabled: () => {
        return false;
      },
      width: () => {
        return '100%';
      },
    },
  );
  let data: {
    visible: boolean;
    multiSelect: boolean;
    page: { current: number; total: number; pageSize: number };
    list: Array<UserInfo>;
    selectedList: Array<UserInfo>;
    selectedIds: Array<string>;
    searchConfig: {
      keyword: string;
      deptId: string;
    };
  } = reactive({
    visible: false,
    multiSelect: false,
    page: {
      current: 1,
      total: 0,
      pageSize: 9,
    },
    selectedIds: [],
    list: [],
    selectedList: [],
    searchConfig: {
      keyword: '',
      deptId: '',
    },
  });

  const paramRef = computed(() => {
    let obj: any = {
      limit: data.page.current,
      size: data.page.pageSize,
      keyword: data.searchConfig.keyword,
    };
    if (props.isSetTransferUser) {
      obj.taskId = props.taskId;
    } else {
      obj.departmentId = data.searchConfig.deptId;
    }
    return obj;
  });

  onMounted(() => {
    if (props.selectedIds) {
      data.selectedIds = Array.isArray(props.selectedIds)
        ? cloneDeep(props.selectedIds)
        : props.selectedIds.split(',');
      getSelectedList();
    }
    if (props.isShow) show();
  });

  async function show() {
    if (props.disabled) return;
    data.selectedIds = [];
    data.selectedList = [];
    data.page.current = 1;
    data.page.total = 0;
    data.searchConfig.deptId = '';
    if (props.selectedIds) {
      data.selectedIds = Array.isArray(props.selectedIds)
        ? cloneDeep(props.selectedIds)
        : props.selectedIds.split(',');
    }
    if ((props.visible !== undefined && props.visible) || props.visible === undefined) {
      await getList();
      await getSelectedList();
      data.visible = true;
    } else {
      data.visible = false;
    }
  }
  function submit() {
    emits('change', data.selectedIds, data.selectedList);
    changeSelectedNames();
    close();
  }
  function close() {
    data.list = [];
    data.selectedIds = [];
    data.selectedList = [];
    data.visible = false;
    emits('close');
  }
  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];
        data.selectedList = [item];
      }
    }
  }

  async function getList() {
    data.list = [];
    data.page.total = 0;
    // let params = {
    //   limit: data.page.current,
    //   size: data.page.pageSize,
    //   departmentId: data.searchConfig.deptId,
    //   keyword: data.searchConfig.keyword,
    // };

    let res = props.isSetTransferUser
      ? await getTransferUser(paramRef.value)
      : 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, //性别
          mobile: ele.mobile, //联系电话
          email: ele.email, //邮箱
        };
        data.list.push(item);
      });
    }
  }
  function search(keyword: string) {
    data.page.current = 1;
    data.searchConfig.keyword = keyword;
    console.log('search');
    getList();
  }
  function handleSelect(deptId = '') {
    data.page.current = 1;
    data.searchConfig.deptId = deptId;
    console.log('handleSelect');
    getList();
  }

  // async function pageChange(pagination) {
  //   data.page.current = pagination.current;
  //   console.log('data.page', data.page, pagination);
  //   await getList();
  // }

  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, //性别
          mobile: ele.mobile, //联系电话
          email: ele.email, //邮箱
        });
      });
      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,
    );
  }
</script>
