<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="12">
            <a-form-item label="真实名字">
              <a-input @change="clearSpace" placeholder="请输入真实名字" v-model="queryParam.realname"></a-input>
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="8">
            <a-form-item label="工号">
              <a-input @change="clearSpaces" placeholder="请输入工号查询" v-model="queryParam.workNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
              <a-form-item label="部门名称">
                <a-input @click="openModal" placeholder="请点击选择部门" v-model="departNames" readOnly >
                  <a-icon slot="prefix" type="cluster" title="部门选择控件"/>
                  <a-icon v-if="queryParam.orgCodeTxt!=null&&queryParam.orgCodeTxt!=''" slot="suffix" type="close-circle" @click="handleEmpty" title="清空"/>
                </a-input>
                <!-- <j-select-depart v-model="queryParam.orgCodeTxt"/> -->
                <!-- <j-tree-select
                        style="width: 200px"
                        v-model="queryParam.orgCodeTxt"
                        dict="sys_depart,depart_name,id"
                        pid-field="parent_id">
                      </j-tree-select> -->
              </a-form-item>
            </a-col>
          <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
        <template v-if="toggleSearchStatus">
          <a-row :gutter="24">
          <a-col :md="6" :sm="12" style="width: 50%;">
            <a-form-item label="人员类别">
              <j-multi-select-tag
              v-model="queryParam.categorys" placeholder="请选择人员类别"
                dictCode="category"/>
                </j-multi-select-tag>
            </a-form-item>
          </a-col>
        
          <a-col :md="6" :sm="12" style="width: 50%;">
            <a-form-item label="雇佣状态">
              <j-multi-select-tag 
                      v-model="queryParam.empStatus"
                      dictCode="employmentStatus"
                      placeholder="请选择雇佣状态">
                    </j-multi-select-tag>
            </a-form-item>
          </a-col>
          </a-row>
        </template>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator" style="border-top: 5px">
      <a-button @click="handleAdd()" type="primary" icon="plus" v-has="'user:add'" >添加员工</a-button>
      <a-button @click="handleExportXltx()"type="primary" icon="plus"  v-has="'user:usermb'" >员工模板</a-button>
      <a-button @click="handleExportXls3('薪资模板')"type="primary" icon="plus"  v-has="'user:changemb'" >薪资模板</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('用户信息')" v-has='"user:export"'>导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel" v-has='"user:import"'>
        <a-button type="primary" icon="import">员工导入</a-button>
      </a-upload>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrls" @change="handleImportExcels" v-has='"userchange:import"'>
        <a-button type="primary" icon="import">薪资导入</a-button>
      </a-upload>
      <a-button type="primary" icon="hdd" @click="recycleBinVisible=true" v-has='"user:recovery"'>回收站</a-button>
     
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay" @click="handleMenuClick">
          <a-menu-item key="1" v-if="selectionRows[0].employmentStatus==40" v-has='"user:delete"'>
            <a-icon type="delete" @click="batchDel" />
            删除
          </a-menu-item>
          <a-menu-item key="4" v-if="selectionRows[0].employmentStatus==40" v-has='"user:rz"'>
            <a-icon type="check-circle"  @click="batchrz"/>
            入职
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
      <!-- <j-super-query :fieldList="superQueryFieldList" @handleSuperQuery="handleSuperQuery" v-has='"user:query"'/> -->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>已选择&nbsp;<a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项&nbsp;&nbsp;
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        bordered
        size="middle"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange" :scroll="{ y: 700,x:1100 }">

        <template slot="avatarslot" slot-scope="text, record, index">
          <div class="anty-img-wrap">
            <a-avatar shape="square" :src="getAvatarView(record.avatar)" icon="user"/>
          </div>
        </template>
        
        <template slot="userRealname" slot-scope="text, record, index">
          <div class="anty-img-wrap">
           <a @click="handleDetails(record)" >{{text}}</a>
          </div>
        </template>
        
        <span slot="categorys" slot-scope="text, record, index">
          <a-tag color="#87d068">{{text}}</a-tag>
        </span>
        
        <span slot="employmentStatuss" slot-scope="text, record, index">
         <a-tag color="#87d068" v-if="record.employmentStatus=='10'||record.employmentStatus==10 ">在职</a-tag>
         <a-tag color="#cd201f" v-else-if="record.employmentStatus=='20'||record.employmentStatus==20 ">离退</a-tag>
         <a-tag color="#cd201f" v-else-if="record.employmentStatus=='30'||record.employmentStatus==30 ">离职</a-tag>
         <a-tag color="blue" v-else-if="record.employmentStatus=='40'||record.employmentStatus==40 ">待入职</a-tag>
        </span>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)" v-has='"user:edit"'>编辑</a>
         
         <a-divider type="vertical"/>
 <a @click="handleChangePassword(record.username)" v-has='"user:editpwd"'>修改密码</a>
          <!-- <a-dropdown v-has='"user:more"'>
            <a class="ant-dropdown-link">
              更多 <a-icon type="down"/>
            </a>
            <a-menu slot="overlay">
              <a-menu-item v-has="'user:details'" v-if="record.employmentStatus==40||record.employmentStatus=='40'">
                <a href="javascript:;" @click="handleDetails(record)">入职</a>
              </a-menu-item>


              <a-menu-item v-has='"user:delete"'>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>

            </a-menu>
          </a-dropdown> -->
        </span>


      </a-table>
    </div>
    <!-- table区域-end -->

  
    <user-modal ref="modalForm" @ok="modalFormOk"></user-modal>
    <user-detail-modal ref="userdetailmodal"></user-detail-modal>
    <password-modal ref="passwordmodal" @ok="passwordModalOk"></password-modal>
    <depart-window ref="departWindow" @ok="modalFormOks"></depart-window>

    <!-- 用户回收站 -->
    <user-recycle-bin-modal :visible.sync="recycleBinVisible" @ok="modalFormOk"/>

  </a-card>
  
