<template>
<div class="app-container calendar-list-container">
  <div class="filter-container">
    <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="姓名或账户" v-model="listQuery.name"> </el-input>
    <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
    <el-button class="filter-item"  v-if="userManager_btn_add"  style="margin-left: 10px;" @click="handleCreate" type="primary" icon="edit">添加</el-button>
  </div>
  <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">
    <el-table-column align="center" label="序号" width="65"> <template scope="scope">
          <span>{{scope.row.id}}</span>
        </template> </el-table-column>
    <el-table-column width="200" align="center" label="姓名"> <template scope="scope">
        <span>{{scope.row.name}}</span>
      </template> </el-table-column>
    <el-table-column width="110" align="center" label="账户"> <template scope="scope">
            <span>{{scope.row.username}}</span>
          </template> </el-table-column>
    <el-table-column width="110" align="center" label="性别"> <template scope="scope">
            <span>{{scope.row.sex}}</span>
          </template> </el-table-column>
    <el-table-column width="300" align="center" label="备注"> <template scope="scope">
            <span>{{scope.row.description}}</span>
          </template> </el-table-column>
    <el-table-column width="180" align="center" label="最后时间"> <template scope="scope">
          <span>{{scope.row.updTime}}</span>
        </template> </el-table-column>
    <el-table-column width="200" align="center" label="最后更新人"> <template scope="scope">
            <span>{{scope.row.updName}}</span>
          </template> </el-table-column>
    <el-table-column align="center" label="操作" width="150"> <template scope="scope">
        <el-button v-if="userManager_btn_edit" size="small" type="success" @click="handleUpdate(scope.row)">编辑
        </el-button>
        <el-button v-if="userManager_btn_del" size="small" type="danger" @click="handleDelete(scope.row)">删除
        </el-button>
      </template> </el-table-column>
  </el-table>
  <div v-show="!listLoading" class="pagination-container">
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
  </div>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
    <el-form :model="form" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="账户" prop="username">
        <el-input v-if="dialogStatus == 'create'" v-model="form.username" placeholder="请输入账户"></el-input>
        <el-input v-else v-model="form.username" placeholder="请输入账户" readonly></el-input>
      </el-form-item>
      <el-form-item v-if="dialogStatus == 'create'" label="密码" placeholder="请输入密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-select class="filter-item" v-model="form.sex" placeholder="请选择">
          <el-option v-for="item in  sexOptions" :key="item" :label="item" :value="item"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否开启" prop="status">
        <el-radio-group class="filter-item" v-model.number="form.status" >
          <el-radio v-for="item in statusOptions" :key="item.val" :label="item.id">{{item.val}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="所属片区" prop="zoneId">
        <el-select class="filter-item" v-model="form.zoneId" placeholder="请选择">
          <el-option v-for="(val, key, index) in getAllZone()" :key="val.code" :label="val.val" :value="val.code"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属分公司" prop="companyId">
        <el-select class="filter-item" v-model="form.companyId" placeholder="请选择分公司">
          <el-option v-for="item in allCompanies" :key="item.id" :label="item.name" :value="item.id"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属角色" prop="groupId">
        <el-select v-model="form.members" multiple filterable remote placeholder="请选择角色" :remote-method="remoteGroupsMethod" :loading="loading">
          <el-option v-for="item in myGroups" :key="item.id" :label="item.name" :value="item.id"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据权限" prop="dataState">
        <el-checkbox-group v-model="form.dataLimit" >
          <el-checkbox  v-for="item in dataOptions"  :label="item.id" :key="item">{{item.val}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="描述">
        <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 5}" placeholder="请输入内容" v-model="form.description"> </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel('form')">取 消</el-button>
      <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
      <el-button v-else type="primary" @click="update('form')">确 定</el-button>
    </div>
  </el-dialog>
</div>
</template>

<script>
import{
  page,
  addObj,
  getObj,
  delObj,
  putObj,
  insertGroups
} from 'api/admin/appUser/index';

import { mapGetters } from 'vuex';

import {
  getAllCompany
} from 'api/base_info/branch_company/';

import {
  getAllZone
} from 'api/base_info/constant/';

import {
  fetchTree,
  getAppUserGroups
} from 'api/admin/group/index';

export default {
  name: 'appUser',
  data() {
    return {
      form: {
        id: undefined,
        username: undefined,
        name: undefined,
        sex: '男',
        status: 1,
        zoneId: undefined,
        companyId: undefined,
        password: undefined,
        description: undefined,
        dataLimit: [],
        members: [],
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入用户',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        username: [
          {
            required: true,
            message: '请输入账户',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 5,
            max: 20,
            message: '长度在 5 到 20 个字符',
            trigger: 'blur'
          }
        ],
        status: [
          {
            type: 'integer',
            required: true,
            message: '请选择',
            trigger: 'blur'
          }
        ],
        zoneId: [
          {
            type: 'integer',
            required: true,
            message: '请选择',
            trigger: 'blur'
          }
        ],
      },
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined
      },
      sexOptions: ['男', '女'],
      zoneOptions: ['男', '女'],
      dataOptions: [{id:"1", val:"所属分公司"}, {id:"2", val:"所属片区"}, {id:"3", val:"所有数据"}],
      statusOptions: [{id:1, val: '开启'}, {id:2, val: '禁用'}],
      dialogFormVisible: false,
      dialogStatus: '',
      userManager_btn_edit: false,
      userManager_btn_del: false,
      userManager_btn_add: false,
      allCompanies: {},
      myGroups: [],
      loading: false,
      textMap: {
        update: '编辑',
        create: '创建'
      },
      tableKey: 0
    }
  },
  created() {
    this.getList();
    getAllCompany(codeAndBranchCompany => {
      this.allCompanies = codeAndBranchCompany;
    });
    // getCurrentGroups().then(result => {
    //   this.myGroups = result.data;
    //   const mems = [];
    //   for (let i = 0; i < result.data.length; i++) {
    //     mems.push(result.data[i].id);
    //   }
    //   this.members = mems;
    // });
    this.userManager_btn_edit = this.elements['appUserManager:btn_edit'];
    this.userManager_btn_del = this.elements['appUserManager:btn_del'];
    this.userManager_btn_add = this.elements['appUserManager:btn_add'];
  },
  computed: {
    ...mapGetters([
      'elements'
    ])
  },
  methods: {
    getAllZone,
    remoteGroupsMethod(query) {
      if (query !== '') {
        this.loading = true;
        this.loading = false;
        fetchTree({
          name: query
        }).then(response => {
          this.myGroups = response;
          // this.total = response.data.total;
          this.loading = false;
        });
      } else {
        this.myGroups = [];
      }
    },
    getList() {
      this.listLoading = true;
      page(this.listQuery)
        .then(response => {
          this.list = response.data.rows;
          this.total = response.data.total;
          this.listLoading = false;
        })
    },
    handleFilter() {
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
    },
    handleUpdate(row) {
      this.resetTemp();
      getObj(row.id)
        .then(response => {
          this.form.id = response.data.id;
          this.form.username = response.data.username;
          this.form.name = response.data.name;
          this.form.sex = response.data.sex;
          this.form.status = response.data.status;
          this.form.zoneId = response.data.zoneId;
          this.form.companyId = response.data.companyId;
          this.form.password = response.data.password;
          this.form.description = response.data.description;
          this.form.dataLimit = response.data.dataLimit;
          let dataLimit = new Array();
          if(response.data.dataCompany != undefined&& response.data.dataCompany != '') {
            let companys = response.data.dataCompany.split(",");
            if(companys.includes(response.data.companyId + "")) {
              dataLimit.push("1");
            }
          }
          if(response.data.dataZone != undefined && response.data.dataZone != '') {
            let zones = response.data.dataZone.split(",");
            if(zones.includes(response.data.zoneId + "")) {
              dataLimit.push("2");
            }
          }
          if(response.data.dataAll != undefined && response.data.dataAll == 1) {
            dataLimit.push("3");
          }
          this.$set(this.form, "dataLimit", dataLimit);

          getAppUserGroups(response.data.id).then(result => {
            this.myGroups = result;
            // debugger;
            let mems = [];
            for (let i = 0; i < result.length; i++) {
              mems.push(result[i].id);
            }
            this.form.members = mems;
          });

          this.dialogFormVisible = true;
          this.dialogStatus = 'update';
        });
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delObj(row.id)
            .then(() => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              });
              const index = this.list.indexOf(row);
              this.list.splice(index, 1);
            });
        });
    },
    create(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          addObj(this.form)
            .then(() => {
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              });
            })
        } else {
          return false;
        }
      });
    },
    cancel(formName) {
      this.dialogFormVisible = false;
      this.$refs[formName].resetFields();
    },
    update(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false;
          this.form.password = undefined;
          putObj(this.form.id, this.form).then(() => {
            insertGroups({
              appUserId: this.form.id,
              groups: this.form.members
            }).then(() => {
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              });
            });
          });
        } else {
          return false;
        }
      });

    },
    resetTemp() {
      this.form = {
        username: undefined,
        name: undefined,
        sex: '男',
        status: 1,
        zoneId: undefined,
        companyId: undefined,
        password: undefined,
        description: undefined,
        dataLimit: [],
        members: [],
      };
    },
    // initGroups() {
    //   getUsers(this.groupId).then(response => {
    //     this.lItems = response.data.leaders;
    //     this.mItems = response.data.members;
    //     const mems = [], leas = [];
    //     for (let i = 0; i < response.data.members.length; i++) {
    //       mems.push(response.data.members[i].id);
    //     }
    //     for (let i = 0; i < response.data.leaders.length; i++) {
    //       leas.push(response.data.leaders[i].id);
    //     }
    //     this.members = mems;
    //     this.leaders = leas;
    //   });
    // }
  }
}
</script>
