<!--张文艺-->
<template>
  <div class="container-fluid">
    <el-row class="filter_style">
      <el-col :span="24" style="padding: 0 0">
        <_BTN_FILTER :isMore="isMore" :btnGroups="btnGroups" :fileName="fileName"
                     @on-click="exportEve" :tableData="tableData"/>
      </el-col>
    </el-row>
    <div>
      <_TABLE :columns="columnHeader" :tableData="dataSource" :tableHeight="1000"
              :sortChange="sortChange" :rowClick="rowClick" :btnMode=true :btns="btns"
              :pageSizes="pageSizes" :currentPage=currentPage :pageSize=pageSize
              :totalCount=totalCount :queryData=this.queryData
              :checkBox=true
              :select="select" :selectAll="selectAll" :hasPagination="true"
              ref="tableGrid" :tableType=tableType :headerClick="headerClick"></_TABLE>
    </div>
    <_POPUP :dialogObj='addDialogObj' @confirmBack="addBack"/>
    <_POPUP :dialogObj='updateDialogObj' @confirmBack="updateBack"/>
    <_POPUP :dialogObj='moreDialogobj' @confirmBack="moreBack"/>
    <_POPUP :dialogObj='sessionFailedDialogObj' @confirmBack="sessionFailedBack" />
  </div>
