<template>
  <div class="layout-no-cols">
    <el-toolbar>
      <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary">
        <i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save" @click="editMemberHandler" :loading="confirmLoading" priv="Member.Information.Edit">
        <span>
          <i class="fa fa-save"></i>保存</span>
      </el-button>
    </el-toolbar>
    <div>
      <div class="detail-panel edit-member-page">
        <h3>会员信息</h3>
        <el-row v-loading="dialogLoading">
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form :model="tmpMember" :rules="memberRules" ref="editMemberForm" label-width="120px" label-suffix="：">
                <el-form-item label="会员名" prop="userName">
                  <el-input type="text" disabled v-model="tmpMember.userName" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="真实姓名" prop="realName" :verify="['Length<21']">
                  <el-input type="text" v-model="tmpMember.realName"></el-input>
                </el-form-item>
                <el-form-item prop="password" label="密码" :verify="['NotNull|必填，密码不能为空','Length<21', 'Length>5']">
                  <el-input type="password" v-model="tmpMember.password"></el-input>
                </el-form-item>
                <el-form-item label="重复密码" prop="repeatPassword">
                  <el-input type="password" v-model="tmpMember.repeatPassword"></el-input>
                </el-form-item>
                <el-form-item label="电子邮箱" prop="email" :verify="['Email|请输入正确的邮箱']">
                  <el-input v-model="tmpMember.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="mobile" :verify="['CnPhone|请输入正确的手机号']">
                  <el-input v-model="tmpMember.mobile"></el-input>
                </el-form-item>
                <el-form-item prop="status" label="状态" :verify="['NotNull|请设置会员状态']">
                  <el-radio class="radio" v-model="tmpMember.status" label="Y">启用 </el-radio>
                  <el-radio class="radio" v-model="tmpMember.status" label="N">禁用 </el-radio>
                </el-form-item>
                <el-form-item prop="gender" label="性别">
                  <el-radio class="radio" v-model="tmpMember.gender" label="M">男 </el-radio>
                  <el-radio class="radio" v-model="tmpMember.gender" label="F">女 </el-radio>
                </el-form-item>
                <el-form-item prop="pwdQuestion" label="密码提示问题">
                  <el-input v-model="tmpMember.pwdQuestion" :maxlength="60"></el-input>
                </el-form-item>
                <el-form-item prop="pwdAnswer" label="密码提示答案">
                  <el-input v-model="tmpMember.pwdAnswer" :maxlength="60"></el-input>
                </el-form-item>
                <el-form-item prop="memo" label="备注">
                  <el-input v-model="tmpMember.memo" :maxlength="30"></el-input>
                </el-form-item>
                <member-dialog-extend v-if="tmpMember.ID" :member.sync="tmpMember"></member-dialog-extend>
              </el-form>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple-light" style="padding-top:50px;">
              <el-upload class="avatar-uploader" :action="importFileUrl" v-loading="uploadLoading" :http-request="fileUploadHandler" :show-file-list="false"
                :on-success="handleAvatarSuccess" :multiple="false" :before-upload="beforeAvatarUpload" accept=".jpg,.jpeg,.bmp,.png,.gif">
                <img :src="imageUrl || `assets/images/face/default-${memberId%6}/120.png`" class="avatar" :onerror="`this.src='assets/images/face/default-${memberId%6}/120.png';`">
              </el-upload>
            </div>
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>会员等级</span>
              </div>
              <div v-for="item in memberLevels" :key="item.value" class="text item">
                <span>{{item.levelTypeName}}：</span>{{item.name}}&nbsp;
                <img height="16" v-bind:src="item.previewPath" onerror="this.onerror=null;this.src='assets/images/icon401a10.png';" />
              </div>
            </el-card>
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>会员积分</span>
              </div>
              <div v-for="item in memberScores" :key="item.value" class="text item">
                <span>{{item.scoreTypeName}}：</span>{{item.score}}&nbsp;&nbsp;
                <span>
                  <a href="javascript:void(0);" @click="memberIntervention(item['scoreType'],item['score']);">人工干预</a>
                </span>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
    <!--人工干预框-->
    <intervetion-dialog :show.sync="intervetionModal" :member-id="memberId" :intervetion-score-type="intervetionScoreType" @callback="afterIntervetion"></intervetion-dialog>
  </div>
