<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :width="800"
    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">
          <template #action="{ record }">
            <a-button type="link" danger @click="handleDelete(record.id)">删除</a-button>
          </template>
        </BasicTable>
      </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, PaginationProps } from '/@/components/Table';
  import { getRoleAllList } from '/@/api/system/role';
  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 });
    setSelectedRowKeys(data.roles?.map((x) => x.id) || []);
    selectedList.value = cloneDeep(data.roles);
    setTableData(selectedList.value);
    num.value = selectedList.value.length;
    searchText.value = '';
    reload();
  });
  const customRow = (record) => {
    return {
      onClick: () => {
        let selectedRowKeys = [...getSelectRowKeys()];
        if (selectedRowKeys.indexOf(record.id) >= 0) {
          let index = selectedRowKeys.indexOf(record.id);
          selectedRowKeys.splice(index, 1);
          let idx = selectedList.value.findIndex((o) => o.id == record.id);
          selectedList.value.splice(idx, 1);
        } else {
          selectedRowKeys.push(record.id);
          selectedList.value.push(record);
        }
        num.value = selectedList.value.length;
        setSelectedRowKeys(selectedRowKeys);
      },
    };
  };
  const [registerTableAll, { getSelectRowKeys, setSelectedRowKeys, reload }] = useTable({
    api: getRoleAllList,
    rowKey: 'id',
    columns,
    beforeFetch: (params) => {
      return { ...params, keyword: searchText.value };
    },
    customRow,
    rowSelection: {
      type: 'checkbox',
      onChange: (val, selectedRows) => {
        if (!searchText.value) {
          num.value = val.length;
          if (val.length && selectedRows.length) {
            //点击触发单选或全选中

            selectedList.value = selectedRows;
          } else if (val.length == 0 && selectedRows.length == 0) {
            //点击触发全不选中
            selectedList.value = [];
          } else if (val.length && selectedRows.length == 0) {
            //编辑回显时
          }
        }
      },
      onSelect: (record, selected) => {
        if (searchText.value) {
          if (selected) {
            selectedList.value.push(record);
          } else {
            let idx = selectedList.value.findIndex((o) => o.id == record.id);
            if (idx >= 0) selectedList.value.splice(idx, 1);
          }
          num.value = selectedList.value.length;
        }
      },
      onSelectAll: (selected, _, changeRows) => {
        if (searchText.value) {
          if (selected) {
            selectedList.value = selectedList.value.concat(changeRows);
          } else {
            changeRows.forEach((record) => {
              let idx = selectedList.value.findIndex((o) => o.id == record.id);
              if (idx >= 0) selectedList.value.splice(idx, 1);
            });
          }
          num.value = selectedList.value.length;
        }
      },
    },
    striped: false,
  });

  const [registerTableSelected, { setTableData, getPaginationRef, setProps }] = useTable({
    dataSource: selectedList.value,
    rowKey: 'id',
    columns,
    striped: false,
    pagination: {
      hideOnSinglePage: true,
    },
    actionColumn: {
      width: 80,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  function reloadPage(total?) {
    let page = getPaginationRef() as PaginationProps;
    setProps({
      pagination: { total: total >= 0 ? total : num.value, pageSize: page.pageSize },
    });
  }
  const handleTabChange = (key) => {
    if (key === '2') {
      setTableData(selectedList.value);
      reloadPage();
      if (searchText.value) {
        handleSearch();
      }
    } else {
      reload();
      const selectedKeys = selectedList.value.map((x) => x.id);
      setSelectedRowKeys(selectedKeys);
    }
  };

  const handleSearch = () => {
    if (activeKey.value === '1') {
      reload();
      setSelectedRowKeys(selectedList.value.map((x) => x.id));
    } else {
      const data = selectedList.value.filter(
        (x) => x.name.includes(searchText.value) || x.code.includes(searchText.value),
      );
      setTableData(data);
      reloadPage(data.length);
    }
  };
  const handleClear = () => {
    setSelectedRowKeys([]);
    selectedList.value = [];
    setTableData([]);
  };
  const handleSubmit = () => {
    emits('success', selectedList.value);
    closeModal();
  };
  function handleDelete(id) {
    for (let i = 0; i < selectedList.value.length; i++) {
      let idx = selectedList.value.findIndex((x) => x.id == id);
      if (idx >= 0) {
        selectedList.value.splice(idx, 1);
        break;
      }
    }
    num.value = selectedList.value.length;
    setTableData(selectedList.value);
    reloadPage();
  }
</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>
