<template>
  <div class="flex-container">
    <a-form :form="Formtable">
      <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="活动标题">
        <a-input placeholder="活动标题" v-decorator="[ 'title', {rules: [{ required: true, message: '活动标题不能为空！' ,whitespace:true}]} ]"></a-input>
      </a-form-item>
      <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="活动详情">
        <a-input placeholder="活动详情" v-decorator="[ 'desc', {rules: [{ required: true, message: '活动详情不能为空！' ,whitespace:true}]} ]"></a-input>
      </a-form-item>
      <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="活动积分">
        <a-input placeholder="活动积分" v-decorator="[ 'integral', {rules: [{ required: false, type:'number', message: '活动积分不能为空！' ,transform:(value)=> {return Number(value)} }]} ]"></a-input>
      </a-form-item>
      <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="活动类型">
        <a-radio-group  v-decorator="['activityType', {rules: [{ required: true, message: '活动类型不能为空！'}]} ]">
          <a-radio value="个人活动">个人活动</a-radio>
          <a-radio value="团队活动">团队活动</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="活动小类">
        <a-select placeholder="请选择" v-decorator="[ 'subclass', {rules: [{ required: true, message: '活动小类不能为空！' ,whitespace:true}]} ]">
          <a-select-option key="">请选择</a-select-option>
          <a-select-option key="部长考核">部长考核</a-select-option>
          <a-select-option key="前置营销">前置营销</a-select-option>
          <a-select-option key="线上活动">线上活动</a-select-option>
          <a-select-option key="线下活动">线下活动</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="活动封面图片">
        <a-upload :beforeUpload="uploadPicture" >
          <a-button> <a-icon type="upload" /> 上传图片 </a-button>
        </a-upload>
      </a-form-item>
      <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="活动范围">
        <a-select v-model="modifyForm.range">
          <a-select-option key="全市">全市</a-select-option>
          <a-select-option v-for="d in subNames" :key="d.value" :value="d.value">{{d.text}}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="排序号">
        <a-input  v-decorator="[ 'sort', {rules: [{ required: true, type:'number', message: '排序号不能为空！' ,whitespace:true,transform:(value)=> {return Number(value)}  }]} ]"></a-input>
      </a-form-item>
      <a-form-item>
        <a-button style="width:200px;margin-left: 35%" @click="createfunctionOk()" type="primary">提交</a-button>
      </a-form-item>
      </a-form>
  </div>
</template>

<script>
import {initSubstName} from "../../../api/school-center/userManager/newUserAPI";
import {addActivity, uploadImg} from "../../../api/school-center/activity/activityAPI";

export default {
  name: "addActivity",
  data: function () {
    return {
      Formtable: this.$form.createForm(this, {name: 'Formtable'}),
      modifyForm: {
        id: '',
        title: '',
        desc: '',
        integral: '',
        activityType: '',
        subclass: '',
        imageUrl: '',
        range: '',
        sort: '',
      },
      subNames: [],
      chosePages:[],
    }
  },
  mounted() {
    this.initSubstName();
  },
  methods:{
    initSubstName() {
      initSubstName().then((res) => {
        if (res.state == "success") {
          const result = res.data
          result.forEach((r) => {
            if (r.subName === 'null')
              return;
            this.subNames.push({
              value: r.subName,
              text: r.subName
            })
          })
        }
      })
    },
    uploadPicture(file) {
      let fileSize = file.size/1024/1024
      if(fileSize > this.pictureSize){
        this.$message.error('上传失败！图片大小不能超过'+this.pictureSize+'M',5);
        return new Promise(resolve => {
          console.log(resolve);
        })
      }else {
        return new Promise(resolve => {
          console.log(resolve);
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => {
            const img = document.createElement('img');
            img.src = reader.result;
            img.onload = () => {
              const  limitWidth = arguments[2] ? arguments[2] : 640;
              const  width = img.width > limitWidth ? limitWidth : img.width;
              const height = img.width > limitWidth ? parseInt((img.height * limitWidth) / img.width) : img.height;
              const canvas = document.createElement('canvas');
              const  ctx = canvas.getContext('2d');
              canvas.width = width
              canvas.height = height
              ctx.fillStyle = '#fff'
              ctx.fillRect(0,0,canvas.width,canvas.height)
              ctx.drawImage(img,0,0,width,height)
              const picture = canvas.toDataURL('image/jpeg')
              return uploadImg({picture}).then(res => {
                if(res == 'error'){
                  this.$message.error('上传失败！',5);
                }
                if(res.state == 'success'){
                  this.modifyForm.imageUrl = res.data;

                  this.$message.success('上传成功',5);
                }
              })
            };
          };
        });
      }
    },
    //提交表单
    createfunctionOk(){
      this.Formtable.validateFields(['title', 'desc',"integral","activityType", 'subclass', 'sort',"range" ], {force: true}, (err, values)=>{
        if (!err){
          debugger
          this.modifyForm.title=values.title
          this.modifyForm.desc=values.desc
          this.modifyForm.integral=values.integral
          this.modifyForm.activityType=values.activityType
          this.modifyForm.subclass=values.subclass
          this.modifyForm.sort=values.sort

          this.chosePages.forEach(value => {
            if (value!=undefined){
              this.modifyForm.chosePages=value+","+this.modifyForm.chosePages
            }
          })

          //插入数据
          if (this.modifyForm.id==""){
            for (let key in this.modifyForm) {
              if (this.modifyForm[key]==undefined){
                this.modifyForm[key]=""
              }
            }
            addActivity(this.modifyForm).then(res=>{
              if (res.state=="success") {
                this.$message.success(res.data ? res.data : '添加成功！', 5);
                this.createfunctionCancel();
                return null;
              }
              this.$message.error(res.data ? res.data : '添加失败！', 5);
            })
            return null;
          }
        }
      })
    },
    createfunctionCancel(){
      this.Formtable.setFieldsValue({
        id: '',
        title: '',
        desc: '',
        integral: '',
        activityType: '',
        subclass: '',
        imageUrl: '',
        range: '',
        sort: '',
      })
      this.modifyForm.id=""
      this.modifyForm.range = ""
      this.modifyForm.chosePages=""
      this.chosePages.splice(0,this.chosePages.length)
      this.modifyvisible=false;
    },
  },
}
</script>

<style scoped>
.ant-form-item {
  margin-bottom: 5px;
}
</style>
