<template>
  <el-dialog :title="dialogObj.title" :visible.sync="dialogObj.show">
    <el-form ref="form" :model="form" label-width="120px">
      <el-form-item label="期数" v-if="!this.dialogObj.periodsId">
        <el-cascader
          class="refresh-cascader-multi width-480"
          style="width: 480px"
          :options="goodsList"
          :props="{value:'id',label:'name'}"
          @active-item-change="handleItemChange"
          @change="changePeriods"></el-cascader>
      </el-form-item>
      <el-form-item label="老师">
        <el-select v-model="form.teacher_id" placeholder="请选择" filterable @change="selectName(teacherList,form.teacher_id)">
          <el-option
            v-for="(data,index) in teacherList"
            :key="index"
            :label="data.name"
            :value="data.id" >
          </el-option>
        </el-select>
      </el-form-item>
       <el-form-item label="班级名称">
        <el-input v-model="form.class_name" style="width:220px"></el-input>
      </el-form-item>
      <el-form-item label="最大学员">
        <el-input-number v-model="form.max_join_num"></el-input-number>
      </el-form-item>
      <el-form-item label="活动方案">
        <el-select
          v-model="form.source" placeholder="请选择" filterable
          :popper-class="'refresh-select-multi width-480'"
          style="width: 480px">
          <el-option
            v-for="(data,index) in classSource"
            :key="index"
            :label="data.name"
            :value="data.type" >
          </el-option>
        </el-select>
      </el-form-item>
      <!--<el-form-item label="班级二维码">
        &lt;!&ndash;<el-input v-model="form.qr"></el-input>&ndash;&gt;
        <el-upload
          action="/api/public/upload/zone"
          :http-request="uploadFile"
          :class="{disabled:!uploadShow}"
          :before-upload="beforeAvatarUpload"
          list-type="picture-card"
          :file-list="imageList"
          :on-success="handleAvatarSuccess"
          :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>-->
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="dialogObj.show = false">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </span>
  </el-dialog>
</template>

