<template>
  <a-modal
    :width="800"
    v-model:visible="visible"
    title="角色用户"
    :keyboard="false"
    :mask-closable="false"
    :closable="false"
    cancel-text="关闭"
    :ok-button-props="{ style: { display: 'none' } }"
  >
    <div class="modal-search">
      <a-form
        ref="formRef"
        name="advanced_search"
        class="ant-advanced-search-form"
        :model="searchParamsState"
      >
        <a-row :gutter="24">
          <a-col :span="10">
            <a-form-item label="帐号" :label-col="{span:10}" name="loginID">
              <a-input v-model:value="searchParamsState.loginID" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="用户名称" :label-col="{span:8}" name="name">
              <a-input v-model:value="searchParamsState.name" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :span="4" style="text-align: left">
            <a-button type="primary" html-type="submit" @click="loadRoleUserList">查询</a-button>
          </a-col>
        </a-row>
        <a-row class="edit-operation">
          <a-col :span="24">
            <a-button type="primary" @click="addRoleUser">新增</a-button>
            <a-button @click="onDelete">删除</a-button>
          </a-col>
        </a-row>
      </a-form>
      <div class="search-result-list">
        <a-table :columns="columns" :data-source="roleUserList" :scroll="{ x: 500, y: 500 }" :pagination="pagination"
                 :loading="formState.loading"
                 @change="handleTableChange"
                 :row-selection="{ selectedRowKeys: formState.selectedRowKeys, onChange: onSelectChange}"
                 :row-key="record=>record.userID"
                 bordered>
        </a-table>
      </div>
    </div>
    <a-modal v-model:visible="visibleUserModal" title="新增角色用户" cancel-text="取消" :width="700"
             @ok="saveRoleUser">
      <a-transfer
        v-model:target-keys="targetKeys"
        :data-source="userList"
        show-search
        :filter-option="(inputValue, item) => (item.name.indexOf(inputValue) !== -1 || item.loginId.indexOf(inputValue) !== -1)"
        :show-select-all="false"
        :list-style="{width: '600px',height: '640px', }"
      >
        <template
          #children="{
          direction,
          filteredItems,
          selectedKeys,
          disabled: listDisabled,
          onItemSelectAll,
          onItemSelect,
        }"
        >
          <a-table
            :scroll="{ x: 300, y: 500 }"
            :row-key="record=>record.userID"
            :row-selection="
            getRowSelection({
              disabled:true,
              selectedKeys,
              onItemSelectAll,
              onItemSelect,
            })
          "
            :columns="direction === 'left' ? leftColumns : rightColumns"
            :data-source="filteredItems"
            size="small"
            :custom-row="
            ({ key }) => ({
              onClick: () => {
                onItemSelect(key, !selectedKeys.includes(key));
              },
            })
          "
            :pagination="false"
          />
        </template>
      </a-transfer>
    </a-modal>
  </a-modal>
</template>
<script lang="ts">
import {computed, createVNode, defineComponent, reactive, ref} from "vue";
import type {TableColumnsType, TableProps} from "ant-design-vue";
import type {FormInstance} from 'ant-design-vue';
import {deleteRoleUser, getRoleUserList, getUserForSettingList, saveRoleUserList} from "@/api/system/role/index"
import {message, Modal} from "ant-design-vue";
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";

type tableColumn = Record<string, string>;
const leftTableColumns = [
  {
    dataIndex: 'name',
    title: '用户名',
  },
  {
    dataIndex: 'loginId',
    title: '帐号',
  },
];
const rightTableColumns = [
  {
    dataIndex: 'name',
    title: '用户名',
  },
  {
    dataIndex: 'loginId',
    title: '帐号',
  }
];

