<template>
  <el-dialog
    :title="dialogObj.title"
    center
    append-to-body
    :visible.sync="dialogObj.show"
    width="800px">
    <div v-loading="loading">
      <el-form ref="form" :model="form" label-width="120px" :rules="rules" :disabled="dialogObj.read">
        <el-form-item label="课程标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="课程封面(670*472)">
          <el-upload
            action="/api/public/upload"
            :http-request="uploadFileMain"
            :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-row>
          <el-col :span="10">
            <el-form-item label="课程类型">
              <el-select v-model="form.type" placeholder="请选择课程类型" @change="selectedLesson = [],selectedLessonList = []">
                <el-option label="月课" :value="0"></el-option>
                <el-option label="日课" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="选择课程">
              <el-cascader
                clearable
                :value="selectedLesson"
                :options="showLessonList"
                :show-all-levels="false"
                @active-item-change="changLessonItem"
                @change="selectLesson"
                :props="{label: 'name',value:'id',children:'children'}"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="已选课程">
              <div class="selected-block" v-for="(data, index) in selectedLessonList" :key="index">
                <el-card shadow="always">
                  <div class="name">{{index+1}}.{{data.name}}</div>
                  <div class="move" v-if="!dialogObj.read">
                    <img class="directionIcon" :src="upSrc" v-if="index !== 0" @click="moveItem(index-1,index)"/>
                    <img class="directionIcon" :src="downSrc" v-if="index !== selectedLessonList.length - 1" @click="moveItem(index,index+1)"/>
                    <i class="el-icon-delete grey" @click="delLesson(data)"></i>
                    <!--<el-button type="info" icon="el-icon-sort-up" v-if="index !== 0" @click="moveItem(index-1,index)" round size="mini"></el-button>-->
                    <!--<el-button type="info" icon="el-icon-sort-down" v-if="index !== selectedLessonList.length - 1" @click="moveItem(index,index+1)" round size="mini"></el-button>-->
                    <!--<el-button type="text" class="button" v-if="index !== 0" @click="moveItem(index-1,index)">上移</el-button>-->
                    <!--<el-button type="text" class="button" v-if="index !== selectedLessonList.length - 1" @click="moveItem(index,index+1)">下移</el-button>-->
                    <!--<el-button type="danger" icon="el-icon-close" @click="delLesson(data)" circle size="mini"></el-button>-->
                  </div>
                </el-card>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="选择盒子">
              <el-cascader
                clearable
                :value="selectedBox"
                :options="showBoxList"
                :show-all-levels="false"
                @change="selectBox"
                expand-trigger="hover"
                :props="{label: 'name',value:'id',children:'children'}"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="已选盒子">
              <div class="selected-block" v-for="(data,index) in selectedBoxList" :key="data.id">
                <el-card shadow="always">
                  <div class="name">{{data.name}}</div>
                  <div class="move" v-if="!dialogObj.read">
                    <img class="directionIcon" :src="upSrc" v-if="index !== 0" @click="moveBox(index-1, index)">
                    <img class="directionIcon" :src="downSrc" v-if="index !== selectedBoxList.length - 1" @click="moveBox(index, index+1)">
                    <i class="el-icon-delete grey" @click="delBox(data)"></i>
                    <!--<el-button type="danger" icon="el-icon-close" @click="delBox(data)" circle size="mini" style="float: right;padding: 3px"></el-button>-->
                  </div>
                </el-card>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer" v-if="dialogObj.type !== 2 && !dialogObj.read">
        <el-button @click="dialogObj.show = false">取 消</el-button>
        <el-button type="primary" @click="sub">确 定</el-button>
      </span>
    </div>
  </el-dialog>

</template>

