<template>
  <div class="content-main-manage">
    <div class="search-list">
      <div class="search-left">
        <Form class="common-form common-form-list" ref="tableParams" :model="tableParams" inline>
          <FormItem label="" prop="orgType">
            <Select v-model="tableParams.orgType" placeholder="" label-in-value>
              <Option v-for="item in orgTypeData" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
          <FormItem label="" prop="roleId">
            <Select v-model="tableParams.roleId" placeholder="角色名称">
              <Option v-for="item in roleData" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
          <FormItem label="" prop="isEnabled">
            <Select v-model="tableParams.isEnabled" placeholder="启用状态">
              <Option v-for="item in enabledData" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
          <FormItem label="" prop="userName">
            <Input placeholder="输入用户号" clearable search v-model="tableParams.userName" />
          </FormItem>
          <FormItem label="" prop="realName">
            <Input placeholder="输入姓名关键词" clearable search v-model="tableParams.realName" />
          </FormItem>
          <FormItem label="">
            <DatePicker type="datetimerange" :value="dateRange" format="yyyy-MM-dd HH:mm:ss" placeholder="更新时间范围" class="common-date-picker date-picker-main" :clearable="false" :editable="false" @on-change="changePicker"></DatePicker>
          </FormItem>
          <FormItem label="" >
            <Button type="primary" class="common-btn-search" @click="searchClick">
              <Icon type="ios-search" style="margin-right:4px;font-size: 16px"/> 筛选
            </Button> 
            <Button type="primary" class="common-btn-search" style="margin-left:10px" @click="resetClick('tableParams')">
              <Icon type="ios-search" style="margin-right:4px;font-size: 16px"/> 重置
            </Button>   
          </FormItem>
        </Form>
      </div>
    </div>
    <div class="btn-container">
      <Button icon="ios-add" class="common-add-btn" @click="addClick">新增用户</Button>
    </div>
    <div class="manage-main-center">
      <Table :columns="columns" :data="tableData" class="common-table app-table" no-data-text="" :row-class-name="rowClassName" :loading="loading">
        <template slot="loading">
            <Loading-animation></Loading-animation>
        </template>
         <template slot-scope="{ row }" slot="action">
           <Tooltip content="重置密码" placement="top">
              <i class="iconfont icon-mima" style="cursor:pointer;color:#858aea;fontSize:16px;marginRight:6px;vertical-align: middle;" @click="resetPwd(row)"></i>
           </Tooltip>
           <Tooltip content="详情" placement="top">
              <i class="iconfont icon-xiangqingmingxi" style="cursor:pointer;color:#B8B532;fontSize:20px;marginRight:6px;vertical-align: middle;" @click="detailClick(row)"></i>
           </Tooltip>
           <Tooltip content="编辑" placement="top">
              <i class="iconfont icon-bianji" style="cursor:pointer;color:#64ACFE;fontSize:20px;marginRight:6px;vertical-align: middle;" @click="editClick(row)"></i>
           </Tooltip>
           <Tooltip content="删除" placement="top">
              <i class="iconfont icon-shanchu" style="cursor:pointer;color:#E92E2E;fontSize:20px;marginRight:6px;vertical-align: middle;" @click="delClick(row)"></i>
           </Tooltip>
        </template>
      </Table>
    </div>
    <div class="common-page">
      <div class="common-page-total">
        共<span>{{tablePage}}</span>页 / <span>{{tableTotal}}</span>条数据
      </div>
      <Page :total="tableTotal" :current="tableParams.pageNum" :page-size="tableParams.pageSize" @on-change="changePage" @on-page-size-change="sizeChange" show-elevator />
    </div>
    <Modal
      v-model="showModal"
      :title="title"
      width="36"
      ref="modalGrag"
      draggable
      reset-drag-position
      @on-visible-change="modalChange"
      :mask-closable="false"
      class-name="common-modal">
      <Form class="common-form common-form-modal" ref="formOption" :model="formOption" :rules="ruleValidate" :label-width="120">
				<FormItem label="用户号：" prop="userName">
          <Input v-model.trim="formOption.userName" placeholder="请输入用户号" maxlength="30" show-word-limit/> 
          <div class="common-form-item-text">可使用工号、学号等唯一不重复身份识别号</div> 
				</FormItem>
        <FormItem label="用户名：" prop="realName">
          <Input v-model.trim="formOption.realName" maxlength="10" show-word-limit /> 
				</FormItem>
				<FormItem label="组织机构：" prop="orgIdArr">
          <Cascader :data="userStationData[0].children" :render-format="format" :clearable="false" change-on-select v-model="formOption.orgIdArr" placeholder="选择组织机构" class="common-cascader" v-if="userStationData && userStationData.length>0" ref="cascader"></Cascader>
          <!-- <Cascader :data="stationOrgData" :render-format="format" :clearable="false" change-on-select v-model="formOption.orgIdArr" placeholder="选择组织机构" class="common-cascader" v-if="userStationData && userStationData.length>0" ref="cascader"></Cascader> -->
        </FormItem>
        <FormItem label="角色名称：" prop="roleId">
           <Select v-model="formOption.roleId" placeholder="角色名称">
              <Option v-for="item in roleModalData" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
        </FormItem>
        <FormItem label="手机号码：" prop="mobilePhone">
         <Input v-model.trim="formOption.mobilePhone" placeholder="手机号格式校验" />
        </FormItem>
        <FormItem label="邮箱：" prop="userMail">
          <Input v-model.trim="formOption.userMail" placeholder="邮箱格式校验"/>  
        </FormItem>
         <FormItem label="启用状态：" prop="isEnable" v-if="title == '新增用户'">
          <i-switch true-color="#57C44F" v-model="formOption.isEnable" disabled></i-switch>
          <span style="color: #718EBD;margin-left:6px">关</span>
          <span style="color: #718EBD;margin-left:12px">（所有新增状态均为关闭，需在列表打开）</span>
        </FormItem>
			</Form>
      <div slot="footer">
          <Button @click="modalCancel">取消</Button>
          <Button type="primary" @click="modalOk('formOption')">确定</Button>
        </div>
    </Modal>
    <Modal
      v-model="modalStatus"
      :title="commonTitle"
      width="30"
      ref="modalGrag"
      draggable
      reset-drag-position
      :mask-closable="false"
      class-name="common-modal">
      <i :class="'iconfont '+ activeClass" :style="{ color: activeColor}" class="modal-icon" v-show="commonTitle!='确认删除'"></i>
      <Icon type="ios-information-circle" :style="{ color: activeColor}" class="modal-icon" v-show="commonTitle=='确认删除'"></Icon>
      <span class="modal-text">{{modalTitle}}</span>
      <div slot="footer">
          <Button @click="commonCancel">取消</Button>
          <Button type="primary" @click="commonOk">确定</Button>
        </div>
    </Modal>
     <Modal
      v-model="detailStatus"
      title="用户详情"
      width="30"
      ref="modalGrag"
      draggable
      reset-drag-position
      footer-hide
      :mask-closable="false"
      class-name="common-modal">
      <Form class="common-form common-form-modal" :model="detailData" :label-width="120">
				<FormItem label="用户号："> 
          <div class="common-form-detail-text">{{detailData.userName}}</div> 
				</FormItem>
        <FormItem label="用户名：">
         <div class="common-form-detail-text">{{detailData.realName}}</div> 
				</FormItem>
				<FormItem label="组织机构：">
          <div class="common-form-detail-text">{{detailData.orgName}}</div> 
        </FormItem>
        <FormItem label="角色名称：">
          <div class="common-form-detail-text">{{detailData.roleName}}</div> 
        </FormItem>
        <FormItem label="手机号码：">
         <div class="common-form-detail-text">{{detailData.mobilePhone}}</div> 
        </FormItem>
        <FormItem label="邮箱：">
          <div class="common-form-detail-text">{{detailData.userMail}}</div> 
        </FormItem>
        <FormItem label="启用状态：">
          <div class="common-form-detail-text">{{detailData.isEnable == 1 ? '开启' : '关闭'}}</div>
        </FormItem>
        <FormItem label="更新时间：">
          <div class="common-form-detail-text">{{detailData.updateTime}}</div> 
        </FormItem>
        <FormItem label="最后登录时间：">
          <div class="common-form-detail-text">{{detailData.lastLoginTime}}</div> 
        </FormItem>
			</Form>
    </Modal>
  </div>