</template>
<script>
  import _TABLE from '@/components/Template/TabPagin/Table.vue'
  import _POPUP from '@/components/Template/Popup/Popup.vue'
  import _BTN_FILTER from '@/components/Template/Screen/btn&filterTemp.vue'
  import BasePath from '@/config/BasePath'
  import api from '@/api'
  import log from '@/log'
  export default {
    mounted () {
      // this.ceshi()
      /** 调用初始化数据 **/
      this.init()
    },
    data () {
      return {
        aa: {
        },
        /** 查询更多条件 **/
        isMore: true,
        /** 过滤的字段 **/
        fileName: ['userName', 'userCode', 'personId', 'email'],
        /** 定义按钮 **/
        btnGroups: [
          {
            name: '新增',
            className: 'btn-info',
            iconName: 'fa-plus',
            event: this.addClk
          }
        ],
        /** table **/
        tableType: '4',
        currentPage: 1, // 默认当前第一页
        pageSize: 10,  // 默认每页20条数据
        pageSizes: [10, 20, 40, 50], // 分页数选择项
        totalCount: 0, // 表格总记录数
        columnHeader: [
          {
            value: 'userCode', // 列的值
            label: '登录账号', // 列的显示字段
            align: 'left' // 列的对齐方式，[left, center, right]，选填，默认是left
          }, {
            value: 'userName',
            align: 'left',
            label: '姓名'
          }, {
            value: 'personId',
            label: '工号',
            align: 'left'
          }, {
            value: 'email',
            label: 'email',
            align: 'left'
          }, {
            value: 'company',
            label: '公司',
            align: 'left'
          }, {
            value: 'remark',
            label: '备注',
            align: 'left'
          }
        ],
        /** 表格数据 **/
        tableData: [],
        dataSource: [], // 当前页的数据
        btns: {
          btnArr: [
            {
              label: '修改', // 按钮的名称
              value: 'modify', // 按钮的值
              type: 'warning',
              icon: 'edit',
              functionName: this.modify // 按钮的方法
            },
            {
              label: '设置',  // 按钮的名称
              value: 'setting', // 按钮的值
              type: 'info',
              icon: 'setting',
              functionName: this.setting // 按钮的方法
            },
            {
              label: '删除',
              value: 'del',
              type: 'danger',
              icon: 'delete',
              functionName: this.del
            }
          ],
          value: 'operation',
          label: '操作',
          width: '300px'
        },
        /** 弹出层 **/
        addDialogObj: {
          title: '新增用户',
          type: 'addUser',
          dialogVisible: false,
          data: {
            form: {
              rowId: '',
              personId: '',
              userName: '',
              userCode: '',
              password: '',
              confirmPass: '',
              company: '',
              department: '',
              email: '',
              status: false,
              loginFlag: false,
              contactPhone: '',
              mobile: '',
              remark: '',
              files: '',
              attrFlag: '0',
              certYn: 'N',
              menuFlag: '0',
              appUserFlag: 'Y',
              usingFlag: '0',
              auditUserId: '-1',
              loginFirst: 'Y',
              companyId: '',
              divisionId: ''
            }
          }
        },
        updateDialogObj: {
          title: '修改用户',
          type: 'editUser',
          dialogVisible: false,
          data: {
            form: {
              rowId: '',
              personId: '',
              userName: '',
              userCode: '',
              company: '',
              department: '',
              email: '',
              status: '',
              loginFlag: '',
              contactPhone: '',
              mobile: '',
              remark: '',
              companyId: '',
              divisionId: ''
            }
          }
        },
        sessionFailedDialogObj: {
          title: '会话失效',
          type: 'sessionFailured',
          dialogVisible: false,
          size: 'tiny',
          data: {
            form: {
              userCode: '',
              password: ''
            }
          }
        },
        moreDialogobj: {
          title: '查询',
          type: 'query',
          dialogVisible: false,
          data: {
            form: {
              userName: '',
              userCode: '',
              companyId: '',
              divisionId: '',
              masterId: '',
              mobile: ''
            }
          }
        }
      }
    },
    methods: {
      /** 初始化数据方法 **/
      init () {
        api.requestJava('POST', BasePath.USER_SELECTLISTPAGES, {})
          .then((request) => {
            if (Number(request.data.code) === 200) {
              this.tableData = request.data.data
              this.currentPage = 1
              this.queryData(this.currentPage, this.pageSize)
            } else if (Number(request.data.code) === 401) {
              this.sessionFailedDialogObj.dialogVisible = true
            } else {
              throw new Error(JSON.stringify(request))
            }
          })
          .catch((err) => {
            this.$store.commit('TOGGLE_LOADING')
            let culprit = this.$route.name
            log.work(err, culprit)
          })
      },
      queryData (page, size) {
        // 前段分页
        this.totalCount = this.tableData.length
        this.dataSource = this.tableData.filter((u, index) => index < size * page && index >= size * (page - 1))
      }, // 分页请求
      select (selection, index) {
        if (selection[0] !== undefined) {
          this.sel_all = []
          this.sel_allRole = []
          for (var i in selection) {
            let param = {}
            let params = {}
            param.rowId = selection[i].rowId
            params.userId = selection[i].rowId
            this.sel_allRole.push(params)
            this.sel_all.push(param)
          }
          console.log(this.sel_all)
        }
      }, // 选中某1条
      selectAll (data) {
        this.sel_all = []
        this.sel_allRole = []
        for (var i in data) {
          let param = {}
          let params = {}
          param.rowId = data[i].rowId
          params.userId = data[i].rowId
          this.sel_all.push(param)
          this.sel_allRole.push(params)
        }
      }, // 全选
      addClk () {
        this.clearObject()
        this.addDialogObj.title = '新增用户'
        this.addDialogObj.dialogVisible = true
      }, // 新增
      modify (index, row) {
        Object.assign(this.updateDialogObj.data.form, row)
        this.updateDialogObj.data.form.status = (Number(row.status) === 1)
        this.updateDialogObj.data.form.loginFlag = ((row.loginFlag) === 'Y')
        /* TODO 公司和部门替换为字典 */
        this.updateDialogObj.title = '修改用户'
        this.updateDialogObj.dialogVisible = true
      }, // 修改
      setting (index, row) {
        this.$message('设置')
        console.log('=====', row.rowId)
        this.$router.push({name: 'LoginInfo', params: {rowId: row.rowId}})
      }, // 设置
      del (index, row) {
        console.log(row.rowId)
        this.$confirm('确定删除此条信息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {}
          params.userId = row.rowId
          let param = {}
          param.rowId = row.rowId
          api.requestJava('POST', 'system/userrole/selectList.do', params)
            .then((request) => {
              if (Number(request.data.code) === 200) {
                var judge = request.data.data.length
                if (judge > 0) {
                  this.$confirm('此用户已分配角色，是否删除角色？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {
                    api.requestJava('POST', 'system/userrole/delete.do', params)
                      .then((request) => {
                        if (Number(request.data.code) === 200) {
                          this.delUser(param)
                        } else if (Number(request.data.code) === 401) {
                          this.sessionFailedDialogObj.dialogVisible = true
                        } else {
                          throw new Error(JSON.stringify(request))
                        }
                      })
                  }).catch(() => {
                    this.delUser(param)
                  })
                } else {
                  this.delUser(param)
                }
              } else if (Number(request.data.code) === 401) {
                this.sessionFailedDialogObj.dialogVisible = true
              } else {
                throw new Error(JSON.stringify(request))
              }
            })
        }).catch(() => {
          this.$message({type: 'info', message: '已取消删除!'})
        })
      },  // 删除
      isMoreClk () {
        this.moreDialogobj.dialogVisible = true
      }, // 更多条件
      inputChange (val) {
        /** 搜索功能回调 **/
        let page = this.currentPage
        let size = this.pageSize
        this.dataSource = JSON.parse(val).filter((u, index) => index < size * page && index >= size * (page - 1))
      },
      delUser (params) {
        api.requestJava('POST', BasePath.USER_DELETE, params)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              this.init()
              this.$message({type: 'success', message: '删除成功!'})
            } else if (Number(request.data.code) === 401) {
              this.sessionFailedDialogObj.dialogVisible = true
            } else {
              throw new Error(JSON.stringify(request))
            }
          })
      },
      addBack (msg) {
        if (msg) {
          this.add(msg)
        } else {
          this.clearObject()
        }
      },
      add (msg) {
        let data = msg.data.form
        let paraminfo = data
        if (data.status) {
          paraminfo.status = '1'
        } else {
          paraminfo.status = '0'
        }
        if (data.loginFlag) {
          paraminfo.loginFlag = 'Y'
        } else {
          paraminfo.loginFlag = 'N'
        }
        api.requestJava('POST', BasePath.USER_INSERT, paraminfo)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              this.clearObject()
              this.init()
              this.$message({type: 'success', message: '新增成功!'})
            } else if (Number(request.data.code) === 401) {
              this.sessionFailedDialogObj.dialogVisible = true
            } else {
              throw new Error(JSON.stringify(request))
            }
          })
      },
      updateBack (msg) {
        let data = msg.data.form
        let paraminfo = data
        if (data.status) {
          paraminfo.status = '1'
        } else {
          paraminfo.status = '0'
        }
        if (data.loginFlag) {
          paraminfo.loginFlag = 'Y'
        } else {
          paraminfo.loginFlag = 'N'
        }
        api.requestJava('POST', BasePath.USER_UPDATE, paraminfo)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              this.init()
              this.$message({type: 'success', message: '修改成功!'})
            } else if (Number(request.data.code) === 401) {
              this.sessionFailedDialogObj.dialogVisible = true
            } else {
              throw new Error(JSON.stringify(request))
            }
          })
      },
      clearObject () {
        let temp = {
          title: '新增用户',
          type: 'addUser',
          dialogVisible: false,
          data: {
            form: {
              rowId: '',
              personId: '',
              userName: '',
              userCode: '',
              password: '',
              confirmPass: '',
              company: '',
              department: '',
              email: '',
              status: false,
              loginFlag: false,
              contactPhone: '',
              mobile: '',
              remark: '',
              files: '',
              certYn: 'N',
              attrFlag: '0',
              menuFlag: '0',
              appUserFlag: 'Y',
              usingFlag: '0',
              auditUserId: '-1',
              loginFirst: 'Y',
              companyId: '',
              divisionId: ''
            }
          }
        }
        let tempMore = {
          title: '查询',
          type: 'query',
          dialogVisible: false,
          data: {
            form: {
              userName: '',
              userCode: '',
              mobile: '',
              companyId: '',
              divisionId: ''
            }
          }
        }
        Object.assign(this.addDialogObj, temp)
        Object.assign(this.moreDialogobj, tempMore)
      },
      sortChange (msg) {},
      rowClick (msg) {},
      moreBack (msg) {
        let param = msg.data.form
        api.requestJava('POST', '/system/user/selectListForFuzzy.do', param)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              console.log(request.data.data)
              this.tableData = request.data.data
              this.queryData(this.currentPage, this.pageSize)
              this.clearObject()
            } else if (Number(request.data.code) === 401) {
              this.sessionFailedDialogObj.dialogVisible = true
            } else {
              throw new Error(JSON.stringify(request))
            }
          })
          .catch((err) => {
            this.$store.commit('TOGGLE_LOADING')
            let culprit = this.$route.name
            log.work(err, culprit)
          })
      }, // 多条件查询
      sessionFailedBack (msg) {
        let headers = msg.data.form
        let array = [headers, this]
        this.$store.dispatch('login', array)
          .then((msg) => {
            if (msg === 'success') {
              this.sessionFailedDialogObj.dialogVisible = false
            }
          })
          .catch((err) => { console.log(err) })
      }, // 会话失效
      exportEve () {
        this.$refs.tableGrid.exportExcel()
      }, // 导出Elxc
      headerClick (column, event) {}
    },
    components: {
      _TABLE,
      _POPUP,
      _BTN_FILTER

    }
  }
</script>
