<template>
  <ych-modal
    :fullscreen="false"
    :visible="visible"
    :title="seletUsesrTitle"
    @ok="handleSubmit"
    @cancel="close"
    :okText="$locale('m.common.button.ok')"
    :cancelText="$locale('m.common.button.close')"
  >
    <a-row :gutter="10" style="background-color: #ececec; padding: 10px; margin: -10px">
      <a-col :md="6" :sm="24">
        <a-card :bordered="false" style="height: calc(100vh - 235px);overflow-y:auto;">
          <!--组织机构-->

          <sys-org-tree @onSelect="onDepSelect" :currentOrgAsRoot="currentOrgAsRoot" :filterAuth="filterAuth" :isResetOrg="isResetOrg" :orgTreeShowDeptAbbr="orgTreeShowDeptAbbr" :deptId="deptId" :customOrgOrderSql="customOrgOrderSql" :customOrgFilterSql="customOrgFilterSql"></sys-org-tree>

          <!--<a-directory-tree
            selectable
            :selectedKeys="selectedDepIds"
            :checkStrictly="true"
            :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
            :treeData="departTree"
            :expandAction="false"
            :expandedKeys.sync="expandedKeys"
            @select="onDepSelect"
          />-->
        </a-card>
      </a-col>
      <a-col :md="getType === 'radio' ? 18 : 12" :sm="24">
        <a-card :bordered="false" style="height: calc(100vh - 235px);overflow-y:auto;">
          {{ $locale('m.system.user.entity.username_realname_workno')}}:
          <a-input-search
            :style="{width:'300px',marginBottom:'15px'}"
            placeholder=""
            v-model="queryParam.keywords"
            @search="onSearch"
          ></a-input-search>
          <a-button @click="searchReset(1)" style="margin-left: 20px" icon="redo">{{ $locale('m.common.button.reset') }}</a-button>
          <!--用户列表-->
          <a-table
            ref="table"
            :scroll="scrollTrigger"
            size="middle"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type: getType}"
            :loading="loading"
            :customRow="clickThenCheck"
            @change="handleTableChange">
          </a-table>
        </a-card>
      </a-col>
      <a-col :md="6" :sm="24" v-if="getType !== 'radio'">
        <ych-selected-user-area :selectionRows="selectionRows" :selectedRowKeys="selectedRowKeys" @change="onSelectChange"></ych-selected-user-area>
      </a-col>
    </a-row>
  </ych-modal>
</template>