<script>
  import {getTeacherListApi,getClassDetailApi,editClassApi,addClassApi,getPeriodsApi,getGoodsListApi,getPeriodsTeacherApi,uploadFileApi,getSourceStudentApi} from "../../service/api";
  import {GOODSTYPE,CLASSSOURCE} from '../../util/wordbook';
  export default {
    props:[
      'dialogObj'
    ],
    data(){
      // let classSource=[];
      // for (let x in CLASSSOURCE ) {
      //   classSource.push({label:CLASSSOURCE[x],value:Number(x)})
      // }
      return{
        imageList:[],
        form:{
          teacher_id:'',
          max_join_num:'',
          class_name:"",
          source:"",
          qr:""
        },
        type:0,
        classSource:[],
        teacherList:[],
        exitTeacherList: [],
        goodsList: [],
        periods: {},
        uploadShow: true
      }
    },
    methods:{
      beforeAvatarUpload(){
        this.uploadShow = false
      },
      handleRemove(){
        this.uploadShow = true
      },
      handleAvatarSuccess(res) {
        this.imageList = [{name:res.data.url,url:process.env.IMAGE_URL_HEAD + res.data.url}]
      },
      uploadFile(a) {
        this.loading = true;
        this.$store.dispatch('setProgress',{type:'new',id:a.file.uid});
        this.fileUid = a.file.uid;
        uploadFileApi({file:a.file,type:'all'}).then(res=>{
          this.form.media_id = res.wechat_info ? res.wechat_info.media_id : '';
          this.imageList = [{name:res.url,url:process.env.IMAGE_URL_HEAD + res.url}];
          this.uploadShow = false;
          this.loading = false;
          this.$message({
            type: 'success',
            message: '上传成功!'
          });
        }).catch(()=>{
          this.loading = false;
        })
      },
      findDifferentArray(array1, array2){
        let newArray = [];
        array1.forEach((val)=>{
            let index = array2.findIndex((item)=>{
                return item.teacher_id === val.id
            })
            if (index === -1) {
              newArray.push(val)
            }
        })
        return newArray
      },
      getTeacher(){
        getTeacherListApi({limit:100,status:0}).then(res=>{
            this.teacherList = res.list
        });
      },
      getTeacherByPeriods(){
          getTeacherListApi({limit:100,status:0}).then(res=>{
              this.teacherList = res.list
        })
      },
      initPage(){
        // 1为编辑
        getSourceStudentApi().then(res=>{
          this.classSource = res
        })
        this.periods = this.dialogObj.periods
        switch (this.dialogObj.type) {
          case 0:
            if(!this.dialogObj.periodsId){
              this.getPeriodList();
            }
            this.form = {
              teacher_id:'',
              max_join_num:'',
              source:'',
              qr:""
            };
            this.type = 0;
            this.uploadShow = true
            this.getTeacher();
            break;
          case 1:
          this.type = 1;
            getClassDetailApi(this.dialogObj.id).then(res=>{
              this.form = {
                teacher_id: parseInt(res.teacher_id),
                max_join_num:res.max_join_num,
                class_name:res.class_name,
                source:res.source,
              };
              if(res.qr){
                this.form.qr = res.qr
                this.imageList = [{name:res.qr,url:res.qr}];
              }
              this.form.media_id = res.media_id ? res.media_id : '';
              this.uploadShow = !res.qr
              console.log(this.uploadShow)
              this.getTeacher();
            })
        }
      },
      getPeriodList(){
        getGoodsListApi().then(res=>{
          res.list.forEach(i=>{
             i.name = '[' + GOODSTYPE[i.goods_type] + ']' + '[' +i.current_price / 100 + '元]' + i.name
            i.children = [];
          });
          this.goodsList = res.list;
          if(!this.periods) {
            getPeriodsApi({goods_id:this.goodsList[0].id}).then(res=>{
              res.list.forEach(i=>{i.name = i.title});
              this.goodsList[0].children = res.list;
              this.periods = res.list[0]
            })
          }
        });
      },
      onSave(){
        if(this.imageList.length > 0){
            this.form.qr = this.imageList[0].url;
        }
        let json = {
          max_join_num:String(this.form.max_join_num),
          teacher_id:String(this.form.teacher_id),
          source : this.form.source,
          class_name:this.form.class_name,
          media_id:this.form.media_id
        };
        if(this.form.qr){
          json.qr = this.form.qr
        }
        console.log(json)
        switch (this.dialogObj.type) {
          case 0:
            let id = this.dialogObj.periodsId ? this.dialogObj.periodsId : this.periods.id;
            addClassApi(id,json).then(res=>{
              this.$message({
                type: 'success',
                message: '添加成功!'
              });
              this.$emit("reflash", this.periods);
              this.dialogObj.show = false;
            });
            break;
          case 1:
            editClassApi(this.dialogObj.id,json).then(res=>{
              this.$message({
                type: 'success',
                message: '修改成功!'
              });
              this.$emit("reflash",this.periods);
              this.dialogObj.show = false;
            })
        }
      },
      handleItemChange(val){
        getPeriodsApi({goods_id:val[0]}).then(res=>{
          res.list.forEach(i=>{i.name = i.title});
          this.goodsList.find(i=>{return i.id === val[0]}).children = res.list
        })
      },
      changePeriods(data){
        if(data.length>1){
          let nowGoods = this.goodsList.find(i=>{return i.id === data[0]});
          this.periods = nowGoods.children.find(i=>{return i.id === data[1]});
          this.getTeacherByPeriods()
        }
      },
      selectName(val,id){
          let filterVal=val.filter(function(item,i){
                 return item.id == id
              });
              this.form.class_name=filterVal[0].name+"一班";
      }
    },
    watch:{
      'dialogObj.show'(value){
        if(value){
          this.initPage()
        }
      }
    }
  }
</script>

<style scoped>
.qr-img {
    width: 148px !important;
    border: none !important;
    border-radius: 0 !important;
  }
.disabled .el-upload--picture-card {
    display: none !important;
  }
</style>