<script>
  import {getCategoryApi,getBoxTypeListApi,addLessonApi,getLessonDetailApi,editLessonApi,uploadFileApi} from "../../service/api";
  import downSrc from "../../assets/down.png"
  import upSrc from "../../assets/up.png"
  export default {
    name: "dialogObj",
    props:[
      'dialogObj'
    ],
    data(){
      return{
        selectedLesson:[],
        selectedLessonList:[],
        lessonList:[],
        showLessonList:[],
        selectedBox:[],
        selectedBoxList:[],
        boxList:[],
        showBoxList:[],
        imageList:[],
        loading:false,
        uploadShow:true,
        downSrc: downSrc,
        upSrc: upSrc,
        form:{
          title:'',
          type:0,
          text_category_ids:[],
          item_category_ids:[],
          cover:0,
        },
        rules:{
          title:[
            { required: true, message: '请输入课程标题', trigger: 'change' }
          ]
        }
      }
    },
    methods:{
      handleItemChange(val){

      },
      changLessonItem(){
        if(this.form.type === 0){
          this.showLessonList.forEach(a=>{
            a.children =  a.children || [];
            a.children.forEach(b=>{
              if(b.children){
                delete b.children
              }
            })
          })
        }else{
          this.showLessonList = this.lessonList
        }
      },
      delLesson(data){
        this.selectedLessonList = this.selectedLessonList.filter(i=>{
          return i.id !== data.id
        })
      },
      delBox(data){
        this.selectedBoxList = this.selectedBoxList.filter(i=>{
          return i.id !== data.id
        })
      },
      selectLesson(data){
        let select = this.showLessonList.find(i=>{return i.id === data[0]});
        if (select.children) {
          select = select.children.find(i=>{return i.id === data[1]});
        } else {
            return
        }
        if(data.length === 3)select = select.children.find(i=>{return i.id === data[2]});
        let index = this.selectedLessonList.findIndex(val => val === select);
        if (index === -1){
          this.selectedLessonList.push(select)
        } else {
          this.$message({
            type: 'info',
            message: '不能重复添加!'
          });
        }
      },
      selectBox(data){
        let select = this.showBoxList.find(i=>{return i.id === data[0]});
        let index = this.selectedBoxList.findIndex(val => val === select);
        if (index === -1){
          this.selectedBoxList.push(select)
        } else {
          this.$message({
            type: 'info',
            message: '不能重复添加!'
          });
        }

      },
      sub(){
        this.$refs['form'].validate((valid) => {
          let itemIds = [];
          let textIds = [];
          this.selectedBoxList.forEach(i=>{itemIds.push(i.id)});
          this.selectedLessonList.forEach(i=>{textIds.push(i.id)});
          if(this.imageList[0]){
            this.form.cover = this.imageList[0].name;
          }
          let json = this.form;
          json.item_category_ids = itemIds.toString();
          json.text_category_ids = textIds.toString();
            if(valid){
              if (!this.form.cover) {
                this.$message({
                  type: 'error',
                  message: '请上传封面!'
                });
                return
              }
              if (!json.text_category_ids) {
                this.$message({
                  type: 'error',
                  message: '请选择课程!'
                });
                return
              }
              switch(this.dialogObj.type){
                case 1:
                  // this.$refs['form'].validate((valid) => {
                  //     if(valid){
                  editLessonApi(this.dialogObj.id,json).then(res=>{
                    this.$message({
                      type: 'success',
                      message: '修改成功!'
                    });
                    this.$emit("reflash");
                    this.dialogObj.show = false;
                  });
                  //     }
                  // });
                  break;
                case 0:
                  // this.$refs['form'].validate((valid) => {
                  //   if(valid){
                  addLessonApi(json).then(res=>{
                    this.$message({
                      type: 'success',
                      message: '新增成功!'
                    });
                    this.$emit("reflash");
                    this.dialogObj.show = false;
                  })
                  //   }
                  // });
                  break
              }
            }
        })
      },
      initDialog(){
        getBoxTypeListApi().then(res=>{
          if(res){
          this.boxList = res;
          this.showBoxList = JSON.parse(JSON.stringify(res))
          }
        });
        getCategoryApi().then(res=>{
          this.lessonList = res;
          this.showLessonList = JSON.parse(JSON.stringify(res))
          switch(this.dialogObj.type){
            case 0:
              this.form={
                title:'',
                type:0,
                text_category_ids:[],
                item_category_ids:[],
                cover:0,
              };
              this.uploadShow = true;
              this.imageList = [];
              this.selectedLessonList = [];
              this.selectedBoxList = [];
              break;
            case 1:
              getLessonDetailApi(this.dialogObj.id).then(resL=>{
                this.form={
                  title:resL.title,
                  type:resL.type,
                  text_category_ids:[],
                  item_category_ids:[],
                  cover:'',
                };
                this.imageList = [{name:resL.cover,url: process.env.IMAGE_URL_HEAD + resL.cover}];
                this.uploadShow = false;
                this.selectedLessonList = [];
                this.selectedBoxList = [];
                if(resL.type === 0){
                  resL.detail['0'].forEach(i=>{
                    this.selectLesson([i.pid,i.id])
                  });
                }else if(resL.type === 1){
                  resL.detail['1'].forEach(t=>{
                    let x = this.showLessonList.find(i=>{
                        i.children = i.children || [];
                        return i.children.find(j=>{return j.id === t.pid})
                    })
                    this.selectLesson([x.id,t.pid,t.id])
                  })
                }
                if(resL.detail['2']){
                  resL.detail['2'].forEach(i=>{
                    this.selectBox([i.id])
                  });
                }

              });
              break;
            case 2:
              this.title = '编辑';
              this.show = this.dialogObj.show;
              this.id = this.dialogObj.id;
              this.type = 2;
//            getTeacherDetailApi(this.id).then(res=>{
//              this.form.name = res.name;
//              this.form.alias = res.alias;
//              this.form.qr = res.qr;
//              this.form.type = res.type;
//              this.form.status = res.status;
//              this.loading = false
//            });
              break
          }
        });
      },
      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}]
      },
      uploadFileMain(a){
        this.$store.dispatch('setProgress',{type:'new',id:a.file.uid});
        this.fileUid = a.file.uid;
        uploadFileApi({file:a.file,type:'local'}).then(res=>{
          this.form.cover = process.env.IMAGE_URL_HEAD + res.url;
          this.imageList[0] = {name:res.url,url:process.env.IMAGE_URL_HEAD + res.url,title:'',lable:''};
        })
      },
      moveBox(first,second){
        let list = this.selectedBoxList;
        let oFirst = list[first];
        let oSecond = list[second];
        this.selectedBoxList.splice(first,1,oSecond);
        this.selectedBoxList.splice(second,1,oFirst);
      },
      moveItem(first,second){
        let list = this.selectedLessonList;
        let oFirst = list[first];
        let oSecond = list[second];
        this.selectedLessonList.splice(first,1,oSecond);
        this.selectedLessonList.splice(second,1,oFirst);
      }
    },
    watch:{
//      dialogObj(){
//        this.initDialog()
//      }
    },
    mounted(){
      this.initDialog()
    }
  }
</script>

<style scoped lang="less">
  .el-col{
    /*height: 50px;*/
    text-align: center;
    margin-bottom: 20px;
    line-height: 40px;
    .el-select{
      width: 100%;
    }
    img{
      width: 50px;
      border-radius: 100px;
    }
    label{
      color: #5982e6;
    }
  }
  .dialog-footer{
    display: block;
    text-align: center;
  }
  .selected-block{
    width: 46%;
    white-space: nowrap;
    height: auto;
    padding: 5px;
    margin: 0;
    text-align: left;
    float: left;
  }
  .move {
    display: flex;
    flex-flow: row;
    justify-content: flex-end;
    align-items: center;
    margin: 3px;
  }
  .name {
    line-height: 20px;
  }
  .directionIcon {
    width: 16px !important;
  }
  .grey {
    color: #666;
  }
</style>
<style>
  .disabled .el-upload--picture-card {
    display: none !important;
  }
  .el-card__body {
    padding: 3px 10px;
  }
</style>