</template>
<script>
const defaultFrom = {userName: '',realName: '',orgId: '',orgIdArr: [],roleId: '',mobilePhone: '',userMail: '',isEnable:0}
export default {
  name: "UserManagementIndex",
  props: {
    userStationData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    currentOrgId: [String,Number]
  },
  data() {
    return {
      loading: true,
      dateRange: [],
      tableParams: {
        keywords: '',
        orgType: 'all',
        orgId: '',
        roleId: '',
        isEnabled: '',
        userName:'',
        realName: '',
        beginUpdateTime: '',
        endUpdateTime: '',
        pageNum: 1,
        pageSize: 10
      },
      tableData: [],
      tableTotal: 0,
      tablePage: 0,
      rowObj: {},
      enabledData: [
         {
          value: '-1',
          label: '启用状态'
        },
        {
          value: '1',
          label: '启用'
        },
        {
          value: '0',
          label: '关闭'
        },
      ],
      orgTypeData: [
        {
          value: 'all',
          label: '当前及下级节点所有用户'
        },
        {
          value: 'cur',
          label: '仅当前节点用户'
        },
      ],
      roleData: [],
      roleModalData: [],
      stationTypeData: [],
      equipStateData: [],
      equipStateModalData: [],
      equipTypeData: [],
      equipTypeModalData: [],
      equipAppModalData: [],
      columns: [
          {
            title: '序号',
            type: 'index',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '用户号',
            key: 'userName',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '用户名',
            key: 'realName',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '组织机构',
            key: 'orgName',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '角色名称',
            key: 'roleName',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '更新时间',
            align: 'center',
            key: 'updateTime',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '启用状态',
            key: 'isEnable',
            align: 'center',
            width: 120,
            render: (h, params) => {
              return h('div', [                             
                h('i-switch', {
                  props: { value: params.row.isEnable,'true-color': '#57C44F', trueValue:1,falseValue: 0
                  },
                  nativeOn:{
                      "mousedown":(event)=>{ // 监听组件原生事件mousedown,此事件在click之前触发
                        this.rowObj =  params.row
                        if (params.row.isEnable == 1) {
                          this.commonTitle = '确认关闭'
                          this.activeColor = '#E92E2E'
                          this.activeClass = 'icon-guanbi'
                          this.modalTitle = '关闭后，用户无法登录。关闭不影响用户已经产生的操作记录。'
                          this.modalStatus = true         
                        } else {
                          this.commonTitle = '确认启用'
                          this.activeColor = '#57C44F'
                          this.activeClass = 'icon-qiyong'
                          this.modalTitle = '启用后，用户即可正常登录使用。'
                          this.modalStatus = true
                        }
                      },
                    }
                }),
              ])
            }
        },
        {
          title: '操作',
          align: 'center',
          slot: 'action',
          width: 160,
        }
      ],
      showModal: false,
      detailStatus: false, 
      modalStatus: false,
      title: '新增用户',
      commonTitle: "确认删除",
      activeColor: '#E92E2E',
      activeClass: '',
      modalTitle: '',
      formOption: {userName: '',realName: '',orgId: '',orgIdArr: [],roleId: '',mobilePhone: '',userMail: '',isEnable:0},
      ruleValidate: {
        userName: [{
          required: true,
          message: '请输入用户ID',
          trigger: 'blur'
        }],
        realName: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        }],
        orgIdArr: [{
          required: true,
          type: 'array',
          message: '请选择组织机构',
          trigger: 'change'
        }],
        roleId: [{
          required: true,
          type: 'number', 
          message: '请选择角色名称',
          trigger: 'change'
        }], 
        mobilePhone: [
             { required: true, message: "请输入手机号码", trigger: "blur" },
             { pattern: /^1[3456789]\d{9}$/, message: "手机号码格式不正确", trigger: "blur" } ///^[1][345789]\d{9}$/
        ],
        userMail: [
            { type: 'email', message: '请输入正确格式的邮箱', trigger: 'blur'}
        ]
      }, 
      detailData: {},
      curOrgId: '',
    };
  },
  watch: {
    currentOrgId: {
    　handler(newValue, oldValue) {
      this.curOrgId = newValue
     },
   }
  },
  mounted() {
    this.getType()
  },
  methods: {
    format (labels, selectedData) {
      const index = labels.length - 1;
      this.formOption.orgId = selectedData.length >0 ? selectedData[selectedData.length-1].nodeId : ''
      return labels[index];
    },
    changePicker (date) {
      this.tableParams.beginUpdateTime = date[0]
      this.tableParams.endUpdateTime = date[1]
    },
    rowClassName(row, index) {
      if (index % 2 == 0) {
        return "ivu-table-stripe-even";
      } else {
        return "ivu-table-stripe-odd";
      }
    },
    // 分页
    changePage (val) {
      this.tableParams.pageNum = val
      this.getTableData()
    },
    //跳转
    sizeChange (val) {
      this.tableParams.pageSize = val
      this.getTableData()
    },
    getType  () {
      // 获取用户状态
      this.$get('metroapi/dic/queryDictionary', {name:'用户状态'}).then(res=>{
        if (res.httpCode == 1 ){
          this.equipStateModalData = JSON.parse(JSON.stringify(res.data))
          this.equipStateData = res.data
          this.equipStateData.unshift({ id: '-1', value: '用户状态' })
        } else {
          this.equipStateData = []
          this.equipStateModalData = []
        }
      })
      //获取角色名称
      this.$get('metroapi/role/box').then(res=>{
        if (res.httpCode == 1 ){
          this.roleModalData = JSON.parse(JSON.stringify(res.data))
          this.roleData = res.data
          this.roleData.unshift({ value: '-1', label: '角色名称' })
        } else {
          this.roleData = []
        }
      })
    },
    // 获取表格数据
    getTableData (orgId) {
      if (typeof(orgId) == 'number' && orgId>0) {
       this.tableParams.orgId = orgId
      } else {
        if (orgId === 0) {
          this.tableParams.orgId = ''
        } else {
          this.tableParams.orgId = this.curOrgId
        }
      }
      let params = JSON.parse(JSON.stringify(this.tableParams))
      params.roleId = params.roleId == '-1' ? '' : params.roleId
      params.isEnabled = params.isEnabled == '-1' ? '' : params.isEnabled
      this.loading = true
      this.$get('metroapi/user/querySysUserPage', params).then(res=>{
        this.loading = false
          if (res.httpCode == 1 ){
            this.tableData = res.data.data
            this.tableTotal = res.data.count
            if (res.data.data.length==0) {
              this.tablePage = 0
            } else {
              this.tablePage = res.data.count<= 10 ? 1: Math.ceil(res.data.count/this.tableParams.pageSize)
            }
            if (res.data.data.length==0 && this.tableParams.pageNum>1) {
              this.tableParams.pageNum--
              return this.getTableData()
            }
          } else {
            this.tableData = []
            this.tableTotal = 0
          }
        })
    },
    // 获取新增用户类型 
    getAddEquipType (params) {
      this.$get('metroapi/application/equipmentTypeInfo', params).then(res=>{
        if (res.httpCode == 1 ){
          this.equipTypeModalData = res.data.data
        } else {
          this.equipTypeModalData = []
        }
      })
    },
    searchClick () {
      this.tableParams.pageNum = 1
      this.getTableData()
    },
    resetClick (name) {
     this.dateRange = []
     this.tableParams.beginUpdateTime = ''
     this.tableParams.endUpdateTime = ''
     this.$refs[name].resetFields()
     this.tableParams.pageNum = 1
     this.getTableData()
    },   
    changeMoldaPicker (val) {
     this.formOption.useDate = val
    },
    addClick () {
      this.formOption = JSON.parse(JSON.stringify(defaultFrom))
      this.title = '新增用户'
      this.showModal = true
    },
    detailClick (row) {
      this.rowObj = row
      this.detailStatus = true
      this.$get('metroapi/user/userView', {userId:row.userId}).then(res=>{
        if (res.httpCode == 1 ){
          this.detailData = res.data
        } else {
          this.$Message.info(res.msg)
        }
      })
    },
    editClick (row) {
      this.rowObj = row
      this.formOption = JSON.parse(JSON.stringify(row));
      this.formOption.orgIdArr = this.treeFindPath(this.userStationData[0].children, node => node.value === row.orgId)
      this.title = '编辑用户'
      this.$nextTick(()=> {
        this.showModal = true
      })
    },
    // 根据子节点id递归获取所有父类的id
		treeFindPath (tree, func, path = []) {
      if (!tree) return []
      for (const data of tree) {
        path.push(data.value)
        if (func(data)) return path
        if (data.children) {
          const findChildren = this.treeFindPath(data.children, func, path)
          if (findChildren.length) return findChildren
        }
        path.pop()
      }
      return []
    },
    delClick (row) {
      this.rowObj = row
      this.commonTitle = '确认删除'
      this.activeColor = '#E92E2E'
      this.activeClass = ''
      this.modalTitle = '删除不影响用户已经产生的操作记录。'
      this.modalStatus = true
    },
    resetPwd (row) {
      this.rowObj = row
      this.commonTitle = '密码重置'
      this.activeColor = '#858aea'
      this.activeClass = ''
      this.modalTitle = '用户密码将被重置为123456。'
      this.modalStatus = true
    },
    modalChange (modalStatus) {
     if (!modalStatus) {
      this.$refs.formOption.resetFields();
     }
    },
    modalOk (formName) {
      let params = JSON.parse(JSON.stringify(this.formOption)) //把对象中的数据给了某个变量，改变一个对象的值，另一个对象也变化的解决方法
      if (this.title == '新增用户') {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$post('metroapi/user/addSysUser', params).then(res=>{
              if (res.httpCode == 1 ){
                this.showModal = false
                this.$Message.info(res.msg)
                this.getTableData()
              } else {
                this.$Message.info(res.msg)
              }
            })
          } else {
            this.showModal = true
          }
       })
      } else {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$post('metroapi/user/updateUser', params).then(res=>{
              if (res.httpCode == 1 ){
                this.showModal = false
                this.$Message.info(res.msg)
                this.getTableData()
              } else {
                this.$Message.info(res.msg)
              }
            })
          } else {
            this.showModal = true
          }
       })
      }
    },
    modalCancel () {
      this.showModal = false
    },
    commonOk () {
      if (this.commonTitle == '确认启用') {
        let params = {
          userId: this.rowObj.userId,
          enabled: 1,
          type: 0
        }
        this.getSwitchStatus(params)
      } else if (this.commonTitle == '确认关闭') {
        let params = {
          userId: this.rowObj.userId,
          enabled:0,
          type: 0
        }
        this.getSwitchStatus(params)
      } else if(this.commonTitle == '确认删除'){
        let params = {
          userId: this.rowObj.userId,
          type: 2
        }
        this.delData(params)
      } else {
        let params = {
          userId: this.rowObj.userId
        }
        this.resetPwdData(params)
      }
    },
    commonCancel () {
      this.modalStatus = false
    },
    // 启用 关闭/接口
    getSwitchStatus (params) {
      this.$get('metroapi/user/operation',params).then(res=>{
        if (res.httpCode == 1 ){
          if (params.enabled == 0) {
            this.rowObj.isEnable = 0
          } else {
            this.rowObj.isEnable = 1
          }
          this.modalStatus = false
        } else {
          this.rowObj.isEnable = 0
          this.$Message.info(res.msg)
        }
      })
    },
    // 删除接口
    delData (params) {
      this.$get('metroapi/user/operation',params).then(res=>{
        if (res.httpCode == 1 ){
          this.modalStatus = false
          this.$Message.info(res.msg)
          this.getTableData()
        } else {
          this.$Message.info(res.msg)
        }
      })
    },
    // 重置密码
    resetPwdData (params) {
      this.$post('metroapi/user/intial',params).then(res=>{
        if (res.httpCode == 1 ){
          this.modalStatus = false
          this.$Message.info(res.msg)
          this.getTableData()
        } else {
          this.$Message.info(res.msg)
        }
      })
    }
  }
};
</script>
<style scoped lang="stylus">
.content-main-manage {
  position: relative;
  height: 100%;
}
.search-list {
  display: flex;
  padding: 10px 0 0;
}
.search-left {
  display: flex;
  align-items: center;
   .ivu-select {
     width: 165px;
     height: 32px;
   }
   .ivu-select-single .ivu-select-selection {
     height: 100%;
   }
   >>> .ivu-input {
     width: 155px;
     height: 32px;
   }
   >>> .ivu-date-picker-editor .ivu-input {
     width: 315px;
   }
   >>> .ivu-input-prefix, >>> .ivu-input-suffix {
     height: 32px;
     line-height: 32px;
   }
   >>> .ivu-input-icon {
     height: 32px;
     line-height: 32px;
   }
   >>> .date-picker-main .ivu-date-picker-header {
    border-bottom: 0.0052083333rem solid #204384;
 }
}
.btn-container {
  display: flex;
  justify-content: flex-end;
  padding-bottom: 10px;
}
.common-form {
  display: flex;
  flex-wrap: wrap;
}
.common-form-modal {
  display: flex;
  flex-direction: column;
}
>>> .common-form-list .ivu-form-item {
  margin-bottom: 10px;
}
.manage-main-center {
  width: 100%;
  height: calc(100% - 150px);
}
.common-table {
  max-height: 100%;
}
>>> .common-table .ivu-table th {
  height: 54px;
 }
 >>> .common-table .ivu-table td {
  height: 55px;
 }
  >>> .common-table .ivu-spin-fix {
   top: 54px;
 }
  >>> .app-table .ivu-spin-fix {
   height: calc(100vh - 375px);
 }
 >>> .ivu-table-tip {
  background: url('../../../assets/images/noData.png') no-repeat center;
}
>>> .app-table .ivu-table-tip {
  height: calc(100vh - 375px);
 }
 >>> .common-table .ivu-table-tip table {
 display: none;
}
 >>> .modal-table {
   overflow: auto !important;
 }
 >>> .modal-table .ivu-spin-fix {
   height: 200px;
 }
  >>> .modal-table .ivu-table-tip {
   height: 200px;
 }
.common-page {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  position: absolute;
  bottom: 0;
  right: 0;
}
.common-page-total {
  color: #fff;
  padding-right: 10px;
  font-size: 14px;
  span {
    color #409EFF;
  }
}
.common-form-item-text {
  font-size: 11px;
  color: #85A3D4;
}
.common-form-detail-text {
  color: #0180e1;
  font-size: 14PX;
}
/* 对话框里的input里的placeholder样式修改 */
/deep/ .ivu-input::-webkit-input-placeholder , /deep/ .ivu-input-number-input::-webkit-input-placeholder{
  color: #718EBD;
}
/deep/ .ivu-input::-moz-placeholder, /deep/ .ivu-input-number-input::-webkit-input-placeholder{   /* Mozilla Firefox 19+ */
  color: #718EBD;
}
/deep/ .ivu-input::-moz-placeholde, /deep/ .ivu-input-number-input::-webkit-input-placeholderr{    /* Mozilla Firefox 4 to 18 */
 color: #718EBD;
}
/deep/ .ivu-input::-ms-input-placeholder, /deep/ .ivu-input-number-input::-webkit-input-placeholder{  /* Internet Explorer 10-11 */
  color: #718EBD;
}
</style>