</template>

<script>
  import UserModal from './modules/UserModal'
  import departWindow from './modules/DepartWindow'
  import UserDetailModal from './modules/UserDetailModal'
  import PasswordModal from './modules/PasswordModal'
  import {putAction,getFileAccessHttpUrl,getAction,downFile} from '@/api/manage';
  import {frozenBatch} from '@/api/api'
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import JInput from '@/components/jeecg/JInput'
  import UserRecycleBinModal from './modules/UserRecycleBinModal'
  import JSuperQuery from '@/components/jeecg/JSuperQuery'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
 import JTreeSelect from '@/components/jeecg/JTreeSelect'
 import JDictSelectTag from '@/components/dict/JDictSelectTag'
 import { ACCESS_TOKEN, TENANT_ID } from "@/store/mutation-types"
 import store from '@/store'
 import { filterObj } from '@/utils/util';
 import {Modal} from 'ant-design-vue'
 import Vue from 'vue'
  export default {
    name: "UserList",
    mixins: [JeecgListMixin],
    components: {
      UserModal,
      PasswordModal,
      JInput,
      UserRecycleBinModal,
      departWindow,
      UserDetailModal,
      JSuperQuery,
      JSelectDepart,
      JTreeSelect,
      JDictSelectTag
    },
    data() {
      return {
        description: '这是用户管理页面',
        queryParam: {
          empStatus:"10",
          categorys:"101",
          orgCodeTxt:null,
        },
        departNames:null,
        recycleBinVisible: false,
        selectedRowKeys:[],
        selectionRows:[],
        columns: [
          /*{
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },*/
          {
            title: '工号',
            align: "center",
            dataIndex: 'workNo',
            width: 100,
          },
          {
            title: '员工姓名',
            align: "center",
            width: 100,
            dataIndex: 'realname',
            scopedSlots: {customRender: "userRealname"}
          },
          // {
          //   title: '头像',
          //   align: "center",
          //   width: 100,
          //   dataIndex: 'avatar',
          //   scopedSlots: {customRender: "avatarslot"}
          // },
          {
            title: '性别',
            align: "center",
            width: 80,
            dataIndex: 'sex_dictText',
           
          },
          
          // {
          //   title: '生日',
          //   align: "center",
          //   width: 100,
          //   dataIndex: 'birthday'
          // },
          // {
          //   title: '手机号码',
          //   align: "center",
          //   width: 120,
          //   dataIndex: 'phone',
          //   customRender:function (t,r,index) {
          //     if(t!=null&&t!=""){
          //       var a=t.slice(0,3);
          //       var b=t.slice(8,11);
          //       return a+"****"+b;
          //     }else{
          //       return"";
          //     }
              
          //   }
          // },
          {
            title: '邮箱',
            align: "center",
            width: 120,
            dataIndex: 'email'
          },
          {
            title: '一级部门',
            align: "center",
            width: 120,
            dataIndex: 'del2'
          },
          {
            title: '二级部门',
            align: "center",
            width: 120,
            dataIndex: 'del3'
          },
          // {
          //   title: '三级部门',
          //   align: "center",
          //   width: 120,
          //   dataIndex: 'del4'
          // },
          {
            title: '职位',
            align: "center",
            width: 120,
            dataIndex: 'post_dictText'
          },
          {
            title: '入职时间',
            align: "center",
            width: 120,
            dataIndex: 'entryDate'
          },
          {
            title: '人员类别',
            align: "center",
            width: 100,
            dataIndex: 'category_dictText',
            scopedSlots: {customRender: "categorys"},
           
          },
          {
            title: '雇佣状态',
            align: "center",
            width: 100,
            dataIndex: 'employmentStatus',
            scopedSlots: {customRender: "employmentStatuss"},
            
          },
          // {
          //   title: '状态',
          //   align: "center",
          //   width: 80,
          //   dataIndex: 'status_dictText'
          // },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: {customRender: 'action'},
            align: "center",
            width: 170
          }

        ],
        superQueryFieldList: [
          { type: 'input', value: 'username', text: '用户账号', },
          { type: 'input', value: 'realname', text: '用户姓名', },
          { type: 'select', value: 'sex', text: '性别', dictCode: 'sex' },
        ],
        url: {
          syncUser: "/act/process/extActProcess/doSyncUser",
          list: "/sys/user/list",
          delete: "/sys/user/delete",
          deleteBatch: "/sys/user/deleteBatch",
          exportXlsUrl: "/sys/user/exportXls",
          importExcelUrl: "sys/user/importExcel",
          importExcelUrls:'sys/user/importExcels',
          pulldata:"/sys/weixin/pullData",
          editstate:"/sys/user/editState",
          userChangemb:'/userchange/userChage/exportXls'
        },
      }
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
      importExcelUrls(){
         return `${window._CONFIG['domianURL']}/${this.url.importExcelUrls}`;
      }
    },
    methods: {
      // onSelectChanges(selectedRowKeys, selectionRows) {
      //   this.selectedRowKeys = selectedRowKeys;
      //   this.selectionRows = selectionRows;
      // },
      handleExportXltx(){
        this.queryParam.orgCodeTxt="空白模板";
        this.$options.methods.handleExportXls.call(this)
        this.queryParam.orgCodeTxt="";
      },
      getAvatarView: function (avatar) {
        return getFileAccessHttpUrl(avatar)
      },
      clearSpace(e) {
        this.queryParam.realname = e.target.value.replace(/\s+/g, '')
      },
      clearSpaces(e) {
        this.queryParam.workNo = e.target.value.replace(/\s+/g, '')
      },
      modalFormOks(formData) {
        if (formData.departIdList != null && formData.departIdList.length > 0) {
          for (let i = 0; i < formData.departIdList.length; i++) {
            this.queryParam.orgCodeTxt=formData.departIdList[i].key;
            this.departNames =formData.departIdList[i].title;
          
           }
        
        }
      
      },
      batchrz(){
        if (this.selectedRowKeys.length<=0) {
          this.$message.warning('请选择一条记录！');
          return false;
        } else {
          var userids=this.selectedRowKeys.join(",");
          getAction(this.url.editstate, {
            userids:userids
          }).then(res => {
            if (res.success) {
              this.$message.success(res.message);
                this.loadData();
              }else{
                this.$message.warning(res.message);
              }
          })
          this.selectedRowKeys=[];
          this.selectionRows=[];
        }
      },
      handleEmpty(){
        this.queryParam.orgCodeTxt=null;
        this.departNames=null;
      },
      batchFrozen: function (status) {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return false;
        } else {
          let ids = "";
          let that = this;
          let isAdmin = false;
          that.selectionRows.forEach(function (row) {
            if (row.username == 'admin') {
              isAdmin = true;
            }
          });
          if (isAdmin) {
            that.$message.warning('管理员账号不允许此操作,请重新选择！');
            return;
          }
          that.selectedRowKeys.forEach(function (val) {
            ids += val + ",";
          });
          that.$confirm({
            title: "确认操作",
            content: "是否" + (status == 1 ? "解冻" : "冻结") + "选中账号?",
            onOk: function () {
              frozenBatch({ids: ids, status: status}).then((res) => {
                if (res.success) {
                  that.$message.success(res.message);
                  that.loadData();
                  that.onClearSelected();
                } else {
                  that.$message.warning(res.message);
                }
              });
            }
          });
        }
      },
      openModal(){
        var ls=[];
        ls.push(this.queryParam.orgCodeTxt);
        this.$refs.departWindow.add(ls, {});
      },
      handleMenuClick(e) {
        var data=this.selectionRows;
        var f=false;
        for(var i=0;i<data.length;i++){
            if(data[i].employmentStatus!=40){
              f=true;
            }
        }
        if(f){
          this.$message.warning('请勾选待入职数据');
          return;
        }
        if (e.key == 1) {
          this.batchDel();
        } else if (e.key == 2) {
          this.batchFrozen(2);
        } else if (e.key == 3) {
          this.batchFrozen(1);
        }else if(e.key==4){
          this.batchrz();
        }
      },
      handleDetails(e){
        console.log(this.$refs)
        this.$refs.userdetailmodal.edit(e);
      },
      handleFrozen: function (id, status, username) {
        let that = this;
        //TODO 后台校验管理员角色
        if ('admin' == username) {
          that.$message.warning('管理员账号不允许此操作！');
          return;
        }
        frozenBatch({ids: id, status: status}).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.loadData();
          } else {
            that.$message.warning(res.message);
          }
        });
      },
      handleExportXls3(fileName){
        
      
        if(!fileName || typeof fileName != "string"){
          fileName = "导出文件"
        }
        downFile(this.url.userChangemb,{}).then((data)=>{
          if (!data) {
            this.$message.warning("文件下载失败")
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName+'.xls')
          }else{
            let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName+'.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link); //下载完成移除元素
            window.URL.revokeObjectURL(url); //释放掉blob对象
          }
        })
      },
      /* 导入 */
      handleImportExcels(info){
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            // this.$message.success(`${info.file.name} 文件上传成功`);
            if (info.file.response.code === 201) {
              let { message, result: { msg, fileUrl, fileName } } = info.file.response
              let href = window._CONFIG['domianURL'] + fileUrl
              this.$warning({
                title: message,
                content: (<div>
                    <span>{msg}</span><br/>
                    <span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
                  </div>
                )
              })
            } else {
              this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
            }
            this.loadData()
          } else {
            this.$message.error(`${info.file.name} ${info.file.response.message}.`);
          }
        } else if (info.file.status === 'error') {
          if (info.file.response.status === 500) {
            let data = info.file.response
            const token = Vue.ls.get(ACCESS_TOKEN)
            if (token && data.message.includes("Token失效")) {
              Modal.error({
                title: '登录已过期',
                content: '很抱歉，登录已过期，请重新登录',
                okText: '重新登录',
                mask: false,
                onOk: () => {
                  store.dispatch('Logout').then(() => {
                    Vue.ls.remove(ACCESS_TOKEN)
                    window.location.reload();
                  })
                }
              })
            }
          } else {
            this.$message.error(`文件上传失败: ${info.file.msg} `);
          }
        }
      },
      handleChangePassword(username) {
        this.$refs.passwordmodal.show(username);
      },
      passwordModalOk() {
        //TODO 密码修改完成 不需要刷新页面，可以把datasource中的数据更新一下
      }
    }

  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>