<template>
  <div class='personal-setting'>
    <el-form ref='userForm' label-position='top' :model='formData' :rules='formRules'>
      <div class='info-box'>
        <el-form-item label='角色'>
          <el-tag v-for='(item, index) in userInfo.roleNames' :key='index'>{{ item }}</el-tag>
        </el-form-item>
        <el-form-item label='姓名' prop='fullName'>
          <el-input v-model.trim='formData.fullName' :disabled='curState === 1' />
        </el-form-item>
        <el-form-item label='手机号码' prop='mobile'>
          <el-input v-model.trim='formData.mobile' :disabled='curState === 1' />
        </el-form-item>
        <el-form-item label='电子邮箱' prop='email'>
          <el-input v-model.trim='formData.email' :disabled='curState === 1' />
        </el-form-item>
        <el-form-item label='性别' prop='sex'>
          <el-radio-group v-model='formData.sex' :disabled='curState === 1'>
            <el-radio-button v-for='item in dictSex' :key='item.value' :label='item.value'>
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
      </div>
      <div class='avatar-box'>
        <el-form-item label='头像' prop='avatar'>
          <div>hi</div>
        </el-form-item>
      </div>
    </el-form>
    <div class='button-box'>
      <el-button type='primary' :loading='loading' @click='handleButton'>
        {{ curState === 1 ? '编辑' : '确认' }}
      </el-button>
      <el-button @click='resetFn' v-if='curState === 2'>重置</el-button>
      <el-button type='warning' @click='closeFn' v-if='curState === 2'>关闭</el-button>
    </div>
  </div>
</template>

<script>
import { isMobile } from '@utils/validate';
import { fetchUserById, fetchUserInfo, updateSelfUserDetail, uploadUserAvatar } from '@api/upms/api-user';

export default {
  name: 'PersonalSetting',
  components: {},
  props: {
    userInfo: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  computed: {
    dictSex() {
      return this.$store.getters.dict.dictSex;
    },
    myUserInfo() {
      return this.$store.getters.userInfo;
    }
  },
  data() {
    let validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        return callback(new Error('请输入正确的手机号码'));
      } else {
        return callback();
      }
    };
    return {
      curState: 1,
      picDisabled: true,
      dbUserInfo: {},
      loading: false,
      formData: {
        fullName: this.userInfo.fullName,
        sex: this.userInfo.sex,
        mobile: this.userInfo.mobile,
        email: this.userInfo.email
      },
      defaultData: {
        sex: '3',
        attachDataList: []
      },
      uploadParams: {},
      formRules: {
        fullName: [{
          required: true,
          message: '请输入姓名',
          trigger: 'blur'
        }],
        mobile: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          },
          {
            len: 11,
            message: '长度11个字符',
            trigger: 'blur'
          },
          {
            required: true,
            validator: validateMobile,
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: false,
            type: 'email',
            message: '请输入正确的电子邮箱',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  methods: {
    handleButton() {
      let vm = this;
      if (vm.curState === 1) {
        vm.curState = 2;
        vm.picDisabled = false;
        fetchUserById({ id: vm.userInfo.id }).then(
          (res) => {
            vm.dbUserInfo = res.data;
            vm.formData = {
              fullName: vm.dbUserInfo.fullName,
              sex: vm.dbUserInfo.sex,
              mobile: vm.dbUserInfo.mobile,
              email: vm.dbUserInfo.email
            };
          },
          (error) => {
            vm.$notify.error({
              title: error.data.msg,
              message: error.data.data
            });
          }
        );
      } else {
        vm.submitFn();
      }
    },
    submitFn() {
      let vm = this;
      vm.$refs.userForm.validate((valid) => {
        if (valid) {
          vm.loading = true;
          vm.updateSelfUserDetailFn();
        }
      });
    },
    resetFn() {
      let vm = this;
      vm.$refs.userForm.resetFields();
      vm.formData = {
        fullName: vm.dbUserInfo.fullName,
        sex: vm.dbUserInfo.sex,
        mobile: vm.dbUserInfo.mobile,
        email: vm.dbUserInfo.email
      };
    },
    closeFn() {
      let vm = this;
      vm.$confirm('确认关闭编辑吗?', '提示', {
        type: 'warning'
      }).then(() => {
        vm.formData = {
          fullName: vm.myUserInfo.fullName,
          sex: vm.myUserInfo.sex,
          mobile: vm.myUserInfo.mobile,
          email: vm.myUserInfo.email
        };
        vm.curState = 1;
        vm.picDisabled = true;
      });
    },
    async updateSelfUserDetailFn() {
      let vm = this;
      await updateSelfUserDetail(vm.formData);
      let res = await fetchUserInfo();
      vm.$store.dispatch('setUserInfo', res.data);
      vm.curState = 1;
      vm.loading = false;
      vm.picDisabled = true;
      vm.$message.success('更新个人信息成功');
      vm.formData = {
        fullName: vm.myUserInfo.fullName,
        sex: vm.myUserInfo.sex,
        mobile: vm.myUserInfo.mobile,
        email: vm.myUserInfo.email
      };
    },
    initUploadParams(fileList) {
      let vm = this;
      let params = {
        fileList: fileList,
        limit: 1
      };
      vm.uploadParams = Object.assign(params, uploadUserAvatar());
    },
    uploadFiles(fileList) {
      this.formData.avatar = fileList.length > 0 ? fileList[0].id : '';
    }
  },
  created() {
    this.initUploadParams(this.userInfo.attachDataList);
  }
};
</script>

<style lang='less' scoped>
.personal-setting {
  :deep(.el-form) {
    display: flex;

    .info-box {
      flex: 1;
    }

    .avatar-box {
      padding-left: 30px;
    }
  }

  .button-box {
    padding-top: 50px;
  }
}
</style>
