<template>
  <a-modal
    :width="props.width"
    :visible="props.visible"
    :confirm-loading="loading"
    :body-style="{ paddingBottom: '8px', height: 'calc(100vh - 400px)', overflowY: 'auto', minHeight: '700px' }"
    @ok="save"
    :title="title"
    @cancel="updateVisible(false)"
    :footer="footer"
    :maskClosable="false"
    wrapClassName="selection-modal"
    v-if="visible"
  >
    <div class="box">
      <a-row class="user-select" :gutter="16">
        <!-- 公司部门选择 -->
        <a-col :xs='24' :sm='24' :md='6' class="height100">
          <OrgUserSelectTree @treeSelect="treeSelect" @checkedTree="checkedTree" ref="OrgUserSelectTreeRef"></OrgUserSelectTree>
        </a-col>
        <!-- 人员表格 -->
        <a-col :xs='24' :sm='24' :md='12' class="height100">
          <a-card :bordered="false" style="height: 100%">
            <!-- 搜索 -->
            <div class="search">
              <a-input v-model:value="where.searchText" placeholder="姓名、账号（回车搜索）" @pressEnter="reload" style="width: 300px">
                <template #suffix>
                  <icon-font iconClass="icon-opt-search"></icon-font>
                </template>
              </a-input>
            </div>
            <div class="user-table">
              <common-table
                :columns="columns"
                :where="where"
                bordered
                isShowRowSelect
                rowId="userId"
                ref="tableRef"
                url="/sysUser/page"
                :customData="customData"
                @onSelect="onSelect"
                @onSelectAll="onSelectAll"
                @tableListChange="list => tableListChange(list)"
              >
                <template #bodyCell="{ column, record }">
                  <!-- 公司 -->
                  <template v-if="column.dataIndex == 'company'">
                    {{ record?.userOrgDTO?.companyName ? record?.userOrgDTO?.companyName : '' }}
                  </template>
                  <!-- 部门 -->
                  <template v-if="column.dataIndex == 'dept'">
                    {{ record?.userOrgDTO?.deptName ? record?.userOrgDTO?.deptName : '' }}
                  </template>
                  <!-- 职务 -->
                  <template v-if="column.dataIndex == 'positionName'">
                    {{ record?.userOrgDTO?.positionName ? record?.userOrgDTO?.positionName : '' }}
                  </template>
                  <!-- 性别 -->
                  <template v-if="column.dataIndex == 'sex'">
                    <span v-if="record.sex == 'M'">男</span>
                    <span v-if="record.sex == 'F'">女</span>
                  </template>
                  <!-- 状态 -->
                  <template v-if="column.dataIndex == 'statusFlag'">
                    <span v-if="record.statusFlag == 1">启用</span>
                    <span v-if="record.statusFlag == 2">禁用</span>
                  </template>
                </template>
              </common-table>
            </div>
          </a-card>
        </a-col>
        <!-- 已选列表 -->
        <a-col :xs='24' :sm='24' :md='6' class="height100">
          <OrgUserSelectList v-model:list="orgUserList" @delete="deleteItem" @deleteAll="deleteAll" />
        </a-col>
      </a-row>
    </div>
  </a-modal>
</template>

<script setup name="OrgUserSelect">
import { deepClone } from '@/utils/common/util';
import { onMounted, ref, nextTick } from 'vue';
import OrgUserSelectTree from './components/org-user-tree.vue';
import OrgUserSelectList from './components/selecteds-list.vue';

const props = defineProps({
  // 宽度
  width: {
    type: String,
    default: '60%'
  },
  // 弹框状态
  visible: Boolean,
  // 弹框标题
  title: {
    type: String,
    default: '标题'
  },
  //底部内容取消显示
  footer: {
    type: String,
    default: undefined
  },
  // 选中列表
  list: {
    type: Array,
    default: []
  }
});

const emits = defineEmits(['update:visible', 'done']);

// 弹框加载状态
const loading = ref(false);
// 搜索条件
const where = ref({
  searchText: '',
  orgIdCondition: ''
});

// 选中列表
const orgUserList = ref([]);

// ref
const tableRef = ref(null);
const OrgUserSelectTreeRef = ref(null);
// 表格配置
const columns = ref([
  {
    dataIndex: 'realName',
    title: '姓名',
    align: 'center',
    width: 100,
    isShow: true
  },
  {
    dataIndex: 'company',
    title: '公司',
    align: 'center',
    width: 100,
    isShow: true
  },
  {
    dataIndex: 'dept',
    title: '部门',
    align: 'center',
    width: 100,
    isShow: true
  },
  {
    dataIndex: 'positionName',
    title: '职务',
    align: 'center',
    width: 100,
    isShow: true
  }
]);

