<template>
  <div class="container">
    <!-- 查询配置 -->
    <div style="padding: 0px 20px">
      <div ref="lxHeader">
        <LxHeader icon="md-apps" text="用户管理" style="margin-bottom: 10px; border: 0px; margin-top: 15px">
          <div slot="content"></div>
          <slot>
            <div>
              <Input style="width: 200px; margin-right: 10px" v-model.number="searchFields.keyword"
                placeholder="关键字搜索" />
              <Button type="primary" @click="load" style="margin-left: 10px">查询</Button>
              <Button type="primary" @click="edit()" style="margin-left: 10px">新增用户</Button>
            </div>
          </slot>
        </LxHeader>
      </div>

      <div class="table-tree">
        <el-table stripe :data="tableData" class="v-table" :height="tableHeight" border style="width: 100%">
          <el-table-column type="index" align="center">
          </el-table-column>
          <el-table-column prop="name" label="用户" width="180">
          </el-table-column>
          <el-table-column prop="username" label="用户名">
          </el-table-column>
          <el-table-column prop="department" label="部门">
            <template slot-scope="scope">
              {{scope.row.department?scope.row.department.name:""}}
            </template>
          </el-table-column>
          <el-table-column prop="address" label="角色">
            <template slot-scope="scope">
              <el-tag size="medium" v-for="(item,index) in scope.row.roles" style="margin-right: 10px;">{{ item.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="300">
            <template slot-scope="scope">
              <el-popover ref="popoverBox" placement="left" width="400" trigger="click">
                <div style="margin-bottom: 15px;">选择角色</div>
                <el-checkbox v-model="role.checked" v-for="(role,index) in scope.row.rolelist" :label="role.name"
                  :key="role.id">
                  {{role.name}}
                </el-checkbox>
                <div style="margin-top:15px; display: flex;justify-content: flex-end;">
                  <Button @click="setrole(scope.row)" type="primary" ghost size="small">确认</Button>
                </div>
                <Button slot="reference" type="primary" ghost size="small">用户授权</Button>
              </el-popover>
              <Button ghost size="small" @click="edit(scope.row)" type="primary" style="margin-left: 10px;">编辑</Button>
              <Button ghost size="small" @click="del(scope.row)" type="error" style="margin-left: 10px;">删除</Button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination @current-change="handleCurrentChange" :current-page="paginations.page"
            :page-size="paginations.page_size" background layout="prev, pager, next" :total="paginations.total">
          </el-pagination>
        </div>
      </div>
      <el-dialog title="用户编辑" :visible.sync="dialogFormVisible" width="30%">
        <el-form :model="form" :rules="rules" ref="form" label-position="right" :label-width="formLabelWidth">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" :readonly="userNameStatus ? false : 'readonly'" autocomplete="off">
            </el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" type="password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="部门" prop="department_id">
            <el-select v-model="form.department_id" placeholder="请选择部门">
              <el-option v-for="item in depts" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('form')">取 消</el-button>
          <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import LxHeader from "@/components/LxHeader/index.vue";
  import {
    save,
    setRoles,
    listuser,
    del
  } from "../../api/system/user.js";
  import {
    list
  } from "../../api/system/role.js";
  import {
    listdept
  } from "../../api/system/department.js";
  export default {
    components: {
      LxHeader
    },
    created() {
      this.initLoad();
      var that = this;
      this.loadRole(function() {
        that.load();
      });
    },
    mounted() {},
    data() {

      return {
        depts: [],
        roleList: [],
        checkAll: false,
        isIndeterminate: true,
        dialogFormVisible: false,
        formLabelWidth: "120px",
        userNameStatus: true,
        form: {
          name: "",
          username: "",
          password: "",
          department_id: ""
        },
        paginations: {
          page: 1,
          page_size: 15,
          total: 0
        },
        rules: {
          name: [{
              required: true,
              message: '请输入姓名',
              trigger: 'blur'
            }
          ],
          username: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            }
          ],
          password: [{
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 8,
              message: '长度至少8位',
              trigger: 'blur'
            }
          ]
        },
        tableHeight: 0,
        //查询条件字段
        searchFields: {
          keyword: ""
        },
        tableData: []
      }
    },
    methods: {
      initLoad() {
        var that = this;
        var clientHeight = document.documentElement.clientHeight
        var lxHeader_height = 96.5; //查询 头部
        var paginationHeight = 37; //分页的高度
        var topHeight = 50; //页面 头部
        let tableHeight = clientHeight - lxHeader_height - topHeight - paginationHeight - 20;
        that.tableHeight = tableHeight;

        listdept().then(res => {
          that.depts = res;
        }).catch(error => {

        });
      },
      loadRole(callback) {
        list().then(response => {
          this.roleList = response;
          callback();
        }).catch(error => {
          //reject(error)
        })
      },
      handleCurrentChange(page) {
        this.paginations.page = page;
        this.load();
      },
      load() {
        var that = this;
        listuser({
          page: that.paginations.page,
          ...this.searchFields
        }).then(response => {
          var data = response.data;
          this.paginations.total = response.total;
          var _rolelist = [];
          for (var m of data) {
            _rolelist = that.roleList;
            m.rolelist = JSON.parse(JSON.stringify(_rolelist)); //深拷贝
            var roles = m.roles;

            var _u_rolelist = m.rolelist;
            for (var mod of _u_rolelist) {
              let _hasRoles = that.hasRoles(roles, mod.id);
              if (_hasRoles) {
                mod.checked = true;
              } else {
                mod.checked = false;
              }
            }
            console.log(_u_rolelist)
            //break;
            m.rolelist = _u_rolelist;
          }
          that.tableData = data;
        }).catch(error => {
          console.log(error)
          //reject(error)
        })
      },
      hasRoles(roles, id) {
        return roles.filter((p, i) => {
          return p.id == id
        }).length == 1;
      },
      del(obj) {
        var that = this;
        if (obj) {
          this.$Modal.confirm({
            title: '确认要删除数据？',
            onOk: () => {
              del({
                id: obj.id
              }).then(response => {
                this.$Message.success('操作成功');
                that.load();
              }).catch(error => {
                console.log(error)
                reject(error)
              })
            },
            onCancel: () => {
              //this.$Message.info('Clicked cancel');
            }
          });
        }
      },
      edit(obj) {
        this.form = this.$options.data().form
        if (obj) {
          var result = Object.assign(this.form, obj);
          this.userNameStatus = false;
          this.form = result;
        } else {
          this.userNameStatus = true;
        }
        this.dialogFormVisible = true;
      },
      submitForm(formName) {
        var that = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            save(that.form).then(response => {
              //console.log(response)
              this.$Message.success('操作成功');
              that.load();
              that.dialogFormVisible = false;
            }).catch(error => {
              //reject(error)
            })
          } else {
            this.$Message.error('数据校验失败');
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        var that = this;
        this.$refs[formName].resetFields();
        that.dialogFormVisible = false;
      },
      setrole(obj) {
        var that = this;
        var rolelist = obj.rolelist;
        var id = obj.id;
        var len = rolelist.filter((p, index) => {
          return p.checked;
        }).length;
        if (len == 0) {
          this.$message.error("请选择角色");
          return false;
        }
        var arr = [];
        for (var m of rolelist) {
          if (m.checked) {
            arr.push(m.id);
          }
        }
        setRoles({
          role_id: arr,
          id: id
        }).then(response => {
          this.$Message.success('操作成功');
          that.load();
          document.body.click();
        }).catch(error => {
          //reject(error)
        })

      }
    }
  };
</script>

<style>
</style>