<script>

  import SysOrgTree from '../ych-org/SysOrgTree'
  import {filterObj} from '../../../utils/util'
  import { getAction, postAction } from '../../../utils/manage'
  import YchOrg from "../../../utils/api/YchOrg"
  import YchSelectedUserArea from './YchSelectedUserArea'
  import LocleUtil from "../../../utils/LocleUtil";

  export default {
    name: 'YchSelectUserByDeptModal',
    components: {
      SysOrgTree,
      YchSelectedUserArea,
    },
    props: {
      modalWidth: {
        type: Number,
        default: 1000,
      },
      multi: {
        type: Boolean|String,
        default: false,
      },
      userIds: {
        type: String,
      },
      // 自定义返回字段，默认返回 id
      customReturnField: {
        type: String,
        default: 'username'
      },
      currentOrgAsRoot:{
        type:Boolean,
        default:false
      },
      filterAuth:{
        type:Boolean,
        default:false
      },
      isResetOrg:{
        type:Boolean,
        default:false
      },
      title:{
        type: String
      },
      requiredMessage:{
        type:String
      },
      filterUser:{
        type:String
      },
      filterUserMessage:{
        type:String
      },
      orgTreeShowDeptAbbr:{
        type:Boolean,
        default:false
      },
      deptId: String, // 指定了根节点
      customOrgOrderSql: String, // 自定义组织树排序Sql
      customOrgFilterSql: String, // 自定义组织树过滤Sql
    },
    data() {
      return {
        queryParam: {
          keywords: "",
        },
        columns: [
          {
            title: LocleUtil.getLocale('m.system.user.entity.username'),
            align: 'center',
            dataIndex: 'username'
          },
          {
            title: LocleUtil.getLocale('m.system.user.entity.realname'),
            align: 'center',
            dataIndex: 'realname'
          },
          {
            title: LocleUtil.getLocale('m.system.user.other.dept_label'),
            align: 'center',
            dataIndex: 'orgCode'
          },
          {
            title: LocleUtil.getLocale('m.system.user.entity.workNo'),
            align: 'center',
            dataIndex: 'workNo'
          },
          /*{
            title: this.LocleUtil.getLocale('m.system.user.entity.sex'),
            align: 'center',
            dataIndex: 'sex',
            customRender: function (text) {
              if (text === 1) {
                return '男'
              } else if (text === 2) {
                return '女'
              } else {
                return text
              }
            }
          },
          {
            title: '手机',
            align: 'center',
            dataIndex: 'phone'
          },
          */
        ],
        scrollTrigger: {},
        dataSource: [],
        selectedRowKeys: [],
        selectionRows: [],
        selectUserRows: [],
        selectUserIds: [],
        ipagination: {
          current: 1,
          pageSize: 10,
          // pageSizeOptions: ['5', '10', '20', '30'],
          pageSizeOptions: ['10','30','50','100','200'],
          showTotal: (total, range) => {
            return LocleUtil.getLocale('m.common.label.page_total', [range[0], range[1], total])
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        selectedDepIds: [],
        departTree: [],
        visible: false,
        form: this.$form.createForm(this),
        loading: false,
        expandedKeys: [],
        url: {
          queryUserPageList: YchOrg.queryUserPageList,
          queryUserListByDepId: YchOrg.queryUserListByDepId
        }
      }
    },
    computed: {
      // 计算属性的 getter
      getType: function () {
        return this.multi == true || this.multi == 'true' ? 'checkbox' : 'radio';
      },
      seletUsesrTitle:function(){
        return this.title || LocleUtil.getLocale('m.components.title.ychSelectUser')
      }
    },
    watch: {
      userIds: {
        immediate: true,
        handler() {
          this.initUserNames()
        }
      },
      deptId: {
        handler() {
          this.loadData()
        }
      },
    },
    created() {
      // 该方法触发屏幕自适应
      this.resetScreenSize();
      this.loadData()
    },
    methods: {
      $locale(params) {
        return LocleUtil.getLocale(params)
      },
      initUserNames() {
        if (this.userIds) {
          let param = {
            pageNo: 1,
            pageSize: this.userIds.split(',').length
          };
          param[this.customReturnField + "$in"] = this.userIds;
          param['currentOrgAsRoot'] = "false"
          param['filterAuth'] = "false"
          //按照传入的id排序
          param['orderByParamUserIds']='true'
          getAction(this.url.queryUserPageList, param).then((res) => {
            if (res.success) {
              let selectedRowKeys = []
              let selectionRows = []
              let realNames = []
              res.result.records.forEach(user => {
                realNames.push(user['realname'])
                selectedRowKeys.push(user['id'])
                selectionRows.push(user)
              })
              this.selectedRowKeys = selectedRowKeys
              this.selectionRows = selectionRows
              this.$emit('initComp', realNames.join(','))
            }
          })
        } else {
          // JSelectUserByDep组件bug issues/I16634
          this.selectedRowKeys = [];
          this.selectionRows = [];
          this.$emit('initComp', '')
        }
      },
      loadData(arg) {
        if (arg === 1) {
          this.ipagination.current = 1;
        }

        this.loading = true
        let params = this.getQueryParams()//查询条件
        params['currentOrgAsRoot'] = this.currentOrgAsRoot
        params['filterAuth'] = this.filterAuth
        if (this.selectedDepIds && this.selectedDepIds.length > 0) {
          params['deptId'] = this.selectedDepIds[0]
        } else if (this.deptId) {
          params['deptId'] = this.deptId
        }

        let url = this.url.queryUserPageList + "?a=a"
        Object.keys(params).forEach(key => {
          url += ("&" + key + "=" + (params[key] || ''))
        })

        postAction(url, {customOrgOrderSql: this.customOrgOrderSql, customOrgFilterSql: this.customOrgFilterSql}).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.ipagination.total = res.result.total
          }
        }).finally(() => {
          this.loading = false
        })
      },
      // 触发屏幕自适应
      resetScreenSize() {
        let screenWidth = document.body.clientWidth;
        if (screenWidth < 500) {
          this.scrollTrigger = {x: 800};
        } else {
          this.scrollTrigger = {};
        }
      },
      showModal() {
        this.visible = true;
        this.initUserNames()
        this.loadData();
        this.form.resetFields();
      },
      getQueryParams() {
        let param = Object.assign({}, this.queryParam, this.isorter);
        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        return filterObj(param);
      },
      getQueryField() {
        let str = 'id,';
        for (let a = 0; a < this.columns.length; a++) {
          str += ',' + this.columns[a].dataIndex;
        }
        return str;
      },
      searchReset(num) {
        let that = this;
        if (num !== 0) {
          that.queryParam = {};
          that.loadData(1);
        }
        that.selectedRowKeys = [];
        that.selectionRows = [];
        that.selectUserIds = [];
        that.selectedDepIds = [];
      },
      close() {
        this.searchReset(0);
        this.visible = false;
      },
      handleTableChange(pagination, filters, sorter) {
        //TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = 'ascend' === sorter.order ? 'asc' : 'desc';
        }
        this.ipagination = pagination;
        this.loadData();
      },
      clickThenCheck (record) {
        return {
          on: {
            click: () => {
              if (this.getType === 'radio') {
                this.onSelectChange(record.id.split(','), [record])
                this.handleSubmit()
              } else {
                const keys = this.selectedRowKeys.filter(vo => vo !== record.id)
                if (keys.length < this.selectedRowKeys.length) {
                  const rows = this.selectionRows.filter(vo => vo.id !== record.id)
                  this.selectedRowKeys = keys
                  this.selectionRows = rows
                } else {
                  this.selectedRowKeys.push(record.id)
                  this.selectionRows.push(record)
                }
              }
            }
          }
        }
      },
      handleSubmit() {
        const userId = this.selectionRows.map(item => item[this.customReturnField]).join(",");
        if(this.requiredMessage && userId.length<1){
          this.$message.warning(this.requiredMessage)
          return false
        }
        if(this.filterUser){
          let filterUsers = this.selectionRows.filter(item=>item.id==this.filterUser)
          if(filterUsers.length>0){
            this.$message.warning(this.filterUserMessage)
            return false
          }
        }
        this.$emit('ok', this.selectionRows, userId);
        this.searchReset(0)
        this.close();
      },
      // 点击树节点,筛选出对应的用户
      onDepSelect(deptId) {
          this.queryParam.keywords = ""
          this.initQueryUserByDepId([deptId]); // 调用方法根据选选择的id查询用户信息
          if (this.selectedDepIds[0] !== deptId) {
            this.selectedDepIds = [deptId];
          }
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        const aa = this.selectionRows.filter(item => selectedRowKeys.indexOf(item.id) !== -1);
        const bb = aa.map(row => row["id"]);
        const cc = selectionRows.filter(item => bb.indexOf(item.id) === -1);
        this.selectionRows = [...aa, ...cc];
      },
      onSearch() {
        this.loadData(1);
      },
      // 根据选择的id来查询用户信息
      initQueryUserByDepId(selectedDepIds) {
        this.loading = true
        const url = this.url.queryUserListByDepId + "?id=" + selectedDepIds.toString()+"&filterAuth="+this.filterAuth
        postAction(url, {customOrgOrderSql: this.customOrgOrderSql, customOrgFilterSql: this.customOrgFilterSql}).then((res) => {
          if (res.success) {
            this.dataSource = res.result;
            this.ipagination.total = res.result.length;
          }
        }).finally(() => {
          this.loading = false
        })
      },
      modalFormOk() {
        this.loadData();
      }
    }
  }
</script>

<style lang="less" scoped>
  .ant-table-tbody .ant-table-row td {
    padding-top: 10px;
    padding-bottom: 10px;
  }

  #components-layout-demo-custom-trigger .trigger {
    font-size: 18px;
    line-height: 64px;
    padding: 0 24px;
    cursor: pointer;
    transition: color .3s;
  }
</style>
