<template>
  <div class="global">
    <div class="mainContainer">
      <div class="title">
        {{pageTitle}}
        <el-button v-if="isDetail" type="success" plain @click="edit()" style="float:right">编辑</el-button>
      </div>
      <div class="main">
        <div class="top">
            <el-form  :inline="true"  :model="user"   class="demo-form-inline" ref="userData" label-width="100px"  :rules="rules">
              <el-col :span="18">
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="用户名:" prop="uName">
                      <el-input v-model="user.uName" :disabled="isDetail" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" v-if="isAdd">
                    <el-form-item label="密码:" prop="uPassword">
                      <el-input v-model="user.uPassword" type="password" :disabled="isDetail" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8"  v-if="isAdd">
                    <el-form-item label="确认密码:" prop="confirmPassword">
                      <el-input v-model="user.confirmPassword"  type="password" :disabled="isDetail" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-col :span="8" style="margin-top:60px">
                  <el-form-item label="所属公司:" prop="depotName">
                    <el-input v-model="user.depotName" :disabled="isdis" style="width:240px"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8" style="margin-top:60px">
                  <el-form-item label="人员名称:" prop="personnelId">
                    <el-select v-model="user.personnelId" placeholder="请选择" @change="personnelIdClick"  :disabled="isDetail">
                      <el-option
                        v-for="item in personList"
                        :key="item.personnelId"
                        :label="item.personnelName"
                        :value="item.personnelId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8" style="margin-top:60px">
                  <el-form-item label="职位:" prop="ppost">
                    <el-input v-model="user.ppost" :disabled="isdis" />
                  </el-form-item>
                </el-col>
              </el-col>
              <el-col :span="6">
                <el-form-item>
                    <img :src="imageUrl" class="avatar">
                  </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="角色组:" prop="roleIds">
                    <div class="roleClass" style="border:1px solid #ccc;padding:15px;width:1200px ">
                      <el-radio :disabled="isDetail" v-model="user.roleIds" v-for="item in roleList" :key="item.roleCode" :label="item.roleCode">{{item.roleName}}</el-radio>
                      <!-- <el-checkbox-group v-model="roleCheckList"  :disabled="isDetail">
                        <el-checkbox v-for="item in roleList" :key="item.roleCode" :label="item.roleCode">{{item.roleName}}</el-checkbox>
                      </el-checkbox-group> -->
                    </div>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="depotId && depotId != 1">
                <el-form-item label="仓房:" prop="houseCheckList">
                    <div style="border:1px solid #ccc;padding:15px ">
                      <el-checkbox-group v-model="user.houseCheckList"  :disabled="isDetail">
                        <el-checkbox v-for="item in houseList" :key="item.houseCode" :label="item.houseCode">{{item.houseName}}</el-checkbox>
                      </el-checkbox-group>
                    </div>
                </el-form-item>
              </el-col>
              <el-col :span="24"  v-if="depotId && depotId != 1">
                <el-form-item label="首页类型:" prop="homeType">
                    <el-radio-group v-model="user.homeType" class="theme-radio">
                      <el-radio v-for="item in themeData" :key="item.value" :label="item.value"  :disabled="isDetail">
                        <img class="themeImg" :src="item.imgsrc"/>{{item.text}}
                      </el-radio>
                    </el-radio-group>
                </el-form-item>
              </el-col>
            </el-form>
        </div>

        <div class="btns">
          <el-button type="success" plain @click="cancel()">返回</el-button>
          <el-button type="success"  v-if="!isDetail" @click="btnSave('userData')">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getAllPerson,getPersonById,getAllRole,getDepotAll,getWarehouseAll,unameExit } from '@/api/system/userManagement/user.js'
