<template>
    <div style="padding:10px">
        <q-card inline class="fit shadow-6">
            <div>
            </div>
            <q-card-main style="height:80%">
                <q-table ref="table" color="primary" :data="serverData" :columns="columns" separator="cell" selection="none" row-key="id" :rows-per-page-options="[5,10,20,30,40,50,60,200,500]" :pagination.sync="serverPagination"
                        @request="request" :loading="loading" :rows-per-page-label="$t('Rows per page')" :no-data-label="$t('No data')">
                    <template slot="top-left" slot-scope="props">
                        <q-input v-model="filter.namezh" type="text" :prefix="$t('Role name') + '：'" />&nbsp;&nbsp;
                        <q-input v-model="filter.name" type="text" :prefix="$t('Role code') + '：'" />&nbsp;&nbsp;
                        <q-btn push dense color="primary" icon="search" @click="search">{{$t('Search')}}</q-btn>&nbsp;&nbsp;
                    </template>
                    <template slot="top-right" slot-scope="props">
                        <q-btn flat round dense :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'" @click="props.toggleFullscreen" />
                    </template>
                    <q-td slot="body-cell-id" slot-scope="props" :props="props" style="width:150px">
                        <q-btn glossy color="secondary" :label="$t('User list')" @click="editRoleUser(props)"></q-btn>
                    </q-td>
                </q-table>
            </q-card-main>
        </q-card>
        <q-modal v-model="editModal" maximized>
          <q-modal-layout>
                <q-toolbar slot="header">
                    <q-btn flat round dense @click="closeEditModal" icon="reply" />
                    <q-toolbar-title>
                      {{$t('Editing role')}}&nbsp;
                        <q-chip small>{{roleName}}</q-chip>&nbsp;{{$t('User under')}}
                    </q-toolbar-title>
                </q-toolbar>
                <q-toolbar slot="footer">
                    <q-toolbar-title>
                    </q-toolbar-title>
                    <q-btn round   color="red"  @click="modifyRoleUser">{{$t('Save')}}</q-btn>
                    <q-btn round @click="closeEditModal">{{$t('Cancel')}}</q-btn>
                </q-toolbar>
              <!-- 选择个人 -->
              <div class=" row q-mb-lg q-ml-lg q-mr-lg" >
                  <div class="col-2 q-ml-lg" style="height:80vh;overflow:auto;">
                  </div>
                  <div class="col-4 q-mt-lg" style="height:80vh;overflow:auto;">
                      <organizationDeptPanel :value="orgList" @change="onOrgListChange" />
                  </div>
                  <div class="col-4 q-mt-lg" style="height:80vh;overflow:auto;" ref="staffListEl" @scroll="onStaffScroll">
                      <div class="q-mb-md">
                          <q-input
                              v-model="selectedSearchText"
                              clearable
                              outlined
                              dense
                              placeholder="搜索已选成员..."
                          >
                              <template v-slot:prepend>
                                  <q-icon name="search" />
                              </template>
                          </q-input>
                          <div class="q-mt-xs text-grey-6" style="font-size:12px;">
                              共 {{ filteredStaff.length }} 人{{ selectedSearchText ? '（已过滤）' : '' }}
                          </div>
                      </div>

                      <div v-if="visibleStaff.length > 0">
                          <div class="row shadow-1 q-mb-xs" v-for="node in visibleStaff" :key="node.key">
                              <div class="col" style="display:flex;align-items:center;">
                                  <q-icon name="person" size="16px" />
                                  <div>
                                      {{ ' ' + node.title }}
                                      <span style="color:#64b5fe">{{ node.no ? ' ' + node.no : '' }}</span>
                                  </div>
                              </div>
                              <div class="col" style="display:flex;align-items:center;justify-content:flex-end;">
                                  <q-btn flat color="primary" icon="clear" @click="deleteNode(node)" />
                              </div>
                          </div>
                      </div>

                      <div v-if="staffLoading" class="text-center q-pa-sm text-grey-6">
                          加载中...
                      </div>

                      <div v-else-if="!selectedSearchText && filteredStaff.length === 0" class="text-grey-5 q-mt-md">
                          没有选择任何成员
                      </div>
                      <div v-else-if="selectedSearchText && filteredStaff.length === 0" class="text-grey-5 q-mt-md">
                          没有匹配的成员
                      </div>
                  </div>
              </div>
            </q-modal-layout> 
        </q-modal>
    </div>
