<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 style="display: flex; align-items: center;" class="searchFields">
              <el-autocomplete class="inline-input" v-model="searchFields.client" :fetch-suggestions="querySearch"
                placeholder="所在工具箱" :trigger-on-focus="true" @select="handleSelectSClient" @blur="handleSelectSClient">
              </el-autocomplete>
              <Input style="width: 200px; margin-left: 10px" v-model.number="searchFields.keyword"
                placeholder="关键词搜索" />
              <Button type="primary" @click="search" style="margin-left: 10px">查询</Button>
              <Button type="primary" @click="edit()" style="margin-left: 10px">添加用户</Button>
              <a style="margin-left: 10px" href="/res/template-user.xlsx" class="ivu-btn ivu-btn-primary"><i
                  class="ivu-icon ivu-icon-ios-download-outline"></i><span>下载模版</span></a>
              <Button icon="md-cloud-upload" style="margin-left: 10px" @click="toImport" type="primary">批量导入</Button>
            </div>
          </slot>
        </LxHeader>


      </div>
      <div ref="lxTable" class="table-tree">
        <el-table :data="tableData" class="v-table" :height="tableHeight" style="width: 100%">

          <el-table-column type="index" width="50" align="center"></el-table-column>
          <el-table-column :prop="column.field" :align="column.align" v-for="(column,index) in columns"
            :label="column.title" :width="column.width">
            <template slot-scope="scope">
              <div v-if="column.type == 'img'">
                <img v-for="(file, vIndex) in getFilePath( scope.row[column.field], column)" :key="vIndex"
                  @click="viewImg(scope.row, column, file.path)" class="table-img" :src="file.path" />
              </div>
              <div v-else-if="column.type=='format'">

                <div v-if="column.field=='client'">
                  {{scope.row[column.field]?scope.row[column.field].name:""}}
                </div>
              </div>
              <div v-else-if="column.type=='opt'">
                <el-popover ref="popoverBox" placement="left" width="400" trigger="click">
                  <div style="margin-bottom: 15px;">选择层</div>
                  <el-checkbox v-model="layer.checked" v-for="(layer,vindex) in scope.row.boxlayers" :label="layer.id"
                    :key="layer.id">
                    {{layer.layerno+"层"}}
                  </el-checkbox>
                  <div style="margin-top:15px; display: flex;justify-content: flex-end;">
                    <Button @click="setPermission(scope.row)" type="primary" ghost size="small">确认</Button>
                  </div>
                  <Button slot="reference" type="success" 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>
              </div>
              <div v-else>{{scope.row[column.field]}}</div>

            </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>

    </div>

    <el-dialog title="批量导入用户" :visible.sync="dialogImportVisible" width="60%">
      <div>
        <el-upload action="/api/admin/upload-file" :data="uploadOther" :limit="1" :on-success="handlesuccessExcel">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传xlsx文件，且不超过500kb</div>
        </el-upload>
      </div>
      <div ref="lxTable" class="table-tree">
        <el-table :data="tableExcelData" class="v-table" :height="tableHeight*0.5" style="width: 100%">
          <el-table-column :prop="column.field" :align="column.align" v-for="(column,index) in excelColumns"
            :label="column.title" :width="column.width">
            <template slot-scope="scope">
              <div>{{scope.row[column.field]}}</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleImport">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="工具箱用户编辑" :visible.sync="dialogFormVisible" width="50%">
      <el-form :model="form" :rules="rules" ref="form" label-position="right" :label-width="formLabelWidth">
        <el-row :gutter="32">
          <el-col :span="24">
            <el-form-item label="所在工具箱" prop="client">
              <el-autocomplete class="inline-input" style="width: 100%;" v-model="form.client"
                :fetch-suggestions="querySearch" placeholder="所在工具箱" :trigger-on-focus="true"
                @select="handleSelectClient" @blur="handleSelectClient">
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录名" prop="loginname">
              <el-input v-model="form.loginname" :disabled="loginnamedisabled" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否管理员">
              <el-switch v-model="form.issuperuser"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="密码" prop="loginpassword">
              <el-input v-model="form.loginpassword" type="password" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="IC卡号" prop="IC_Num">
              <el-input v-model="form.IC_Num" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="电话" prop="tel">
              <el-input v-model="form.tel" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
    listUser,
    save,
    del,
    setPermission,
    previewimport,
    doimport
  } from "../../api/toolbox/user.js"
  import {
    listToolbox
  } from "../../api/toolbox/list.js"
  import LxHeader from "@/components/LxHeader/index.vue";
  import {
    getToken
  } from '@/utils/auth'
  export default {
    components: {
      LxHeader
    },
    created() {
      this.initLoad();
      this.load();
      this.uploadOther.token = getToken();
    },
    mounted() {},
    data() {
      var validatePhone = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入通知电话'));
        } else if (!this.base.isPhone(value)) {
          callback(new Error('请输入正确通知电话'));
        } else {
          callback();
        }
      };
      return {
        loginnamedisabled: false,
        uploadOther: {
          token: ""
        },
        uploadPath: "",
        excelColumns: [{
            field: "loginname",
            title: "用户名",
            type: "string",
            width: 150
          },
          {
            field: "username",
            title: "姓名",
            type: "string",
            width: 150
          },
          {
            field: "IC_Num",
            title: "IC卡号",
            type: "string",
          },
          {
            field: "tel",
            title: "电话",
            type: "int",
            width: 120
          },
          {
            field: "client",
            title: "授权工具箱",
            type: "format",
            width: 300
          },
        ],
        tableExcelData: [],

        dialogImportVisible: false,
        paginations: {
          page: 1,
          page_size: 15,
          total: 10
        },
        rules: {
          loginname: [{
            required: true,
            message: '请输入登录名',
            trigger: 'blur'
          }],
          loginpassword: [{
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }],
          username: [{
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }],
          tel: [{
            required: true,
            validator: validatePhone,
            trigger: 'blur'
          }],
          client: [{
            required: true,
            message: '请选择工具箱',
            trigger: 'change'
          }]
        },
        tableData: [],
        dialogFormVisible: false,
        form: {
          loginname: "",
          loginpassword: "",
          username: "",
          IC_Num: "",
          tel: "",
          issuperuser: 1,
          client: "",
          client_id: ""
        },
        formLabelWidth: "120px",
        tableHeight: 0,
        //查询条件字段
        searchFields: {
          client_id: "",
          keyword: "",
          client: ""
        },
        columns: [{
            field: "loginname",
            title: "用户名",
            type: "string",
            width: 150
          },
          {
            field: "username",
            title: "姓名",
            type: "string",
            width: 150
          },
          {
            field: "IC_Num",
            title: "IC卡号",
            type: "string",
          },
          {
            field: "tel",
            title: "电话",
            type: "int",
            width: 120
          },
          {
            field: "client",
            title: "授权工具箱",
            type: "format",
            width: 300
          },
          {
            field: "opt",
            title: "操作",
            type: "opt",
            align: "center",
            width: 180
          }
        ],
      };
    },
    methods: {
      handlesuccessExcel(response, file, filelist) {
        console.log(response)
        this.uploadPath = response.path;
        previewimport({
          file_path: response.path
        }).then(res => {
          if (res.errors.length > 0) {
            this.$message.error(res.errors[0])
          } else
            this.tableExcelData = res.data;
        }).catch(error => {

        })
      },
      handleImport() {
        doimport({
          file_path: this.uploadPath
        }).then(res => {
          if (res.errors) {
            this.$message.error(res.errors.join(","))
          } else {
            this.load();
            this.dialogImportVisible = false;
          }
        }).catch(error => {

        })
      },
      toImport() {
        this.dialogImportVisible = true;
      },

      hasPermission(arr, id) {
        return arr.filter((p, i) => {
          return p.layerid == id
        }).length == 1;
      },
      search() {
        this.paginations.page = 1;
        this.load();
      },
      load() {
        let that = this;
        listUser({
          page: this.paginations.page,
          page_size: this.paginations.page_size,
          client_id: this.searchFields.client_id,
          keyword: this.searchFields.keyword
        }).then(response => {
          var data = response.data;
          this.tableData = data;
          for (var m of this.tableData) {
            let _boxlayers = JSON.parse(JSON.stringify(m.boxlayers)); //深拷贝
            for (var mod of _boxlayers) {
              let _hasPermission = that.hasPermission(m.permissions, mod.id);
              if (_hasPermission) {
                mod.checked = true;
              } else {
                mod.checked = false;
              }
            }
            m.boxlayers = _boxlayers;
          }

          this.paginations.total = response.total;
        }).catch(error => {
          //reject(error)
        })
      },
      querySearch(queryString, cb) {
        listToolbox({
          keyword: queryString,
          page_size: 999,
        }).then(response => {
          var data = response.data;
          for (var m of data) {
            m.value = m.name;
          }
          cb(data)
        }).catch(error => {
          //reject(error)
        })
      },
      handleCurrentChange(page) {
        this.paginations.page = page;
        this.load();
      },
      handleSelectSClient(item) {
        this.searchFields.client_id = item.id;
      },
      handleSelectClient(item) {
        this.form.client_id = item.id;
      },
      setPermission(obj) {
        let arr = [];
        for (var m of obj.boxlayers) {
          if (m.checked)
            arr.push(m.original_id)
        }

        var that = this;
        setPermission({
          layer_id: arr
        }, obj.id).then(response => {
          this.$Message.success('操作成功');
          that.load();
        }).catch(error => {

        })
      },
      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;
        that.tableHeight = tableHeight;
      },
      edit(obj) {
        this.form = this.$options.data().form
        if (obj) {
          var result = Object.assign(this.form, obj)
          this.form = result;
          this.form.client = obj.client.name;
          this.form.client_id = obj.client.id;
          this.form.issuperuser = obj.issuperuser == 1;
          this.loginnamedisabled = true;
        } else
          this.loginnamedisabled = false;
        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.dialogFormVisible = false;
              that.load();
            }).catch(error => {
              //reject(error)
            })
          } else {
            this.$Message.error('数据校验失败');
            return false;
          }
        });
      },
      resetForm(formName) {
        var that = this;
        this.$refs[formName].resetFields();
        that.dialogFormVisible = false;
      },
      del(obj) {
        var that = this;
        if (obj) {
          this.$Modal.confirm({
            title: '确认要删除数据？',
            onOk: () => {
              del({
                id: obj.id
              }).then(response => {
                this.$Message.success('操作成功');
                that.search();
              }).catch(error => {
                console.log(error)
                //reject(error)
              })
            },
            onCancel: () => {
              //this.$Message.info('Clicked cancel');
            }
          });
        }
      },

    }
  };
</script>

<style>
  .searchFields .el-input__inner {
    height: 32px !important;
    line-height: 32px !important;
  }
</style>
