addPerson.vue 11.5 KB
<template>
  <div>
    <el-dialog :title="$t('dialog.addPerson')" :visible.sync="isShow" class="manage-dialog" :before-close="closeDialog" :close-on-click-modal="false">
      <el-form :model="addForm" status-icon :rules="rules" ref="addForm">
        <el-form-item :label="$t('table.name')" prop="name">
          <el-input v-model="addForm.name"></el-input>
          <i class="error-tip">*</i>
        </el-form-item>
        <el-form-item :label="$t('table.gender')" prop="gender">
          <el-select class="manage-sel" v-model="addForm.gender" :placeholder="$t('pholder.select')" :no-data-text="$t('pholder.nodata')">
            <el-option :label="$t('head.man')" :value="1"></el-option>
            <el-option :label="$t('head.woman')" :value="0"></el-option>
          </el-select>
          <i class="error-tip">*</i>
        </el-form-item>
        <el-form-item :label="$t('table.age')" prop="age">
          <el-input v-model="addForm.age"></el-input>
          <i class="error-tip">*</i>
        </el-form-item>
        <el-form-item :label="$t('table.type')" prop="type">
          <el-select class="manage-sel" v-model="addForm.type" :placeholder="$t('pholder.type')" :no-data-text="$t('pholder.nodata')">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
          </el-select>
          <i class="error-tip">*</i>
        </el-form-item>
        <el-form-item :label="$t('dialog.tel')" prop="tel">
          <el-input v-model="addForm.tel"></el-input>
          <!-- <i class="error-tip">*</i> -->
        </el-form-item>
        <el-form-item :label="$t('dialog.email')" prop="email">
          <el-input v-model="addForm.email"></el-input>
          <!-- <i class="error-tip">*</i> -->
        </el-form-item>
        <el-form-item :label="$t('table.square')" prop="mallId">
          <el-select
            class="manage-sel"
            v-model="addForm.mallId"
            filterable
            :placeholder="$t('pholder.select')"
            :no-data-text="$t('pholder.nodata')"
            @change="onMallChange"
          >
            <el-option v-for="item in mallList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <i class="error-tip">*</i>
        </el-form-item>
        <el-form-item :label="$t('dialog.profilePic')" prop="photo"> 
          <!-- <el-button @click="profileHandle" class="dialog-btn">{{$t('dialog.profilePic')}}</el-button>
          <input type="file" v-show="false" @change="handleChange2" ref="fileinput" /> -->
          <el-upload
            class="avatar-uploader"
            :multiple="false"
            :show-file-list="false"
            :auto-upload="false"
            :action="uploadAction"
            :headers="uploadHeaders"
            :on-change="handleChange"
            ref="profileupload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <i class="error-tip">*</i>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" class="dialog-btn">
          {{ $t('dialog.cancel') }}
        </el-button>
        <el-button type="primary" :loading="addButLoad" :disabled="addButDisable" @click="addSubmit('addForm')" class="dialog-btn dialog-confirm-btn">
          {{ addButDisable? $t('button.uploaing') : $t('dialog.confirm') }}
        </el-button>
      </div>
    </el-dialog>
    <crop-dialog ref="cropRef" @profilePath="getPath"></crop-dialog>
  </div>
</template>

<script>
import CropDialog from '../components/Clip/crop'

