<template>
  <section class="userInfo form-content">
    <el-button type="text" class="edit" @click="handleEdit">修改个人信息</el-button>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :inline="true" label-width="100px">
        <el-form-item label="登录名称" prop="loginName">
          <el-input v-model="ruleForm.loginName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="ruleForm.userName" :disabled="isReadonly"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="ruleForm.address" :disabled="isReadonly"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email" :disabled="isReadonly"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone" :disabled="isReadonly"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio class="sex" v-model="ruleForm.userSex" label="男" :disabled="isReadonly">男</el-radio>
          <el-radio class="sex" v-model="ruleForm.userSex" label="女" :disabled="isReadonly">女</el-radio>
        </el-form-item>
        <el-form-item label="所属机构">
          <el-cascader
            :disabled="isReadonly"
            :options="ruleForm.options"
            :props="defaultProps"
            v-model="ruleForm.selectedOptions"
            change-on-select
            @change="handleChange">
          </el-cascader>
        </el-form-item>
    </el-form>

    <div class="userFooter" v-show="!isReadonly">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSure('ruleForm')">保 存</el-button>
    </div>
  </section>
</template>

<script>
import Api from '../api/index.js'

export default {
  data () {
    return {
      isReadonly: true,
      ruleForm: {
        loginName: '',
        userPassword: '',
        rePassword: '',
        userName: '',
        address: '',
        email: '',
        phone: '',
        status: 'enable',
        userSex: '男',
        // type: '2',
        options: [{
          value: 'zhinan',
          label: '指南',
          children: [{
            value: 'shejiyuanze',
            label: '设计原则',
            children: [{
              value: 'yizhi',
              label: '一致'
            }, {
              value: 'fankui',
              label: '反馈'
            }, {
              value: 'xiaolv',
              label: '效率'
            }, {
              value: 'kekong',
              label: '可控'
            }]
          }]
        }],
        selectedOptions: ['1001'],
        organguid: '1001',
        resetPassword: ''
      },
      rules: {
        loginName: [
          {required: true, message: '请输入登录名称', trigger: 'blur'},
          {validator: (rule, value, callback) => {
              if (value.length > 15 || value.length < 3) {
                callback(new Error('长度必须为3~15个字符'))
              } else {
                var reg = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
                if (reg.test(value)) {
                  callback(new Error('不能含有特殊字符'))
                } else {
                  callback()
                }
              }
            },
            trigger: 'change'
          }
        ],
        userName: [
          {required: true, message: '请输入用户名称', trigger: 'blur'},
          {validator: (rule, value, callback) => {
              if (value.length > 8 || value.length < 2) {
                callback(new Error('长度必须为2~8个字符'))
              } else {
                var reg = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
                if (reg.test(value)) {
                  callback(new Error('不能含有特殊字符'))
                } else {
                  callback()
                }
              }
            },
            trigger: 'change'
          }
        ],
        phone: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          {validator: (rule, value, callback) => {
              let mobile = /^1[34578][0-9]{9}$/
              if (mobile.test(value)) {
                callback()
              } else {
                callback(new Error('请输入合理的手机号'))
              }
            },
            trigger: 'change'
          }
        ],
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
        ]
      },
      defaultProps: {
        children: 'childOrganinfoinfos',
        label: 'organname',
        value: 'organguid'
      },
      treeData: []
    }
  },
  computed: {
    gisopUserInfo() {
      return this.$store.state.gisopUserInfo
    }
  },
  mounted () {
    this.initData()
    this.getOrganTree()
  },
  methods: { 
    // 初始化数据
    initData () {
      this.showUserData()
    },
    // 获取机构树
    getOrganTree () {
      Api.getOrganTree()
        .then(data => {
          let datas = data.data
          if (data.status === 0) {
            this.ruleForm.options = this.getChilds(data.result)
          } else {
            this.$message({
              type: 'warning',
              message: '请求数据失败'
            })
          }
        }).catch(res => { 
          console.log('error:', res)
        })
    },
    // 选择机构树
    handleChange (value) {
      this.ruleForm.organguid = value[value.length - 1]
    },
    // 展示数据
    showUserData () {
      Api.showUserData(this.gisopUserInfo.userguid)
      .then(data => {
        let datas = data.data
        if (data.status === 0) {
          this.ruleForm.loginName = datas.loginname
          this.ruleForm.userName = datas.username
          this.ruleForm.address = datas.address || ''
          this.ruleForm.email = datas.email
          this.ruleForm.phone = datas.phone || ''
          this.ruleForm.status = datas.status
          this.ruleForm.userSex = datas.usersex
          this.ruleForm.organguname = datas.organguname
          // this.ruleForm.type = data.result.type.toString()
          this.ruleForm.organguid = datas.organguid
          this.ruleForm.selectedOptions = []
          if (datas.organguid !== null) {
            let len = parseInt(datas.organguid.length / 4)
            for (let i = 1; i <= len; i++) {
              // console.log(data.result.organguid.substring(0, i*4))
              this.ruleForm.selectedOptions.push(datas.organguid.substring(0, i * 4))
            }
          }
        } else {
          this.$message({
            type: 'warning',
            message: '获取数据失败'
          })
        }
      }).catch(res => {
        this.$message({
          type: 'error',
          message: '获取数据失败'
        })
      })
    },
    // 确定
    handleSure (ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          this.sureEdit()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 确定修改
    sureEdit () {
      this.isReadonly = true
      var formData = new FormData()

      formData.append('loginname', this.ruleForm.loginName)
      formData.append('username', this.ruleForm.userName)
      formData.append('address', this.ruleForm.address)
      formData.append('email', this.ruleForm.email)
      formData.append('phone', this.ruleForm.phone)
      // formData.append('status', this.ruleForm.status)
      formData.append('usersex', this.ruleForm.userSex)
      // formData.append('organguname', this.ruleForm.organguname)
      formData.append('organguid', this.ruleForm.organguid)
      // formData.append('type', this.ruleForm.type)
 
      formData.append('userguid', this.gisopUserInfo.userguid)

      Api.editUserService(formData)
        .then(data => {
          this.dialogLoading = false
          this.addUserOnoff = false
          if (data.status === 0) {
            this.$message({
              type: 'success',
              message: '修改个人信息成功'
            })
          } else {
            this.$message({
              type: 'warning',
              message: '修改个人信息失败,请检查数据是否有误'
            })
          }
        })
        .catch(res => {
          this.$message({
            type: 'error',
            message: '请求数据失败'
          })
        }) 
    },
    // 取消
    handleCancel () { 
      this.isReadonly = true
      this.showUserData()
    },
    // 递归
    getChilds (data) {
      for (var i = 0; i < data.length; i++) {
         if (data[i].childOrganinfoinfos.length !== 0) {
          this.getChilds(data[i].childOrganinfoinfos)
        } else {
          delete data[i]['childOrganinfoinfos']
        }
      }
      return data
    },
    // 修改个人信息
    handleEdit () {
      this.isReadonly = false
    }
  } 
}
</script>

<style lang="scss">
  .userInfo {
    padding: 28px 12px 0 12px;
    position: relative;

    .edit {
      position: absolute;
      right: 8px;
      top: -15px;
      cursor: pointer;
      // color: #409EFF;
      font-size: 14px;
    }

    .el-input {
      display: inline-block;
      width: 320px;
    }
    span.tips {
      margin-left: 10px;
      margin-top: 10px;
      display: inline-block;
      width: 300px;
      vertical-align: top;
      font-size: 12px;
      color: #768394;
      line-height: 14px;
    }
    .userFooter {
      text-align: center;
      padding: 10px 0;
    }

    .el-input.is-disabled {
      .el-input__inner {
        color: #606266;
      }
    }
    .el-textarea.is-disabled {
      .el-textarea__inner {
        color: #606266;
      }
    }
  }
</style>