</template>
<script>
import { getRolePagedList } from "@/service/permission/role";
import { getUserRoleList, editRoleUser, editUserRoleList, listByIds} from "@/service/user/user";
import organizationDeptPanel from '@/components/organization-dept-panel'
export default {
  components: { organizationDeptPanel},
  // name: "roleuser",
  data() {
    return {
      orgList:[],//选中的树节点
      selectStaff:[],//选中的人
      selectedSearchText: '', // 右侧已选列表搜索
      visibleStaff: [], // 当前可见的已选成员（分页）
      staffPageSize: 50,   // 每页加载条数
      staffPage: 1,       // 当前页
      staffLoading: false, // 加载中
      staffListEl: null, // 滚动容器 ref
      treeKey:[],
      resdata:[],
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      namefilter:"",
      leaderSelected: [],
      leaderList: [],
      tempFunction:{
          contactList:[{}],
      },
      serverData: [],
      serverPagination: {
        page: 1,
        rowsNumber: 0, // specifying this determines pagination is server-side
        rowsPerPage: 10 // current rows per page being displayed
      },
      columns: [
        {
          name: "namezh",
          required: true,
          label: this.$t("Role name"),
          align: "left",
          field: "namezh",
          sortable: true
        },
        {
          name: "name",
          label: this.$t("Role code"),
          field: "name",
          sortable: true,
          align: "left",
        },
        {
          name: "id",
          required: true,
          label: this.$t("ID"),
          align: "left",
          field: "id"
        }
      ],
      filter: {
        name: "",
        namezh: ""
      },
      loading: false,
      editModal: false,
      roleId: 0,
      roleName: "",
      roleUser: {
        serverData: [],
        serverPagination: {
          page: 1,
          rowsNumber: 0, // specifying this determines pagination is server-side
          rowsPerPage: 10 // current rows per page being displayed
        },
        columns: [
                  {
          name: "username",
          required: true,
          label: this.$t("Name"),
          align: "left",
          field: "username",
          sortable: true
        },
        {
          name: "account",
          label: this.$t("Account"),
          field: "account",
          sortable: true,
          align: "left"
        },
        {
          name: "email",
          label: this.$t("Email"),
          field: "email",
          sortable: true,
          align: "left"
        },
        {
          name: "phoneNumber",
          label: this.$t("Phone"),
          field: "phoneNumber",
          sortable: true,
          align: "left"
        },
        {
          name: "position",
          required: true,
          label: this.$t("Position"),
          align: "left",
          field: "position"
        },
        {
          name: "id",
          required: true,
          label: this.$t("ID"),
          align: "left",
          field: "id"
        }
        ],
        filter: {
          account: "",
          username: "",
          roleId: ""
        },
        loading: false
      }
    };
  },
  computed: {
    filteredStaff() {
      if (!this.selectedSearchText) return this.selectStaff;
      const kw = this.selectedSearchText.toLowerCase();
      return this.selectStaff.filter(s =>
        (s.title || '').toLowerCase().includes(kw) ||
        (s.no || '').toLowerCase().includes(kw)
      );
    }
  },
  watch: {
    filteredStaff() {
      this.staffPage = 1;
      this.visibleStaff = this.filteredStaff.slice(0, this.staffPageSize);
    }
  },
  methods: {
    onOrgListChange(selectedIds) {//新组件选中后回调
        this.orgList = selectedIds;
        if (selectedIds.length > 0) {
            listByIds(selectedIds).then(res => {
                let users = res.data.data || [];
                this.selectStaff = users.map(u => ({
                    key: u.id,
                    title: u.title || u.label || '',
                    no: u.no || ''
                }));
                this.visibleStaff = this.selectStaff.slice(0, this.staffPageSize);
                this.staffPage = 1;
            });
        } else {
            this.selectStaff = [];
            this.visibleStaff = [];
            this.staffPage = 1;
        }
    },
    // checkStaffNode(nodeList){//组织机构树人员选择后组件的回调方法-返回选中的node
    //     this.selectStaff = nodeList
    // },
    // checkStaffKey(keyList){//组织机构树人员选择后组件的回调方法-返回key
    //     this.selectStaff = keyList
    // },
    //  删除节点事件
    deleteNode(node) {
      if (!node) {
        return false;
      }
      var staff = this.selectStaff.filter(staff => staff.key !== node.key);
      this.selectStaff = staff;
      this.orgList = this.selectStaff.map(item=>item.key);
      this.visibleStaff = this.filteredStaff.slice(0, this.staffPage * this.staffPageSize);
    },
    onStaffScroll(e) {
      const el = e.target;
      if (el.scrollHeight - el.scrollTop - el.clientHeight < 50) {
        this.loadMoreStaff();
      }
    },
    loadMoreStaff() {
      if (this.staffLoading) return;
      const total = this.filteredStaff.length;
      const next = (this.staffPage + 1) * this.staffPageSize;
      if (next >= total) {
        this.visibleStaff = this.filteredStaff;
        this.staffLoading = false;
      } else {
        this.staffLoading = true;
        setTimeout(() => {
          this.staffPage++;
          this.visibleStaff = this.filteredStaff.slice(0, this.staffPage * this.staffPageSize);
          this.staffLoading = false;
        }, 100);
      }
    },
    async request(props) {
      this.loading = true;
      this.serverPagination = props.pagination;
      let table = this.$refs.table,
        { page, rowsPerPage, sortBy, descending } = props.pagination;
      let query = {
        pageNum:  page,
        pageSize: rowsPerPage,
        sortBy: sortBy,
        descending: descending,
        name: this.filter.name,
        namezh: this.filter.namezh
      };
      let dataRes = await getRolePagedList(query);
      let data = dataRes.data.data;
      this.serverPagination.rowsNumber = data.total;
      this.serverData = data.list;
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    async editRoleUser(props) {
      this.roleId = props.value;
      this.roleName = props.row.namezh;
      this.editModal = true;
      let query = { role: this.roleId };
      let dataRes = await getUserRoleList(query);
      let data = dataRes.data.data;
      this.orgList = data || [];
      if (this.orgList.length > 0) {
        let idsRes = await listByIds(this.orgList);
        let users = idsRes.data.data || [];
        this.selectStaff = users.map(u => ({
          key: u.id,
          title: u.title || u.label || '',
          no: u.no || ''
        }));
        this.visibleStaff = this.selectStaff.slice(0, this.staffPageSize);
        this.staffPage = 1;
      } else {
        this.selectStaff = [];
      }
    },
    closeEditModal(){//关闭弹层，清空树
      this.editModal=false
      this.orgList = []
      this.selectStaff = []
      this.visibleStaff = []
      this.staffPage = 1
      this.selectedSearchText = ''
    },
    search() {
      this.request({
        pagination: this.serverPagination,
        filter: this.filter
      });
    },
    searchRoleUser() {
      this.roleUserRequest({
        pagination: this.roleUser.serverPagination,
        filter: this.roleUser.filter
      });
    },
    async modifyRoleUser() {
      //保存用户角色信息，并刷新角色用户列表
      let userIds = this.selectStaff.map(item=>item.key).join(",")
      let res = await editUserRoleList({
          roleId: this.roleId,
          userIds: userIds
        });

      this.closeEditModal()
      this.$q.notify({
        type: "positive",
        message: this.$t("Added successfully"),
        position: "bottom-right"
      });
      this.request({
        pagination: this.serverPagination,
        filter: this.filter
      });
    }
  },
  mounted() {
    this.request({
      pagination: this.serverPagination,
      filter: this.filter
    });
  }
};
</script>
