<template>
  <div class="right-mine">
    <div class="right-mine-title">
      <span style="font-size: 18px;font-weight: bold">基本设置</span>
<!--      <el-button v-if="!isModifyMode" type="primary" size="mini" class="pull-right" @click="isModifyMode = true">编辑</el-button>-->
    </div>
    <div style="margin-bottom: 15px;width: 550px">
      <el-form :model="userForm" :rules="rules" status-icon ref="userForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="头像" prop="photoUrl">
          <el-upload
            class="avatar-uploader"
            style="border: lightgrey 1px solid;"
            action="https://jsonplaceholder.typicode.com/posts/"
            :before-upload="beforeFileUpload"
            :http-request="uploadFile"
          >
<!--            :disabled="!isModifyMode"-->

            <img v-if="userForm.photoUrl" :src="userForm.photoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="userForm.unit" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender" >
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker type="date" placeholder="选择日期" v-model="userForm.birthday"
                          style="width: 100%;"
                          :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>
        <el-form-item label="省市" prop="address" style="width: 160%">
          <provincecity v-if="userForm.location!==null"
            ref="addFormProvince"
            @selectChange="locationChange"
            :provinceCode="userForm.location!==null?userForm.location&&userForm.location.provinceCode:'3200'"
            :cityCode="userForm.location!==null?userForm.location&&userForm.location.cityCode:'3201'"
          ></provincecity>
<!--          :isModifyMode="!isModifyMode"-->
        </el-form-item>
        <el-form-item label="个人能力" style="width: 160%">
          <el-checkbox-group v-model="userForm.personalCompetence">
            <el-checkbox v-for="item in serviceType" :label="item.code" :name="item.code" :key="item.code" >{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
<!--          <el-button  v-if="isModifyMode" type="primary" size="small" class="pull-left" @click="submitUserInfo">提交修改</el-button>-->
          <el-button type="primary" size="small" class="pull-left" @click="submitUserInfo">提交修改</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import Http from '@/js/http'
  import Apis from '@/js/api'
  import {notify} from '@/constants/index'
  import {storageGet,getAllServiceTypes,getProvinceNameByProvinceCode,getProvinceCodeByProvinceName} from '@/js/index'
  import provincecity from '@/components/commons/NProvinceCity'
  export default {
    name: "Mine",
    data() {
      return {
        user: {},
        isModifyMode:false,
        serviceType:[],
        userForm: {
          gender:"",
          birthday:new Date(),
          photoUrl :'',
          userName: '',
          unit:'',
          personalCompetence:[],
          province:'',
          city:'',
          location:{},
        },
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          }
        },
        rules: {
          photoUrl: [
            { required: true, message: '请上传头像', trigger: 'blur'},
          ],
          userName: [
            { required: true, message: '请设置用户名', trigger: 'change' }
          ],
          province: [
            { required: true, message: '请选择省份', trigger: 'blur' }
          ],
          city: [
            { required: true, message: '请选择城市', trigger: 'blur' }
          ],
          gender: [
            { required: true, message: '请选择性别', trigger: 'blur' }
          ],
          // address:[
          //   {required: true, message: '请填写地址', trigger: 'blur' },
          // ]
        }
      }
    },
    components:{
      provincecity
    },
    methods: {
      submitUserInfo() {
        this.$refs['userForm'].validate(valid => {
          if (valid) {
            let location = getProvinceNameByProvinceCode(this.userForm.province, this.userForm.city);
            console.log(location)
            this.userForm.province = location.provinceCode;
            this.userForm.city = location.cityCode;
            let params = this.userForm;
            delete params.location;
            console.log(params);
            Http.put(`/api/personal/update/${this.user.id}`, params).then(res => {
              this.isModifyMode = false;
              notify('success', '修改成功 ');
              this.loadData();
            })
          }
        })
      },
      //联系地址改变
      locationChange (provinceId, cityId) {
        if (provinceId || cityId) {
          this.userForm.province = provinceId
          this.userForm.city = cityId
        }
      },
      //文件上传前的响应函数
      beforeFileUpload (file) {
        // 文件大小不能超过10M
        if (file.size > 5 * 1000 * 1000){
          notify('error', '单个文件大小不能超过5M')
          return false;
        }
        let fileName = file.name
        let index = fileName.lastIndexOf('.');
        // 文件不能没有后缀
        if (index <= 0){
          notify('error', '只能上传png/jpg/jpeg格式的文件')
          return false;
        }
        let fileSuffix = fileName.substr(index)
        // 文件后缀必须是.png或者.jpg
        if (fileSuffix !== '.jpg' && fileSuffix !== '.png' && fileSuffix !== '.jpeg') {
          notify('error', '只能上传png/jpg/jpeg格式的文件')
          return false;
        }
      },
      //上传文件，此处为上传图片
      uploadFile (param) {
        const formData = new FormData()
        let config = {
          //添加请求头
          headers: {'Content-Type': 'multipart/form-data'},
        }
        formData.append('file', param.file)
        //console.log(JSON.parse(this.user).userVO)
        Http.upload(Apis.FILE.UPLOAD_IMAGE.replace('{userId}', this.user.id), formData, config).then((res) => {
          this.userForm.photoUrl = res.data
          notify('success', '上传成功')
          // this.$refs['agency'].validateField('photoUrl');
        }).catch(error => {
          notify('error', error.data)
        })
      },
      loadData() {
        Http.get(`/api/personal/display/${this.user.id}`).then((res) => {
          this.userForm.gender = res.userVO.gender ? res.userVO.gender : '';
          this.userForm.photoUrl = res.userVO.photoUrl ? res.userVO.photoUrl : '';
          this.userForm.birthday = res.userVO.birthday ? res.userVO.birthday : new Date();
          this.userForm.userName = res.userVO.userName ? res.userVO.userName : '';
          this.userForm.unit = res.userVO.unit ? res.userVO.unit : '';
          this.userForm.province = res.userVO.province ? res.userVO.province : '';
          this.userForm.city = res.userVO.city ? res.userVO.city : '';
          this.userForm.personalCompetence = res.userVO.personalCompetence ? res.userVO.personalCompetence : [];
          this.userForm.location = getProvinceCodeByProvinceName(this.userForm.province, this.userForm.city);
          this.userForm.province = this.userForm.location&&this.userForm.location.provinceCode;
          this.userForm.city = this.userForm.location&&this.userForm.location.cityCode;
        })
      },
      setUserInfo(){
        this.user = storageGet('user') && storageGet('user').userVO;
      },
      setServiceType () {
        getAllServiceTypes().then((res) => {
          this.serviceType = res;
        })
      },

    },
    mounted() {
      this.$nextTick(()=>{
        this.setUserInfo();
        this.setServiceType();
        this.loadData();
      })

    }
  }
</script>

<style scoped lang="less">
  .avatar-uploader{
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin-right: 30px;
    width: 178px;
    height: 178px;
  }
  .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: 178px;
    height: 178px;
    display: block;
  }
  .right-mine {
    padding: 20px;
    background-color: rgba(255, 255, 255, 1);
    box-shadow: 0px 1px 6px 0px rgba(8, 6, 6, 0.13);

    .right-mine-title {
      padding: 10px;
      border-bottom: 1px solid #ccc;
      margin-bottom: 20px;
    }

    .avator-wrapper {
      height: 70px;
      width: 70px;
      line-height: 70px;
      vertical-align: middle;
    }
  }

</style>