import Vue from 'vue'
import {addFun,updateFun,detailFun} from '@/api/system/userManagement/user'
import { getUser } from '@/utils/auth'
import theme1 from '../../../../assets/images/company.png'
import theme2 from '../../../../assets/images/storehouseDirector.png'
import theme3 from '../../../../assets/images/staff.png'
export default {
  name: 'AddUser',
  data() {
    const checkUname = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入用户名'))
      } else {
        if(value == this.copyUname){
          callback()
        }else{
          unameExit(value).then((res) => {
            if (res.code == 200) {
              if (res.data > 0) {
                callback(new Error('该用户名已存在'))
              } else {
                callback()
              }
            } else {
              callback(new Error(res.msg))
            }
          })
        }
      }
    }
    const validatePass = (rule, value, callback) => {
      if(value){
          if (value.length < 6 || value.length > 14) {
            callback(new Error('密码长度6-14位，必须有数字和字母'))
          } else {
            callback()
          }
      }else{
        callback(new Error('请输入密码'))
      }
    }
    const validateCheckPass = (rule, value, callback) => {
      if(value){
        if (value !== this.user.uPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }else{
        callback(new Error('请再次输入密码'))
      }
    }
    return {
      personList:[],
      roleList:[],
      depotIdList:[],
      houseList:[],
      isdis: true,
      isDetail: false,
      imageUrl: '',
      houseCheckList: [],
      user: {
        uName:'', //用户名
        uPassword:'', //密码
        confirmPassword: '',
        depotName:'', //所属公司
        personnelName:'', //人员名称
        personnelId:'', //人员id
        roleIds:'', //角色id
        houseCheckList: [],
        storehouseIds:'', //仓房id
        ppost:'', //职位
        homeType: null,
      },
      // 验证规则
      rules: {
        uName: [
          {
            required: true,
            trigger: 'blur',
            validator: checkUname
          }
        ],
        uPassword: [
          {
            required: true,
            trigger: 'blur',
            validator: validatePass
          }
        ],
        confirmPassword: [
          {
            required: true,
            trigger: 'blur',
            validator: validateCheckPass
          }
        ],
        personnelId: [
          {
            required: true,
            message: '请选择人员',
            trigger: 'change'
          }
        ],
        roleIds: [
          {
            required: true,
            message: '请选择角色组',
            trigger: 'change'
          }
        ],
        homeType: [
          {
            required: true,
            message: '请选择首页类型',
            trigger: 'change'
          }
        ],
        houseCheckList: [
          {
            required: true,
            message: '请选择仓房',
            trigger: 'change'
          }
        ],
      },
      isAdd: false,
      isEdit: false,
      depotId: '',
      themeData: [
        {"imgsrc": theme2, "text": "库主任及以上领导首页", "value": 2},
        {"imgsrc": theme3, "text": "员工首页", "value": 3},
      ],
      copyUname:'',
      pageTitle:''
    }
  },
  created() {
    this.getPersonList()
    this.getRoleList()
    this.getWarehouseAllList()
    this.$nextTick(() => {
    if (this.$route.query.state == 'add') {
      this.reast()
      this.pageTitle = '新增用户'
      this.user.depotName = this.$route.query.depotName
      this.depotId = this.$route.query.depotId
      this.isAdd = true
    }
    if (this.$route.query.state == 'edit') {
      this.reast()
      this.pageTitle = '编辑用户'
      this.isEdit = true
      this.detailInfo()
    }
    if (this.$route.query.state == 'detail') {
      this.reast()
      this.pageTitle = '查看用户'
      this.isDetail = true
      this.detailInfo()
    }
    })
    
  },
  mounted() {},
  methods: {
    getPersonList() {
      let depotId = this.$route.query.depotId
      getAllPerson(depotId).then(res => {
        this.personList = res.data
      })
    },
    getRoleList() {
      getAllRole().then(res => {
        this.roleList = res.data
      })
    },
    personnelIdClick() {
      this.personList.forEach(item => {
        if(item.personnelId == this.user.personnelId){
          this.user.personnelName = item.personnelName
          // this.user.depotName = item.depotName
        }
      })
      getPersonById(this.user.personnelId).then(res => {
        this.user.ppost = res.data.ppost
        this.imageUrl = `http://101.36.160.140:21021/api/csc-szls-system-manage/minio/preViewPicture/${res.data.pheadPortrait}` 
      })
    },
    getWarehouseAllList() {
      getWarehouseAll(this.$route.query.depotId).then(res => {
        this.houseList = res.data
      })
    },

    addList() {
      addFun(this.user).then(res => {
        if (res.code == 200) {
          this.$message.success('新增成功')
          this.$router.push({ 
            path: '/systemManagement/user/userManagement',
            query: {
              name:'UserManagement'
            }
          })
          this.reast()
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    updateList() {
      updateFun(this.user).then(res => {
        if (res.code == 200) {
          this.$message.success('修改成功')
          this.$router.push({ 
            path: '/systemManagement/user/userManagement',
            query: {
              name:'UserManagement'
            }
          })
          this.reast()
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    detailInfo() {
      detailFun(this.$route.query.id).then(res => {
        if (res.code == 200) {
          this.depotId = res.data.depotId
          res.data.uName = res.data.uname
          this.user = res.data
          this.copyUname = res.data.uname
          this.user.personnelId = res.data.personnelId.toString()
          if(this.user.storehouseIds){
            this.user.houseCheckList = this.user.storehouseIds.split(',')
          }else{
            this.user.houseCheckList = []
          }
          getPersonById(this.user.personnelId).then(res => {
            this.user.ppost = res.data.ppost
            this.user.depotName = res.data.depotName
            this.imageUrl = `http://101.36.160.140:21021/api/csc-szls-system-manage/minio/preViewPicture/${res.data.pheadPortrait}` 
          })
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    btnSave(formName) {
      if(this.depotId == 1){
        this.user.homeType = 1
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.user.personnelId = Number(this.user.personnelId)
          if(this.user.houseCheckList.length>0){
            this.user.storehouseIds = this.user.houseCheckList.join(',')
          }else{
            this.user.storehouseIds = ''
          }
          console.log(this.user)
          if (this.$route.query.state == 'add') {
            this.addList()
          } else if (this.$route.query.state == 'edit') {
            this.updateList()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancel() {
      this.reast()
      this.$router.push({ 
        path: '/systemManagement/user/userManagement',
        query: {
          name:'UserManagement'
        }
      })
    },
    reast() {
      // 对表单进行重置
        this.$refs['userData'].resetFields()
        this.user = {
          uName:'', //用户名
          uPassword:'', //密码
          confirmPassword: '',
          depotName:'', //所属公司
          personnelName:'', //人员名称
          personnelId:'', //人员id
          roleIds:'', //角色id
          houseCheckList:[],
          storehouseIds:'', //仓房id
          ppost:'', //职位
          homeType: null,
        }
    },
    edit() {
      this.pageTitle = '编辑用户'
      this.isEdit = true
      this.isDetail = false
    }
  }
}
</script>
<style lang="scss" scoped>
.mainContainer {
  position: relative;
  .title {
    margin-bottom: 20px;
  }
  .main {
    padding: 20px 30px;
  }
  .top {
    display: flex;
    .top_left {
      width: 60%;
      .el-form--inline .el-form-item {
        width: 45%;
        margin-bottom: 40px;
      }
    }
    .top_right {
      width: 40%;
      text-align: center;

      .imageBtn {
        margin-top: 10px;
      }
    }
  }
  .middle,
  .bottom_warehouse {
    margin: 20px 0;
    display: flex;
    align-items: center;

    .check_div {
      width: 1200px;
      height: 100px;
      display: flex;
      padding-left: 20px;
      align-items: center;
      border: 1px solid #ccc;
    }
  }
  .bottom_warehouse {
    .warehouse_div {
      width: 1200px;

      .checkGroup
      {
        max-height: 70px;
        overflow-y: scroll;
      }

    }
  }
  .warehouse,
  .roleGroup {
    width: 100px;
    text-align: right;
    margin-right: 20px;
    white-space: nowrap;
  }
  .btns {
    text-align: right;
  }
}
</style>
<style scoped>
.el-date-editor {
  width: 180px !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 158px;
  height: 158px;
  display: block;
}
.theme-radio .el-radio{ width: 450px; margin-bottom: 40px; line-height: 140px;}
.themeImg{ float: left; margin-right: 10px; width: 276px; height: 143px;}
</style>
