<template>
  <div class="personal-info-container">
    <el-card class="personal-info-header">
      <div class="header-content">
        <div class="avator-container">
          <el-avatar :size="80" :src="photoUrl" fit="cover">
            <img :src="photoUrl" alt="" />
          </el-avatar>
          <el-upload
            action="string"
            :http-request="updateUserImage"
            :show-file-list="false"
          >
            <el-button size="mini" type="primary"
              >{{ $t('personal.upload') }}
            </el-button>
          </el-upload>
        </div>
        <div class="header-info">
          <el-row>
            <el-col :span="6">
              <div>
                {{ $t('personal.name') }}：{{ currentUser.user.fullname }}
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                {{ $t('personal.account') }}：{{ currentUser.user.account }}
              </div>
            </el-col>
            <el-col :span="6">
              <div>性别：{{ form.sex }}</div>
            </el-col>
            <el-col :span="6">
              <div>出生年月：{{ form.userExtend.birthday }}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <div>
                {{ $t('personal.phone') }}：{{ currentUser.user.phone }}
              </div>
            </el-col>
            <el-col :span="6">
              <div>邮箱：{{ form.email }}</div>
            </el-col>
            <el-col :span="6">
              <div>
                组织：{{ currentUser.org[0] ? currentUser.org[0].orgName : '' }}
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                岗位：
                {{ postName }}
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div>
                {{ $t('personal.role') }}：<span
                  class="role"
                  v-for="(item, index) in currentUser.role.roleName.split('|')"
                  :key="item"
                >
                  <span v-if="index !== 0">、</span>{{ item }}
                </span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-card>
    <el-card class="personal-info-bottom" body-style="overflow:auto">
      <el-form ref="form" :model="form" :rules="rules" label-position="top">
        <div class="title-info">个人信息更新</div>
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item :label="$t('personal.name')" prop="fullname">
              <el-input
                v-model="form.fullname"
                :placeholder="$t('common.input')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="$t('personal.gender')" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item
              label="出生年月"
              prop="userExtend.birthday"
              :rules="rules.birthday"
            >
              <el-date-picker
                v-model="form.userExtend.birthday"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="请选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item
              label="身份证号"
              prop="userExtend.idNumber"
              :rules="rules.idNumber"
            >
              <el-input
                v-model="form.userExtend.idNumber"
                :placeholder="$t('common.input')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="$t('personal.mailbox')" prop="email">
              <el-input
                v-model="form.email"
                :placeholder="$t('common.input')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="$t('personal.phone')" prop="mobile">
              <el-input
                v-model="form.mobile"
                :placeholder="$t('common.input')"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <!-- <el-col :span="4">
                        <el-form-item label="工号" prop="userNumber">
                            <el-input
                                v-model="form.userNumber"
                                :placeholder="$t('common.input')"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item
                            label="工种"
                            prop="userExtend.workType"
                            :rules="rules.workType"
                        >
                            <el-input
                                v-model="form.userExtend.workType"
                                :placeholder="$t('common.input')"
                            ></el-input>
                        </el-form-item>
                    </el-col> -->
          <el-col :span="4">
            <el-form-item
              label="职称"
              prop="userExtend.jobTitle"
              :rules="rules.jobTitle"
            >
              <el-input
                v-model="form.userExtend.jobTitle"
                :placeholder="$t('common.input')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item
              label="文化程度"
              prop="userExtend.diploma"
              :rules="rules.diploma"
            >
              <el-input
                v-model="form.userExtend.diploma"
                :placeholder="$t('common.input')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item
              label="入职时间"
              prop="userExtend.hireDate"
              :rules="rules.hireDate"
            >
              <el-date-picker
                v-model="form.userExtend.hireDate"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="请选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('personal.address')" prop="address">
              <el-input
                v-model="form.address"
                :placeholder="$t('common.input')"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="工作经历（入司后工作经历）"
              prop="userExtend.workExperience"
              :rules="rules.workExperience"
            >
              <el-input
                type="textarea"
                :autosize="{minRows: 2, maxRows: 6}"
                v-model="form.userExtend.workExperience"
                :placeholder="$t('common.input')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="有何技能和特长(证书)"
              prop="userExtend.skills"
              :rules="rules.skills"
            >
              <el-input
                type="textarea"
                :autosize="{minRows: 2, maxRows: 6}"
                v-model="form.userExtend.skills"
                :placeholder="$t('common.input')"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="personal-info-footer">
      <div style="text-align: center">
        <el-button type="primary" @click="updataInfo" :loading="saveing"
          >{{ $t('common.save') }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import uc from '@/api/uc.js'

export default {
  name: 'personal-info',
  data() {
    var isEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error('邮箱不能为空'))
      } else {
        const reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
        const email = reg.test(value)
        if (!email) {
          callback(new Error('邮箱格式如:admin@163.com'))
        } else {
          callback()
        }
      }
    }
    var isMobileNumber = (rule, value, callback) => {
      if (!value) {
        callback(new Error('手机号不能为空'))
      } else {
        // const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
        const reg = /^1[3-9]\d{9}$/
        const isPhone = reg.test(value)
        value = Number(value) //转换为数字
        if (typeof value === 'number' && !isNaN(value)) {
          //判断是否为数字
          value = value.toString() //转换成字符串
          if (value.length < 0 || value.length > 12 || !isPhone) {
            //判断是否为11位手机号
            callback(new Error('手机号码格式有误，请核查！'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }

    var isCardId = (rule, value, callback) => {
      if (!value) {
        return new Error('身份证号不能为空)')
      } else {
        const reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(([0-2][1-9])|10|20|30|31)\d{3}(\d|X|x)$/
        const card = reg.test(value)
        if (!card) {
          //判断座机为12位
          callback(new Error('身份证格式有误，请核查！'))
        } else {
          callback()
        }
      }
    }

    return {
      currentUser: {
        org: [],
        role: {
          roleName: ''
        },
        user: {}
      },
      options: [
        {
          value: '男',
          label: '男'
        },
        {
          value: '女',
          label: '女'
        }
      ],
      form: {
        userExtend: {
          workExperience: '',
          birthday: '',
          hireDate: ''
        }
      },
      rules: {
        fullname: [
          {
            required: true,
            message: '姓名不能为空',
            trigger: ['blur', 'change']
          }
        ],
        sex: [
          {
            required: true,
            message: '性别不能为空',
            trigger: ['blur', 'change']
          }
        ],
        birthday: [
          {
            required: true,
            message: '出生年月不能为空',
            trigger: ['blur', 'change']
          }
        ],
        idNumber: [
          {
            required: true,
            message: '身份证号不能为空',
            trigger: ['blur', 'change']
          },
          {validator: isCardId, trigger: 'blur'}
        ],
        email: [
          {
            required: true,
            message: '邮箱不能为空',
            trigger: ['blur', 'change']
          },
          {validator: isEmail, trigger: 'blur'}
        ],
        mobile: [
          {
            required: true,
            message: '手机号不能为空',
            trigger: ['blur', 'change']
          },
          {validator: isMobileNumber, trigger: 'blur'}
        ],
        userNumber: [
          {
            required: true,
            message: '工号不能为空',
            trigger: ['blur', 'change']
          }
        ],
        workType: [
          {
            required: true,
            message: '工种不能为空',
            trigger: ['blur', 'change']
          }
        ],
        jobTitle: [
          {
            required: true,
            message: '职称不能为空',
            trigger: ['blur', 'change']
          }
        ],
        diploma: [
          {
            required: true,
            message: '文化程度不能为空',
            trigger: ['blur', 'change']
          }
        ],
        hireDate: [
          {
            required: true,
            message: '入职时间不能为空',
            trigger: ['blur', 'change']
          }
        ],
        address: [
          {
            required: true,
            message: '地址不能为空',
            trigger: ['blur', 'change']
          }
        ],
        workExperience: [
          {
            required: true,
            message: '工作经历不能为空',
            trigger: ['blur', 'change']
          }
        ]
        // skills: [
        //     {
        //         required: true,
        //         message: '不能为空',
        //         trigger: ['blur', 'change'],
        //     },
        // ],
      },
      photoUrl: window.context.front + '/img/defaultPhoto.jpg',
      photo: '',
      saveing: false,
      postName: ''
    }
  },
  mounted() {
    this.getInfo()
  },
  methods: {
    updateUserImage(param) {
      const formData = new FormData()
      formData.append('files', param.file)
      uc.fileUpload(formData)
        .then(response => {
          this.photo = response.fileId
          this.form.photo = response.fileId
          this.$store
            .dispatch('menu/downloadImg', response.fileId)
            .then(res => {
              if (res != '') {
                this.photoUrl = res
              }
            })
          param.onSuccess() // 上传成功的图片会显示绿色的对勾
          this.updataInfo()
        })
        .catch(response => {
          param.onError()
        })
    },
    getInfo() {
      let currentUser = sessionStorage.getItem('currentUser')
      let account = JSON.parse(currentUser).account
      if (account) {
        uc.getUser(account).then(res => {
          this.currentUser = res
          let post = this.currentUser.post
          for (let key in post) {
            this.postName = post[key].postName || ''
            this.form.userExtend.workType = this.postName || ''
          }
          let form = res.user

          let {
            birthday = '',
            hireDate = '',
            idNumber = '',
            workExperience = '',
            workType = '',
            jobTitle = '',
            diploma = '',
            skills = ''
          } = res.userExtend

          let userExtend = {
            birthday,
            hireDate,
            idNumber,
            workExperience,
            workType,
            jobTitle,
            diploma,
            skills,
            ...res.userExtend
          }

          this.form = form
          this.$set(this.form, 'userExtend', userExtend)

          if (this.form.photo) {
            this.$store
              .dispatch('menu/downloadImg', this.form.photo)
              .then(res => {
                if (res != '') {
                  this.photoUrl = res
                }
              })
          }
        })
      }
    },
    updataInfo() {
      this.saveing = true
      this.$refs.form.validate((valid, object) => {
        if (valid) {
          this.form.userExtend.workType = this.postName || ''
          this.$http
            .post(window.context.uc + '/api/user/v1/user/updateUser', this.form)
            .then(res => {
              if ((res.status = 200)) {
                this.$message.success('更新成功')
                this.$store.dispatch('login/checkUserInfoState')
                this.$bus.$emit('updataUserInfo')
                // this.$router.push('/platLayout/homePage')
              }
            })
            .finally(() => {
              this.saveing = false
            })
        } else {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
          this.saveing = false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';

.personal-info-container {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 16px;

  .el-header {
    display: flex;
    align-items: center;
    border-bottom: 1px solid $--system-border-color3;
    // background: #314351;
  }

  .title {
    font-size: 16px;
  }

  .personal-info-header {
    margin-bottom: 16px;
  }

  .header-content {
    display: flex;
    height: 100%;
  }

  .avator-container {
    width: 120px;
    height: 100%;
    margin-right: 30px;
    box-sizing: border-box;
    text-align: center;
  }

  .header-info {
    width: calc(100% - 150px);
    padding: 6px 0;
    display: flex;
    flex-flow: column;
    justify-content: space-between;
    gap: 14px;
    div {
      font-size: 14px;
    }
    .role {
      font-size: 14px;
    }
  }
}

.el-card.is-always-shadow {
  border-radius: 20px;
}
.personal-info-bottom {
  height: calc(100% - 288px);
  margin-bottom: 16px;
  overflow: auto;
}
.personal-info-footer {
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.title-info {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #43a1ff;
}
::v-deep .el-form--label-top .el-form-item__label {
  padding: 0;
}
::v-deep .el-form-item {
  margin-bottom: 14px;
}
::v-deep .el-avatar {
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style>
