<template>
  <div class="box">
    <div>
      <div style="margin-bottom: 10px">
        <el-form :inline="true" label-width="80px">
          <el-form-item>
            <el-input v-model="keyword"  placeholder="请输入用户姓名或手机号"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="search" type="success">搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-if="hasPerm('user:add')" type="primary" @click="addUser">添加用户</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" v-if="hasPerm('user:del')" @click="delAll">删除用户</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-table
            border
            :data="tableData"
            style="width: 100%"
            :height="590+'px'"
            ref="multipleTable"
            tooltip-effect="dark"
            @selection-change="handleSelectionChange">
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              prop="id"
              label="用户ID"
              width="80"></el-table-column>
<!--          <el-table-column-->
<!--              prop="userName"-->
<!--              label="用户姓名"></el-table-column>-->
          <el-table-column prop="account" label="登录名"></el-table-column>
<!--          <el-table-column label="性别">-->
<!--            <template slot-scope="scope">-->
<!--              <span v-if="scope.row.male == 1">男</span>-->
<!--              <span v-else>女</span>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column prop="password" label="密码"></el-table-column>
<!--          <el-table-column-->
<!--              prop="birthday"-->
<!--              label="出生日期"></el-table-column>-->
<!--          <el-table-column-->
<!--              prop="mobile"-->
<!--              label="手机号"></el-table-column>-->
<!--          <el-table-column-->
<!--              prop="job"-->
<!--              label="职务"></el-table-column>-->
<!--          <el-table-column-->
<!--              prop="address"-->
<!--              label="住址"></el-table-column>-->
<!--          <el-table-column-->
<!--              prop="remark"-->
<!--              label="备注"></el-table-column>-->
          <el-table-column
              v-if="hasPerm('user:is')"
              label="是否启用">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.accountStatus"  :active-value="1"  :inactive-value="0" @change="handleSwitch($event, scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" v-if="hasPerm('user:edit')" size="mini" style="margin-right: 10px;" @click="edit(scope.row)">编辑</el-button>
              <el-dropdown>
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <el-popconfirm
                        title=" 确定要删除这个用户吗？"
                        @confirm="del(scope.row)"
                    >
                      <el-button type="text" v-if="hasPerm('user:del')" size="mini" slot="reference">删除</el-button>
                    </el-popconfirm>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button type="text" @click="handleFarm(scope.row)" size="mini" >分配牧场</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <table-footer
            :totals="total"
            :size="size"
            @sizeChange="sizeChange"
            @pageChange="pageChange"></table-footer>

      </div>
    </div>
    <el-dialog
        :title="showType ? '编辑用户' : '新增用户'"
        :visible.sync="dialogVisible"
        width="50%">
      <div>
        <el-form ref="form" :model="forms" label-width="80px" :rules="rules">
          <el-form-item label="登录名" prop="account">
            <el-input v-model="forms.account" placeholder="默认手机号为登录名，如没有填写手机号则是用户姓名为登录名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="account">
            <el-input type="password" v-model="forms.password" ></el-input>
          </el-form-item>
<!--          <el-form-item label="性别">-->
<!--            <el-radio-group v-model="forms.male">-->
<!--              <el-radio :label="0">女</el-radio>-->
<!--              <el-radio :label="1">男</el-radio>-->
<!--            </el-radio-group>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="出生日期">-->
<!--            <el-date-picker type="date" placeholder="选择日期" v-model="forms.birthday" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="手机号">-->
<!--            <el-input v-model="forms.mobile" placeholder="默认手机号为登录名，如没有填写手机号则是用户姓名为登录名"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="住址">-->
<!--            <el-input v-model="forms.address"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="职务">-->
<!--            <el-input v-model="forms.job"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="描述">-->
<!--            <el-input v-model="forms.remark"></el-input>-->
<!--          </el-form-item>-->
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
                <el-button @click="reset">取 消</el-button>
                <el-button type="primary" @click="onSubmit('form')">{{showType ? '更 新' : '新 增'}}</el-button>
              </span>
    </el-dialog>
    <el-dialog
        title="牧场分配"
        :visible.sync="dialogFarm"
        width="50%">
      <div>
        <el-table
            :data="farmList"
            ref="multipleTable"
            tooltip-effect="dark"
            @selection-change="handleFarmChange">
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              prop="id"
              label="牧场id">
          </el-table-column>
          <el-table-column
              prop="farmName"
              label="牧场名称">
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
                <el-button @click="dialogFarm = false">取 消</el-button>
                <el-button type="primary" @click="farmSave">保存</el-button>
              </span>
    </el-dialog>
  </div>
</template>

<script>
import TableFooter from '../../components/TableFooter';
import {getUserList, addUser, editUser, isUser, delUser,} from '../../utils/api';
import { mapState } from 'vuex';
export default {
  name: "UserAdmin",
  components: {
    TableFooter
  },
  computed: {
    ...mapState(['farmList'])
  },
  data() {
    return {
      dialogVisible: false,
      showType: false,
      keyword: '',
      tableData: [],
      total: 0,
      size: 20,
      pageNum: 1,
      forms: {
        account: '',
        password: '',
        remark: '',
        mobile: '',
        male: 0,
        job: '',
        birthday: '',
        address: '',
        id: ''
      },
      selectList: '',
      rules: {
        userName: [ { required: true, message: '请输入用户姓名', trigger: 'blur' },]
      },
      dialogFarm: false,
      // farmList: [],
      // 选中牧场的id
      selectFarm: '',
    };
  },
  created() {
  },
  methods: {
    // 搜索
    search() {
      this.init();
    },
    // 修改size
    sizeChange(val) {
      this.size = val;
      this.init();
    },
    // 修改页数
    pageChange(val) {
      this.pageNum= val;
      this.init();
    },
    // 初始化
    init() {
      let params = {
        pageNum: this.pageNum,
        pageSize: 100,
        searchStr: this.keyword
      };
      getUserList(params)
          .then(res => {
            if(res.code === 10000) {
              this.tableData = res.data.records;
              this.total = res.data.total;
            } else {
              this.$message(res.message);
            }
          })
    },
    // getFarm() {
    //   getFarm().then(res => {
    //     console.log(res)
    //     if(res.code === 10000) {
    //       this.farmList = res.data;
    //     }
    //   })
    // },
    // 添加用户
    addUser() {
      this.dialogVisible = true;
      this.showType = false;
    },
    // 用户编辑
    edit(data) {
      this.forms =  {
        account: data.account,
        password: data.password,
        remark: data.remark,
        mobile: data.mobile,
        male: parseInt(data.male),
        job: data.job,
        birthday: data.birthday,
        address: data.address,
        id: data.id
      };
      this.forms.userId = data.userId;
      this.showType = true;
      this.dialogVisible = true;
    },
    // 用户删除
    del(data) {
      delUser( {userIds: data.id})
          .then(res => {
            if(res.code === 10000) {
              this.init();
              this.$message.success(res.message);
            } else {
              this.$message.error(res.message);
            }
          })
    },
    // 保存
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.showType) {
            let params = {};
            params.account = this.forms.account;
            params.password = this.forms.password;
            params.male = this.forms.male;
            params.birthday = this.forms.birthday;
            params.mobile = this.forms.mobile;
            params.address = this.forms.address;
            params.job = this.forms.job;
            params.remark = this.forms.remark;
            params.id = this.forms.id;
            params.userId = this.forms.userId;
            editUser(params)
                .then(res => {
                  if(res.code === 10000) {
                    this.init();
                    this.$message.success(res.message);
                  } else {
                    this.$message.error(res.message);
                  }
                  this.reset();
                })
          } else {
            let params = {};
            params.account = this.forms.account;
            params.password = this.forms.password;
            params.male = this.forms.male;
            params.birthday = this.forms.birthday;
            params.mobile = this.forms.mobile;
            params.address = this.forms.address;
            params.job = this.forms.job;
            params.remark = this.forms.remark;
            addUser(params)
                .then(res => {
                  if(res.code === 10000) {
                    this.init();
                    this.$message.success(res.message);
                  } else {
                    this.$message.error(res.message);
                  }
                  this.reset();
                })
          }
          this.dialogVisible = false;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 重置
    reset() {
      this.forms = {
        account: '',
        password: '',
        remark: '',
        mobile: '',
        male: '',
        job: '',
        birthday: '',
        address: '',
        id: ''
      };
      this.pageNum = 1;
      this.keyword = '';
      this.dialogVisible = false;
      this.showType = false;
    },
    // 选择
    handleSelectionChange(val) {
      let arr = [];
      val.forEach(item => {
        arr.push(item.id);
      });
      this.selectList = arr.join(',');
    },
    // 批量删除
    delAll() {
      if(this.selectList) {
        this.$confirm('此操作将永久删除批量删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delUser( {userIds: this.selectList})
              .then(res => {
                if(res.code === 10000) {
                  this.init();
                  this.selectList = '';
                  this.$message.success(res.message);
                } else {
                  this.$message.error(res.message);
                }
              })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      } else {
        this.$alert('请先选择批量删除的用户！');
      }
    },
    // 是否启用
    handleSwitch(val, data) {
      let accountStatus = '';
      if(val) {
        accountStatus = 1;
      } else {
        accountStatus = 0;
      }
      isUser( {ids: data.id, status: accountStatus})
          .then(res => {
            if(res.code ===  10000) {
              this.$message.success(res.message);
            } else {
              this.$message.error(res.message);
            }
          })
    },
    // 打开分配牧场
    handleFarm(data) {
      this.dialogFarm = true;
      this.selectId = data.id;
      if(data.farmIds === null) {
        this.$nextTick(() => {
          this.$refs.multipleTable.clearSelection();
          this.$forceUpdate();
        });
      } else {
       let arr = data.farmIds.split(',');
        this.$nextTick(() => {
          this.$refs.multipleTable.clearSelection();
          for (let key in this.farmList) {
            for(let i in arr) {
              if(this.farmList[key]['id'] == arr[i]) {
                this.$refs.multipleTable.toggleRowSelection(this.farmList[key], true);
              }
            }
          }
        })
      }

    },
    // 选择牧场
    handleFarmChange(val) {
      let arr = [];
      val.forEach(item => {
        arr.push(item.id);
      });
      this.selectFarm = arr.join(',');
    },
    // 牧场保存
    farmSave() {
      let params = {
        id: this.selectId,
        farmIds: this.selectFarm
      }
      editUser(params).then(res => {
        this.dialogFarm = false;
        this.selectFarm = '';
        this.selectId = '';
        if(res.code === 10000) {
          this.$message.success('绑定成功！');
          this.init();
        } else {
          this.$message.error('绑定失败！');
        }
      })
    }
  },
  mounted() {
    this.init();
    // 获取牧场列表
    // this.getFarm();
  }
}
</script>

<style scoped>
.box {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 20px;
}
</style>
