<!-- 新增用户 -->
<template>
  <view class="adduser">
    <view class="warp">
      <view class="item">
        <view class="title">账号</view>
        <input class="msg" type="text" v-model="userInfo.account" placeholder="请输入账号(系统会自动加上前缀)" placeholder-style="color:#e8e8e8" />
      </view>
      <view class="item">
        <view class="title">用户昵称</view>
        <input class="msg" type="text" v-model="userInfo.name" placeholder="请输入真实姓名" placeholder-style="color:#e8e8e8"/>
      </view>
      <view class="item">
        <view class="title">角色</view>
        <view class="uni-list-cell">
          <view class="uni-list-cell-db">
            <picker @change="bindPickerChange" :value="userIndex" :range="userArray" range-key="name" class="uni-upd">
              <view class="uni-input" :class=" userIndex === 0 ? '' : 'txtcolor'">{{ userArray[userIndex].name }}</view>
            </picker>
            <view class="icon-warp">
              <image
                src="../../../static/images/moreicon.png"
                class="iconRight"
              ></image>
            </view>
          </view>
        </view>
      </view>
      <view class="item">
        <view class="title">手机号</view>
        <input class="msg" type="text" v-model="userInfo.phone" placeholder="请输入手机号" placeholder-style="color:#e8e8e8"/>
      </view>

      <view v-if="userdata">
        <view class="item">
          <view class="title">密码</view>
          <input class="msg" id="password"  v-model="passwordone" type="password" placeholder="默认不修改密码" placeholder-style="color:#e8e8e8"/>
        </view>
        <view class="item">
          <view class="title">确认密码</view>
          <input class="msg" id="password" v-model="passwordtwo" type="password" placeholder="默认不修改密码" placeholder-style="color:#e8e8e8"/>
        </view>
      </view>
      <view v-if="!userdata">
        <view class="item">
          <view class="title">密码</view>
          <input class="msg" id="password"  v-model="passwordone" type="password" placeholder="请输入密码" placeholder-style="color:#e8e8e8"/>
        </view>
        <view class="item">
          <view class="title">确认密码</view>
          <input class="msg" id="password" v-model="passwordtwo" type="password" placeholder="再次输入密码" placeholder-style="color:#e8e8e8"/>
        </view>
      </view>
      
    </view>
    <view class="btn">
      <view class="sure" @tap='submitUserInfo'>确认</view>
    </view>

		<rf-loading v-if="loading"></rf-loading>

  </view>
</template> 

<script>