export default defineComponent({
  props: {
    loadData: {
      type: Function,
      default: null
    }
  },
  setup() {
    const roleUserList = ref([]);
    const userList = ref([]);
    const visible = ref<boolean>(false);
    const visibleUserModal = ref<boolean>(false);
    const confirmLoading = ref<boolean>(false);
    const searchParamsState = reactive({
      page: 1,
      rows: 20,
      loginID: '',
      name: '',
      roleID: ''
    });
    const userTypeID = ref<number>();
    const modalFormRef = ref<FormInstance>();
    const columns: TableColumnsType = [
      {
        title: '序号',
        align: 'center',
        width: 60,
        key: 'userID',
        customRender: item => `${searchParamsState.rows * (searchParamsState.page - 1) + item.index + 1}`
      },
      {title: '帐号', dataIndex: 'loginID', key: 'loginID', width: 150},
      {title: '用户名称', width: 150, dataIndex: 'name', key: 'name',},
    ];
    const formState = reactive({
      total: 0,
      selectedRowKeys: [],
      loading: false
    });
    const pagination = computed(() => ({
      total: formState.total,
      current: searchParamsState.page,
      pageSize: searchParamsState.rows,
      showSizeChanger: true
    }));
    const targetKeys = ref<string[]>();
    const leftColumns = ref<tableColumn[]>(leftTableColumns);
    const rightColumns = ref<tableColumn[]>(rightTableColumns);
    const getRowSelection = ({
                               selectedKeys,
                               onItemSelectAll,
                               onItemSelect,
                             }: Record<string, any>) => {
      return {
        onSelectAll(selected: boolean, selectedRows: any[]) {
          const treeSelectedKeys = selectedRows.map((record) => record.userID);
          onItemSelectAll(treeSelectedKeys, selected);
         /* console.log("当前选择的用户id集合",targetKeys.value);
          console.log("selectedKeys",selectedKeys);*/
        },
        onSelect(record: any, selected: boolean) {
          onItemSelect(record.userID, selected);
          /*console.log("当前userList",userList.value);
          console.log("当前选择的用户id集合",targetKeys.value);
          console.log("selectedKeys",selectedKeys);*/
        },
        selectedRowKeys: selectedKeys,
      };
    };


    const onSelectChange = (selectedRowKeys: any) => {
      formState.selectedRowKeys = selectedRowKeys;
    };
    const getUserList = () => {
      getUserForSettingList({userType: userTypeID.value, roleID: searchParamsState.roleID}).then((result: any) => {
        userList.value = result;
      });
    };
    const handleTableChange: TableProps['onChange'] = (
      pag: { pageSize: number; current: number }
    ) => {
      searchParamsState.page = pag.current
      loadRoleUserList();
    };

    const saveRoleUser = () => {
      saveRoleUserList(searchParamsState.roleID, targetKeys.value).then(() => {
        visibleUserModal.value = false;
        loadRoleUserList();
      });

    }

    const show = (roleID, userType) => {
      searchParamsState.roleID = roleID;
      userTypeID.value = userType;
      searchParamsState.loginID ='';
      searchParamsState.name ='';
      formState.selectedRowKeys = [];
      formState.total = 0;
      loadRoleUserList();
      visible.value = true;
    };

    const handleCancel = () => {
      visible.value = false;
    };

    const onDelete = () => {
      if (formState.selectedRowKeys.length <= 0) {
        message.warning('请选择需要删除的数据！');
        return false;
      }

      Modal.confirm({
        title: '确认删除选中角色用户?',
        icon: createVNode(ExclamationCircleOutlined),
        content: '',
        okText: '确认删除',
        okType: 'danger',
        okButtonProps: {},
        cancelText: '取消',
        onOk() {
          deleteRoleUser(searchParamsState.roleID, formState.selectedRowKeys).then(() => {
            loadRoleUserList();
          });
        },
        onCancel() {

        },
      });

    }

    const addRoleUser = () => {
      visibleUserModal.value = true;
      targetKeys.value = [];
      getUserList();
    }


    const loadRoleUserList = async function () {
      formState.loading = true;
      const result: any = await getRoleUserList(searchParamsState);
      roleUserList.value = result.list;
      formState.total = result.total;
      formState.loading = false;
    }



    return {
      visible,
      confirmLoading,
      modalFormRef,
      searchParamsState,
      columns,
      pagination,
      roleUserList,
      show,
      handleCancel,
      handleTableChange,
      onSelectChange,
      formState,
      onDelete,
      visibleUserModal,
      addRoleUser,
      saveRoleUser,
      userList,
      targetKeys,
      leftColumns,
      rightColumns,
      getRowSelection,
      loadRoleUserList
    };
  },
  created() {

  },
})
</script>