onMounted(() => {
  orgUserList.value = deepClone(props.list);
  let orgList = [];
  let userList = [];
  orgUserList.value.forEach(item => {
    if (item.type == '3') {
      userList.push(item.id);
    } else {
      orgList.push(item.id);
    }
  });
  nextTick(() => {
    OrgUserSelectTreeRef.value.checkedKeyss = orgList;
    tableRef.value.selectedRowList = userList;
  });
});

// 左侧树选中
const treeSelect = (selectedKeys, metadata) => {
  where.value.orgIdCondition = selectedKeys[0];
  reload();
};

// 自定义人员数据
const customData = res => {
  res.data.rows.forEach(item => {
    item.id = item.userId;
    item.name = item.realName;
    item.type = '3';
  });
  return res;
};

// 重新查询
const reload = () => {
  tableRef.value.reload();
};

// 树选择
const checkedTree = (checked, node) => {
  // 选中状态
  if (checked) {
    if (!orgUserList.value.find(item => item.type == node.orgType && item.id == node.id)) {
      orgUserList.value.push(node);
    }
  } else {
    // 取消选中状态
    deleteItem(node);
  }
};

// 选中或取消选中某一列
const onSelect = (record, selected, selectedRows) => {
  if (selected) {
    if (!orgUserList.value.find(userItem => userItem.id == record.id && userItem.type == record.type)) {
      orgUserList.value.push(record);
    }
  } else {
    deleteItem(record);
  }
};

// 全选反选
const onSelectAll = (selected, selectedRows, changeRows) => {
  if (selected) {
    // 全选时遍历选中的数组，加入已选列表
    changeRows.forEach(item => {
      if (!orgUserList.value.find(userItem => userItem.id == item.id && userItem.type == '3')) {
        orgUserList.value.push(item);
      }
    });
  } else {
    // 反选时删除当前页的全部数据
    changeRows.forEach(item => {
      for (let i = orgUserList.value.length - 1; i >= 0; i--) {
        if (item.id == orgUserList.value[i].id) {
          orgUserList.value.splice(i, 1);
        }
      }
    });
  }
};

// 表格数据变化
const tableListChange = list => {
  if (tableRef.value?.selectedRowList) {
    let selectedRowKeys = [];
    if (list && list.length > 0) {
      list.forEach(listItem => {
        if (orgUserList.value.find(item => item.id == listItem.id && item.type == '3')) {
          selectedRowKeys.push(listItem.id);
        }
      });
    }
    tableRef.value.selectedRowList = selectedRowKeys;
  }
};

// 刪除已选单个
const deleteItem = record => {
  orgUserList.value.splice(
    orgUserList.value.findIndex(item => item.type == record.type && item.id === record.id),
    1
  );
  if (record.type != '3') {
    if (OrgUserSelectTreeRef.value.checkedKeyss.checked.find(item => item == record.id)) {
      OrgUserSelectTreeRef.value.checkedKeyss.checked.splice(
        OrgUserSelectTreeRef.value.checkedKeyss.checked.findIndex(item => item === record.id),
        1
      );
    }
  } else {
    let list = orgUserList.value.filter(item => item.type == '3');
    tableListChange(list);
  }
};

// 删除全部已选
const deleteAll = () => {
  orgUserList.value = [];
  OrgUserSelectTreeRef.value.checkedKeyss.checked = [];
  tableListChange([]);
};

// 关闭弹框
const updateVisible = value => {
  emits('update:visible', value);
};

// 保存
const save = () => {
  loading.value = true;

  loading.value = false;
  // 关闭弹框
  updateVisible(false);
  emits('done', orgUserList.value);
};
</script>

<style scoped lang="less">
.box {
  width: 100%;
  height: 100%;
}
.user-select {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
:deep(.ant-card-body) {
  padding: 0;
  height: 100%;
}
.search {
  height: 40px;
  line-height: 40px;
}
.user-table {
  height: calc(100% - 50px);
  padding: 10px 0;
}
</style>
<style lang="less">
@media screen and (max-width: 768px) {
  .selection-modal {
    .ant-modal {
      width: 100% !important;
      top: 20px;
    }
    .user-select {
      overflow-y: auto;
    }
  }
}
</style>