export default {
  components: { CropDialog },
  props: {
    mallId: {
      type: Number,
      default: null
    },
    mallList: {
      type: Array,
      default: () => []
    },
    // typeList: {
    //   type: Array,
    //   default: () => []
    // }
  },
  data() {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('年龄不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(Number(value))) {
          callback(new Error('请输入正确格式'));
        } else {
          // if (value < 18) {
          // callback(new Error('必须年满18岁'));
          // } else {
          callback();
          // }
        }
      }, 1000);
    };
    var checkPhoto = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请上传证件照'))
      } else {
        callback(); 
      }
    }
    var checkEmail = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if(!/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value)) {
        return callback(new Error('邮箱格式错误'))
      }
    }
    return {
      timer:'',
      isShow: false,
      addForm: {
        name: '',
        mallId: null,
        gender: null,
        age: null,
        type: null,
        tel: '',
        email: '',
        photo: null,
      },
      // mallList: [],
      typeList: [],
      uploadAction: '/persons/uploadImg/',
      uploadHeaders: {},
      profileFormData: {},
      imageUrl: '',
      maxSize: 20,
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'change' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        age: [
          { validator: checkAge, trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        mallId: [
          { required: true, message: '请选择所属广场', trigger: 'change' }
        ],
        email: [
          { validator: checkEmail, trigger: 'change' }
        ],
        photo: [
          { validator: checkPhoto, trigger: 'change' }
        ]
      },
      curMallId: null,
      addButDisable: false,
      addButLoad: false
    }
  },
  // watch: {
  //   'addForm.mallId': {
  //     handler(nVal, oVal) {
  //       console.log(nVal, typeof nVal, this.isShow)
  //       if (nVal !== null && this.isShow) {
  //         this.fetchPersonType()
  //       }
  //     },
  //     immediate: true
  //   }
  // },
  created() {
    this.uploadHeaders = {
      'Authorization': this.$cookie.get('atoken')
    }
  },
  methods: {
    dialogInit() {
      // this.curMallId = mall_id
      // const isExitMallId = this.mallList.some(item => item.id == mall_id)
      if (this.mallList.length) {
        this.addForm.mallId = this.mallId || this.mallList[0].id
      }
      this.fetchPersonType()
      // this.getMallList()
      this.isShow = true
    },
    fetchPersonType() {
      if (!this.addForm.mallId) return false
      this.addForm.type = null
      this.typeList = []
      return new Promise(resolve => {
        this.$api.management.personTypeList({
          accountId: this.$cookie.get('accountId'),
          mallId: this.addForm.mallId
        }).then(res => {
          const { code, data } = res.data
          if (code === 200) {
            this.typeList = data.reduce((arr, curr) => {
              arr.push(curr)
              return arr
            }, [])
            resolve()
          }
        })
      })
    },
    // getMallList() {
    //   this.mallList = [];
    //   this.$api.base.mall({
    //     accountId: this.$cookie.get('accountId'),
    //     status: 1
    //   })
    //   .then(res => {
    //     let result = res.data;
    //     result.data.forEach(item => {
    //       if(item.id == this.curMallId) {
    //         this.addForm.mallId = item.id
    //       }
    //     })
    //     if(result.data.length > 0) {
    //       if(!this.curMallId) {
    //         this.addForm.mallId = result.data[0].id
    //       }
    //       this.mallList = result.data
    //     }
    //   })
    //   .catch(err => {
    //     this.catchErrorHandle(err)
    //   })
    // },
    onMallChange(val) {
      this.addForm.mallId = val
      this.fetchPersonType()
    },
    handleChange(file, fileList) {
      let
        {
          maxSize
        } = this,
        isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png',
        isLt2M = file.size / 1024 / 1024 < maxSize

      if (!isJPG) {
        this.$message.error(this.$t('message.uploadImg') + ' JPG or Png' + this.$t('message.imgFormat'))
      }
      // 超出大小
      if (!isLt2M) {
        this.$message.error(this.$t('message.imgLimSize') + ' 20MB!')
      }
      if(isJPG && isLt2M) {
        this.$refs.cropRef.cropDialogInit(fileList[fileList.length - 1].raw)
      }
    },
    getPath(path, blobPath) {
      this.profileFormData = path
      this.imageUrl = blobPath
      this.addForm.photo = blobPath
    },
    addSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        try {
          if (valid) {
            if(this.addButDisable) return
            this.addButDisable = this.addButLoad = true
            clearTimeout(this.timer)
            this.timer = setTimeout(()=>{ 
              let params = null
                params = new FormData()
              // this.addForm['accountId'] = this.$cookie.get('accountId');
              if (this.toRawType(this.profileFormData) === 'FormData') {
                for(let key of this.profileFormData.keys()) {
                  let val = this.profileFormData.get(key)
                  params.append(key, val)
                }
                Object.keys(this.addForm).forEach((k) => {
                  if(typeof this.addForm[k] !== 'undefined'
                    && (this.addForm[k]
                    || typeof(this.addForm[k]) === 'number')
                  ) {
                    params.append(k, this.addForm[k])
                  }
                })
              } else {
                Object.keys(this.addForm).forEach((k) => {
                  params.append(k, this.addForm[k])
                })
              }
              params.append('accountId', this.$cookie.get('accountId'))
              params.append('createType', 0)
              this.$api.management.addPerson(params, {
                headers: {
                  'Content-type': 'application/x-www-form-urlencoded;charset=utf-8'    //multipart/form-data; charset=utf-8
                }
              }).then((data) => {
                let result = data.data
                if(result.code == 200) {
                  this.$refs.addForm.resetFields();
                  this.$refs.profileupload.clearFiles()
                  this.imageUrl = ''
                  this.isShow = false
                  this.$parent.getList()
                } else {
                  this.$message({
                    showClose: true,
                    type: 'error',
                    message: result.msg
                  })
                }
                this.addButDisable = this.addButLoad = false
              })
              .catch(err => {
                this.addButDisable = this.addButLoad = false
                this.catchErrorHandle(err)
              })
              },300)
          } else {
            return false
          }
        } catch (error) {
          this.addButDisable = this.addButLoad = false
        }
      })
    },
    closeDialog() {
      this.profileFormData = null
      this.$refs.profileupload.clearFiles()
      this.imageUrl = ''
      this.$refs.addForm.resetFields()
      this.isShow = false
      // this.$parent.getTableData()
    }
  }
}
</script>