export default {
  name: 'adduser',
  components: {},
  data () {
    //这里存放数据
    return {
      loading: false,

      userArray: [{ name: '请选择角色', id: '' }],
      userIndex: 0,
      roleList:[],

      // 用户信息
      passwordone: null,
      passwordtwo: null,
      userInfo: {
        account: '',  // 账号必传
        name: '',  //昵称必传
        roleId: '', // 角色id必传
        phone: '', // 手机号必传
        password: '', // 密码必传 
        status: '', // 状态
        id: '',
        mid: uni.getStorageSync('scenicMessage').id, 
      },
      namePrefix: uni.getStorageSync('scenicMessage').account + '-',

      // 编辑
      userdata: null
    };
  },
  onLoad(option) {
    // this.userdata = JSON.parse(option.userdata)
    if (JSON.parse(option.userdata).id) {
      this.userdata = JSON.parse(option.userdata)
      this.userdata.account =  this.userdata.account.substring(this.namePrefix.length)
      this.userdata.password = ''
      this.userInfo = this.userdata
      console.log(this.userInfo);
    }
  },
  onShow () {
    this.getRoleList().then( ()=>{
      if (this.userInfo.id) {
        this.userArray.forEach((item,index) => {
          if (item.name === this.userInfo.roleName) {
            this.userIndex = index
          }
        });
      }
    })
  },
  //方法集合
  methods: {
    // 角色选择
    bindPickerChange(e) {
      this.userIndex = e.detail.value
      this.userInfo.roleId = this.userArray[this.userIndex].id
    },
    // 角色列表
    async getRoleList () {
      await this.$http.get('/mrole/getList',{
        mid:this.userInfo.mid
      }).then( res=>{
        if (res.code === 200 && res.msg==='OK') {
          res.data.forEach(element => {
            if (element.name) {
              this.roleList.push({name: element.name,id: element.id})
              this.userArray = this.userArray.concat(this.roleList)
            }
          });
        }
      })
    },
    // 提交表单
    submitUserInfo () {
      this.verify().then( userInfo =>{
        this.loading = true
        // 账号添加景区前缀
        userInfo.account = this.namePrefix +this.userInfo.account
        this.$http.post('/user/save',userInfo).then( res=>{
          console.log(res);
          if (res.code === 200 && res.msg === 'OK') {
            if (this.userdata) {
              this.$mHelper.toast('修改成功')
            } else {
              this.$mHelper.toast('添加成功')
            }
            this.loading = false
            setTimeout(() => {
              this.$mRouter.back()
            }, 500);
          } 
        })
        
      })
    },
    // 表单验证规则
    verify () {
      console.log(this.userInfo);
      return new Promise((resolve,reject) =>{
        // 验证
        if ( !this.userInfo.account || !this.userInfo.name || !this.userInfo.roleId || !this.userInfo.phone ) {
          let obj = this.userInfo
          let arr = []
          for (let key in obj) {
            if (key === 'account' && !this.userInfo.account) {
              this.$mHelper.toast('请输入账号')
              return
            } else if (key === 'name' && !this.userInfo.name) {
              this.$mHelper.toast('请输入昵称')
              return
            } else if (key === 'phone' && !this.userInfo.phone) {
              this.$mHelper.toast('请输入手机号')
              return
            } else if (key === 'roleId' && !this.userInfo.roleId) {
              this.$mHelper.toast('请选择角色')
              return
            }
          }
        }
        // 账号验证
        if (this.userInfo.account) {
          let pattern = /^[a-zA-Z][a-zA-Z0-9_]{4,}$/
          if ( !pattern.test(this.userInfo.account)) {
            this.$mHelper.toast('请输入5位以上，以字母开头，可含数字、字母、下划线的账号！')
            return
          }
        }
        // 手机号验证
        if (this.userInfo.phone) {
          let pattern =  /^1[3|4|5|7|8][0-9]\d{8}$/
          if (!pattern.test(this.userInfo.phone)) {
            this.$mHelper.toast('请输入正确的手机号')
            return
          }
        }

        // 密码验证
        if ( this.userdata) {
          // 编辑
          console.log('编辑');
          if (this.passwordone === this.passwordtwo) {
            this.userInfo.password = this.passwordtwo
            if (this.userInfo.password) {  // 判断用户是否修改密码
              let pattern =  /^[a-zA-Z0-9_]{6,}$/
              if ( !pattern.test(this.userInfo.password)) {
                this.$mHelper.toast('请输入6位以上，可含字母、数字、下划线的密码！')
                return
              }
            }
          } else {
            this.passwordone = ''
            this.passwordtwo = ''
            this.$mHelper.toast('两次密码不一致，请重新输入')
            return
          }
        } else {
          // 新增
          console.log('新增');
          if (this.passwordone === this.passwordtwo && this.passwordtwo && this.passwordone ) {
            this.userInfo.password = this.passwordtwo
            let pattern =  /^[a-zA-Z0-9_]{6,}$/
            if ( !pattern.test(this.userInfo.password)) {
              this.$mHelper.toast('请输入6位以上，可含字母、数字、下划线的密码！')
              return
            }
          } else {
            this.passwordone = ''
            this.passwordtwo = ''
            this.$mHelper.toast('两次密码不一致，请重新输入')
            return
          }
        }
        

        resolve(this.userInfo)
      })
    }
  }
}
</script>
<style lang='scss' scoped>
.adduser {
  padding-top: 24upx;
  .warp {
    background-color: #fff;
    padding: 0 31upx;
    .item {
      display: flex;
      padding: 30upx 0;
      border-bottom: 1px solid #e1e1e1;
      &:last-child {
        border-bottom: none;
      }
      .title {
        color: #666666;
        width: 170upx;
        letter-spacing: 2upx;
      }
      .msg {
        flex: 1;
      }

      .uni-list-cell {
        flex: 1;
      }
      .uni-list-cell-db {
        display: flex;
        justify-content: space-between;
      }
      .uni-upd {
        width: 100%;
      }
      .uni-input {
        color: #e8e8e8;
      }
      .txtcolor {
        color: #000;
      }
      .icon-warp {
        width: 19upx;
        .iconRight {
          width: 19upx;
          height: 27upx;
        }
      }
    }
  }
  .btn {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 41upx;
    .sure {
      width: 600upx;
      height: 98upx;
      background-color: #8064f7;
      text-align: center;
      line-height: 98upx;
      letter-spacing: 2upx;
      border-radius: 6upx;
      color: #fff;
      font-size: 32upx;
    }
  }
}
</style>