<template>
  <el-dialog
    title="新增用户"
    width="660px"
    :visible.sync="visible"
    :before-close="_close"
  >
    <!-- <el-form :model="form" :rules="rules" ref="form" label-width="90px">
            <el-form-item label="角色名称 : " prop="name">
                <el-input v-model="form.name" placeholder="" maxlength="30" ></el-input>
            </el-form-item>
            <el-form-item label="角色描述 : " prop="intro">
                <el-input type="textarea" v-model="form.intro" placeholder="" resize="none" rows="4" ></el-input>
            </el-form-item>
    </el-form>-->
    <div class="chooseuser">
      <span style="color:#303133">选择用户：</span>
      <el-radio v-model="checked" label="1">从已有员工中选择</el-radio>
      <el-radio v-model="checked" label="2">新增员工</el-radio>
    </div>
    <div v-if="checked == '1'"   v-loading="loading" class="roleContent">
      <div class="roleContentLeft">
        <p style="color:#303133">选择：</p>
        <div class="chooseBox">
          <div>
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
            >全选
            </el-checkbox
            >
          </div>
          <el-checkbox-group
            v-model="checkedCities"
          >
            <div class="checkone" v-for="(item,index) in admin_user" :key="index">
              <el-checkbox :label="item.id" :value="item.id" @change="change">
                <img v-if="item.avatar.length > 0" :src="item.avatar" alt=""/>
                <img
                  v-if="item.avatar.length == 0"
                  src="https://kuyi.shengws.com/S1.png"
                  alt=""
                />
                <span>{{item.user_name}}</span>
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
      </div>

      <div class="roleContentRight" v-loading="loading">
        <p style="color:#303133">已选：</p>
        <div class="chooseBox">
          <div class="hasChoosedOne" v-for="(item,index) in is_check_admin_user" :key="index">
            <img v-if="item.avatar.length > 0" :src="item.avatar" alt=""/>
            <img
              v-if="item.avatar.length == 0"
              src="https://kuyi.shengws.com/S1.png"
              alt=""
            />
            <span>{{item.user_name}}</span>
          </div>
        </div>
      </div>
    </div>
    <div v-if="checked == '2'" class="newStaff">
      <el-form
        :model="ruleForm"
        :rules="newrules"
        ref="form"
        label-position="left"
      >
        <el-form-item label="姓名" prop="name" label-width="50px">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone" label-width="70px">

          <el-input  v-model="ruleForm.phone"  maxlength="11"></el-input>
        </el-form-item>

        <el-form-item label="职称 : " label-width="50px">
          <el-select v-model="ruleForm.user_type" placeholder="用户类型">
            <el-option
              v-for="item in user_types"
              :label="item.name"
              :value="item.index"
              :key="item.index"
            ></el-option>
          </el-select>

          <el-select v-model="ruleForm.user_title" placeholder="用户职称">
            <el-option
              v-for="item in user_titles"
              :label="item.name"
              :value="item.index"
              :key="item.index"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="职位" label-width="50px">
          <el-input v-model="ruleForm.position"></el-input>
        </el-form-item>
      </el-form>
      <div class="newItem">
        <p style="width:80px;text-align:right;padding-right:8px">
          <i
            class="el-icon-circle-plus"
            style="font-size:20px;color:#338AFB"
          ></i>
        </p>
        <p style="color:#409FFF" @click="continueAddStaff()">保存并继续新增员工</p>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="hide">取 消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="submitAction()">保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { addRole, AddUserRole, getStaffsList, modifyRole,getRoleInfo } from '@/api/role/role'
  import { addAdmin, getAddAdminInitData, getModifyAdminInitData, modifyAdmin } from '@/api/role/admin'

  export default {
    name: 'EditRole',
    data() {
      var checkMobile = (rule, value, callback) => {
        if (!value || value.length == 0) {
          return callback(new Error('手机号不能为空'))
        }
        if (/^1\d{10}$/.test(value) == false) {
          return callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
      var checkName = (rule, value, callback) => {
        if (!value || value.length == 0) {
          return callback(new Error('姓名不能为空'))
        } else {
          callback()
        }
      }

      return {
        org:null,
        submitLoading:false,
        loading:true,
        local_user_id:0,
        form: {
          id: 0,
          name: '',
          intro: ''
        },
        role_id: 0,
        visible: false,
        rules: {
          phone: [{ required: true, validator: checkMobile, trigger: 'blur' }],
          name: [{ required: true, validator: checkName, trigger: 'blur' }],
          intro: [{ required: true, message: '请输入角色说明', trigger: 'blur' }]
        },
        admin_user: [],
        is_check_admin_user: [],
        user_types: [
          { index: 2, name: '医生' },
          { index: 3, name: '护士' }
        ],
        user_titles: [
          { index: 1, name: '医士' },
          { index: 2, name: '医师' },
          { index: 3, name: '住院医师' },
          { index: 4, name: '主治医师' },
          { index: 5, name: '副主任医师' },
          { index: 6, name: '主任医师' },
          { index: 7, name: '护士' },
          { index: 8, name: '护师' },
          { index: 9, name: '主管护师' },
          { index: 10, name: '副主任护师' },
          { index: 11, name: '主任护师' },
          { index: 12, name: '运营专员' },
          { index: 13, name: '运营主管' }
        ],
        //
        checked: '1',
        checkAll: false,
        checkedCities: [],
        isIndeterminate: true,
        ruleForm: {
          name: '',
          phone: '',
          position: '',
          user_type: 2,
          user_title: 1,
          role: ''
        },
        newrules: {
          phone: [{ required: true, validator: checkMobile, trigger: 'blur' }],

          name: [
            { required: true, message: '请输入用户名字', trigger: 'blur' },
            { max: 10, message: '10个字以内', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      continueAddStaff(){
        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.form.id === 0) {
              this.ruleForm.role = this.role_id
              addAdmin(
                this.ruleForm.phone,
                this.ruleForm.name,
                this.ruleForm.user_type,
                this.ruleForm.user_title,
                this.ruleForm.role,
                '',
                this.ruleForm.position
              )
                .then(rs => {
                  var resp = rs.data
                  if (resp.state === 1) {
                    this.$store.dispatch('DidChangeAdmins')
                    var _this = this
                    setTimeout(() => {
                      _this.$store.dispatch('RecoverAdminsChangeState')
                    }, 500)
                    this.$emit('did-edit-role')
                    this.ruleForm.phone = ''

                    this.ruleForm.name = ''
                    this.ruleForm.user_type = 2
                    this.ruleForm.user_title = 1
                    this.ruleForm.role = ''
                    this.ruleForm.position = ''
                  } else {
                    this.$message.error(resp.msg)
                  }
                })
                .catch(err => {
                  this.loading = false
                  this.$message.error(err)
                })
            }
          } else {
            return false
          }
        })



      },
      change(val) {
        if (this.checkedCities.length == this.admin_user.length) {
          this.checkAll = true
        } else {
          this.checkAll = false
        }
      },
      GetAllStaff: function() {
        getStaffsList()
          .then(rs => {
            var resp = rs.data
            if (resp.state === 1) {
              this.admin_user = resp.data.admins
              this.org = resp.data.org
              this.isSubSuperAdmin = resp.data.isSubSuperAdmin;

              for (let i = 0; i < this.admin_user.length; i++) {
                if (this.admin_user[i].role_ids.length > 0) {
                  let isExist = -1
                  let ids = this.admin_user[i].role_ids.split(',')
                  isExist = ids.indexOf(this.role_id.toString())
                  if (isExist >= 0) {
                    this.is_check_admin_user.push(this.admin_user[i])
                    this.admin_user.splice(i, 1)
                    i = i - 1
                  }
                }
              }
              console.log(this.admin_user)


              for (let i = 0; i < this.admin_user.length; i++) {
                if (this.isSubSuperAdmin) { //如果当前用户是子管理员,则将管理员剔除到待添加员工列表
                  console.log(this.admin_user[i].user_id)
                  console.log(this.org.creator)

                  if (this.admin_user[i].user_id == this.org.creator) {
                    this.admin_user.splice(i, 1);
                    i = i - 1;
                  } else {
                    if (this.admin_user[i].is_sub_admin && this.admin_user[i].user_id != this.local_user_id) {
                      this.admin_user.splice(i, 1);
                      i = i - 1;
                    }
                  }
                } else { //如果当前用户是超级管理员，而且当前编辑角色是子管理员的话，需要将超级管理员剔除到待添加员工列表
                  if (this.role.name == "子管理员" && this.role.is_system == 1) {
                    if (this.admin_user[i].user_id == this.org.creator) {
                      this.admin_user.splice(i, 1);
                      i = i - 1;
                    }
                  }
                }
              }



              this.loading = false

            } else {
              this.$message.error(resp.msg)
              this.loading = false

            }
          })
          .catch(err => {
            this.$message.error(err)
          })

      },
      _close: function(done) {
        this.clear()
        done()
      },
      clear: function() {
        this.form.id = 0
        this.form.name = ''
        this.form.intro = ''
      },
      show(role_id) {
        this.clear()
        this.loading = true
        this.checked = '1'
        this.visible = true
        this.role_id = role_id
        this.admin_user = []
        this.is_check_admin_user = []
        this.checkedCities = []
        this.local_user_id = this.$store.getters.xt_user.user.id

        this.getRoleInfo(role_id)
      },getRoleInfo(id){
        let params = {
          role_id: id
        }
        getRoleInfo(params)
          .then(rs => {
            var resp = rs.data
            if (resp.state === 1) {
              this.role = resp.data.role
              this.loading = true
              this.GetAllStaff()


            } else {
              this.$message.error(resp.msg)

            }
          })
          .catch(err => {
            this.$message.error(err)
          })



      }, hide() {
        this.clear()
        this.visible = false
      },
      modify(id, name, intro) {
        this.form.id = id
        this.form.name = name
        this.form.intro = intro
        this.visible = true
      },
      submitAction() {
        if (this.checked == '1') {
          if (this.checkedCities.length == 0) {
            this.$message.error('至少选择一个用户')
            return
          }
          let params = {
            id: this.role_id,
            ids: this.checkedCities.join(',')
          }
          this.submitLoading = true

          AddUserRole(params).then(response => {
            if (response.data.state === 1) {
              this.$message.success('添加成功')
              this.$emit('did-edit-role')
              this.hide()
              this.submitLoading = false

            } else {
              this.submitLoading = false

              this.$message.error(response.data.msg)

            }
          }).catch(e => {
            this.submitLoading = false


          });
        } else {
          this.$refs.form.validate(valid => {
            if (valid) {
              this.submitLoading = true
              if (this.form.id === 0) {
                this.ruleForm.role = this.role_id
                addAdmin(
                  this.ruleForm.phone,
                  this.ruleForm.name,
                  this.ruleForm.user_type,
                  this.ruleForm.user_title,
                  this.ruleForm.role,
                  '',
                  this.ruleForm.position
                )
                  .then(rs => {
                    this.submitLoading = false

                    var resp = rs.data
                    if (resp.state === 1) {

                      this.$store.dispatch('DidChangeAdmins')
                      var _this = this
                      setTimeout(() => {
                        _this.$store.dispatch('RecoverAdminsChangeState')
                      }, 500)
                      this.$emit('did-edit-role')
                      this.hide()

                      this.ruleForm.phone = ''
                      this.ruleForm.name = ''
                      this.ruleForm.user_type = 2
                      this.ruleForm.user_title = 1
                      this.ruleForm.role = ''
                      this.ruleForm.position = ''
                    } else {
                      this.$message.error(resp.msg)
                    }
                  })
                  .catch(err => {
                    this.submitLoading = false

                    this.loading = false
                    this.$message.error(err)
                  })
              }
            } else {
              this.submitLoading = false
              return false
            }
          })

        }

        // this.$refs.form.validate(valid => {
        //   if (valid) {
        //     // 验证通过
        //     if (this.form.id === 0) {
        //       // 新增 role
        //       addRole(this.form.name, this.form.intro)
        //         .then(rs => {
        //           var resp = rs.data;
        //           if (resp.state === 1) {
        //             var new_id = resp.data.id;
        //             var new_name = resp.data.name;
        //             var new_intro = resp.data.intro;
        //             var new_status = resp.data.status;
        //             this.$emit(
        //               "did-add-role",
        //               new_id,
        //               new_name,
        //               new_intro,
        //               new_status
        //             );
        //
        //             this.hide();
        //           } else {
        //             this.$message.error(resp.msg);
        //           }
        //         })
        //         .catch(err => {
        //           this.$message.error(err);
        //         });
        //     } else {
        //       // 修改 role
        //       modifyRole(this.form.id, this.form.name, this.form.intro)
        //         .then(rs => {
        //           var resp = rs.data;
        //           if (resp.state === 1) {
        //             this.$emit(
        //               "did-edit-role",
        //               this.form.id,
        //               this.form.name,
        //               this.form.intro
        //             );
        //             this.hide();
        //           } else {
        //             this.$message.error(resp.msg);
        //           }
        //         })
        //         .catch(err => {
        //           this.$message.error(err);
        //         });
        //     }
        //   } else {
        //     // 验证失败
        //     return false;
        //   }
        // });
      },
      handleCheckAllChange(val) {
        this.checkedCities = []
        if (val) {
          for (let i = 0; i < this.admin_user.length; i++) {
            this.checkedCities.push(this.admin_user[i].id)
          }
        } else {
          this.checkedCities = []
        }

        this.isIndeterminate = false
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length
        this.checkAll = checkedCount === this.cities.length
        this.isIndeterminate =
          checkedCount > 0 && checkedCount < this.cities.length
      }
    }
  }
</script>

<style lang="scss" scoped>
  .roleContent {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;

  .roleContentLeft {

  .chooseBox {
    width: 280px;
    height: 320px;
    overflow-y: auto;
    border: 1px solid rgba(235, 238, 240, 1);
    margin-top: 26px;
    padding: 20px;

  .checkone {
    display: flex;
    align-items: center;
    height: 50px;
  }

  .el-checkbox__label {
    display: flex;
    align-items: center;

  img {
    width: 30px;
    height: 30px;
    margin-right: 10px;
  }

  }
  }
  }
  .roleContentRight {

  .chooseBox {
    width: 280px;
    height: 320px;
    overflow-y: auto;
    border: 1px solid rgba(235, 238, 240, 1);
    margin-top: 26px;
    padding: 20px;

  .hasChoosedOne {
    display: flex;
    align-items: center;
    height: 50px;

  img {
    width: 30px;
    height: 30px;
    margin-right: 10px;
  }

  }
  }
  }
  }
  .newStaff {
    margin-top: 26px;

  .newItem {
    display: flex;
    align-items: center;
  }

  }
</style>

<style lang="scss">
  .roleContent {

  .roleContentLeft {

  .chooseBox {

  .el-checkbox {
    display: flex;
    align-items: center;
  }

  .el-checkbox__label {
    display: flex;
    align-items: center;
  }

  }
  }
  }
</style>
