<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :width="1000"
    title="新增组织"
    :fixedHeight="true"
    @ok="handleSubmit"
  >
    <a-tabs
      v-model:activeKey="activeKey"
      @change="handleTabChange"
      :tabBarStyle="{
        height: '50px',
        margin: '0 16px 10px',
        justifyContent: 'space-between',
      }"
    >
      <a-tab-pane key="1" tab="全部">
        <BasicTable @register="registerTableAll" />
      </a-tab-pane>
      <a-tab-pane key="2" tab="已选" force-render>
        <BasicTable @register="registerTableSelected" />
      </a-tab-pane>
      <template #rightExtra>
        <div class="left-extra">
          <span class="left-text">已选中{{ num }}条</span>
          <span style="height: 24px; border-left: 1px solid #ddd; margin: 0 16px 0 10px"></span>
          <a-input
            class="right-input"
            v-model:value="searchText"
            placeholder="请输入关键字"
            @keypress.enter="handleSearch"
          />

          <a-button
            @click="
              () => {
                searchText = '';
                handleSearch();
              }
            "
            class="!rounded ml-4"
          >
            重置
          </a-button>
          <a-button type="primary" @click="handleSearch" class="!rounded ml-4"> 搜索 </a-button>
        </div>
        <a-button type="primary" danger @click="handleClear" class="!rounded mx-4"> 清空 </a-button>
      </template>
    </a-tabs>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, useTable, BasicColumn } from '/@/components/Table';
  import { getDepartmentEnabledTree } from '/@/api/system/department';
  import { useI18n } from '/@/hooks/web/useI18n';

  import { cloneDeep } from 'lodash-es';
  const { t } = useI18n();
  const columns: BasicColumn[] = [
    {
      title: t('组织名称'),
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: t('组织编码'),
      dataIndex: 'code',
      align: 'center',
    },
  ];

  const activeKey = ref('1');
  const selectedList = ref<any[]>([]);
  const num = ref(0);
  const searchText = ref('');

  const emits = defineEmits(['success']);
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    setSelectedRowKeys1(data.orgs?.map((x) => x.id) || []);
    reload();
  });

  const [
    registerTableAll,
    {
      getSelectRows,
      setSelectedRowKeys: setSelectedRowKeys1,
      getSelectRowKeys: getSelectRowKeys1,
      reload,
    },
  ] = useTable({
    api: getDepartmentEnabledTree,
    rowKey: 'id',
    columns,
    beforeFetch: (params) => {
      return { ...params, name: searchText.value };
    },
    showIndexColumn: false,
    rowSelection: {
      type: 'checkbox',
      onChange: (val) => {
        num.value = val.length;
      },
    },
    striped: false,
  });

  const [
    registerTableSelected,
    {
      setTableData,
      getDataSource,
      setSelectedRowKeys: setSelectedRowKeys2,
      getSelectRowKeys: getSelectRowKeys2,
    },
  ] = useTable({
    dataSource: selectedList.value,
    rowKey: 'id',
    columns,
    rowSelection: {
      type: 'checkbox',
      onChange: (val) => {
        num.value = val.length;
      },
    },
    striped: false,
    pagination: {
      hideOnSinglePage: true,
    },
  });

  const handleTabChange = (key) => {
    if (key === '2') {
      setSelectedRowKeys2(cloneDeep(getSelectRowKeys1()));
      selectedList.value = cloneDeep(getSelectRows());
      selectedList.value.map((x) => {
        delete x.children;
      });
      setTableData(selectedList.value);
    } else {
      const dataSourceKeys = getDataSource().map((x) => x.id);
      const selected = selectedList.value.filter((x) => {
        return (
          !dataSourceKeys.includes(x.id) ||
          (dataSourceKeys.includes(x.id) && getSelectRowKeys2().includes(x.id))
        );
      });
      const selectedKeys = selected.map((x) => x.id);
      setSelectedRowKeys1(selectedKeys);
    }
  };

  const handleSearch = () => {
    if (activeKey.value === '1') {
      reload();
    } else {
      const data = selectedList.value.filter(
        (x) => x.name.includes(searchText.value) || x.code.includes(searchText.value),
      );
      setTableData(data);
    }
  };
  const handleClear = () => {
    setSelectedRowKeys1([]);
    setSelectedRowKeys2([]);
    setTableData([]);
  };
  const handleSubmit = () => {
    getSelectRows().map((x) => {
      delete x.children;
    });
    emits('success', getSelectRows());
    closeModal();
  };
</script>
<style lang="less" scoped>
  .ant-tabs {
    height: 100%;
  }

  :deep(.ant-tabs-content-holder) {
    height: calc(100% - 60px);

    .ant-tabs-content {
      height: 100%;
    }
  }

  :deep(.vben-basic-table .ant-table) {
    padding: 0 16px;
  }

  :deep(.vben-basic-table .ant-table-container) {
    height: 100%;
  }

  :deep(.ant-tabs-extra-content) {
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .left-extra {
      display: flex;
      align-items: center;

      .left-text {
        width: 80px;
        height: 24px;
        background: rgb(28 141 255 / 8%);
        border-radius: 4px;
        border: 1px solid @primary-color;
        font-size: 12px;
        color: @primary-color;
        line-height: 24px;
        text-align: center;
      }
    }
  }

  :deep(.ant-input.right-input) {
    width: 180px;
    height: 32px;
    background: #fff;
    border-radius: 4px;
    border: 1px solid #ddd;
  }
</style>