</template>

<script>
import util from '@src/common/util.js'
import MemberDialogExtend from './components/MemberDialogExtend.vue'
import intervetionDialog from './intervetionDialog.vue'

export default {
  components: {
    'member-dialog-extend': MemberDialogExtend,
    'intervetion-dialog': intervetionDialog
  },
  props: {
    memberId: {
      required: true
    }
  },
  data() {
    return {
      // 会员验证规则
      memberRules: {
        repeatPassword: [
          {
            validator: (rule, value, callback) => {
              if (value !== this.tmpMember.password) {
                callback(new Error('请重复输入相同的密码'))
              } else {
                callback()
              }
            },
            trigger: 'blur',
            required: true
          }
        ]
      },
      importFileUrl: '',
      imageUrl: '', // 图像路径
      confirmLoading: false,
      memberLevels: [], // 会员等级
      memberScores: [], // 会员积分
      intervetionModal: false,
      intervetionScoreType: '', // 人工干预积分类型
      dialogLoading: false,
      tmpMember: {}, //  表单对象
      uploadLoading: false
    }
  },
  created() {
    this.beforeShowPage()
  },
  methods: {
    // 图片上传
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isBMP = file.type === 'image/bmp'
      const isGIF = file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isBMP && !isGIF && !isPNG) {
        this.$message.error('上传头像图片只能是.jpg,.jpeg,.bmp,.png,.gif格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG || isBMP || isGIF) && isLt2M
    },
    // 处理上传图标
    async fileUploadHandler(event) {
      this.uploadLoading = true
      const { file } = event
      const formData = new FormData()
      formData.append('file', file)
      formData.append('ID', this.tmpMember.ID)
      try {
        let data = await axios.post(`/ui/member/uploadhead`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        this.uploadLoading = false
        if (data.data.status === 1) {
          this.imageUrl = data.data.imgurl
          this.tmpMember.logoFile = data.data.zvingfile
        }
      } catch (e) {
        this.uploadLoading = false
        // util.showErrorNotification(e)
      }
    },
    // 人工干预弹出框
    memberIntervention(type, score) {
      this.intervetionScoreType = type
      this.intervetionModal = true
    },
    afterIntervetion(array) {
      this.memberScores = array
    },
    async beforeShowPage() {
      this.dialogLoading = true
      this.imageUrl = ''
      try {
        let memberData = await axios.get(`/ui/member/${this.memberId}`)
        this.tmpMember = memberData.data.data
        if (this.tmpMember.logoFile) {
          this.imageUrl = memberData.data.prefix + this.tmpMember.logoFile
        }
        this.tmpMember.password = '********'
        this.tmpMember.repeatPassword = '********'
        let levelsData = await axios.get(`/ui/member/${this.memberId}/bindmemberlevels`)
        this.memberLevels = levelsData.data.data
        let scoresData = await axios.get(`/ui/member/${this.memberId}/bindmemberscores`)
        this.memberScores = scoresData.data.data
      } catch (e) {}
      this.dialogLoading = false
    },
    // 处理编辑事件
    async editMemberHandler() {
      this.confirmLoading = true
      try {
        this.tmpMember.addTime = util.formatDate(new Date(this.tmpMember.addTime), 'yyyy-MM-dd HH:mm:ss')
        await util.validateForm(this.$refs['editMemberForm'])
        let res = await axios.put(`/ui/member/${this.memberId}`, this.tmpMember)
        this.confirmLoading = false
        util.showResponseMessage(res.data)
      } catch (e) {
        this.confirmLoading = false
        util.showErrorMessageBox(e)
      }
    }
  }
}
</script>

<style>
  /* image-uploader*/

  .edit-member-page .avatar-uploader {
    text-align: center;
  }

  .edit-member-page .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    background-color: #eef1f6;
  }

  .edit-member-page .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .edit-member-page .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .edit-member-page .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .edit-member-page .el-card {
    margin-top: 50px;
    margin-left: 30px;
  }

  .edit-member-page .el-form-item .el-input {
    width: 260px;
  }
</style>
