<!-- 课程创建/修改 -->

<template>
  <div class="pjc">
    <el-page-header @back="$router.go(-1)" :content="title" style="margin-bottom: 30px;"></el-page-header>
    <!-- <h3>{{ title }}</h3> -->
    <el-form :model="courseDeail" label-width="110px" :rules="rules">
      <el-form-item label="课程名称:" prop="name">
        <el-input :maxlength="30"  show-word-limit v-model.trim="courseDeail.name" style="width: 40%" placeholder="输入课程名称，最多30字符"></el-input>
      </el-form-item>
      <el-form-item label="预览图:" prop="thumb">
        <uploadOss
          :headers="$xtoken"
          :action="$action"
          :limit="1"
          list_type="picture-card"
          :accept="$acceptImg"
          :multiple="true"
          ref="clearPicture"
          coursePath="course"
          :show-file-list="true"
          :file-list="courseDeail.thumb"
          :on-success="handleFilesSuccess2"
          :on-preview="onFilePreView"
          :before-upload="beforeUpload"
          :on-remove="onFileRemove2"
        >
          <i class="el-icon-plus"></i>
        </uploadOss>
        <!-- <div style="display: flex;">
          <div style="cursor: pointer;margin-right: 10px;" @click="showApm(courseDeail.thumb)">
            <userImage
            v-if="courseDeail.thumb"
            width="100px"
            height="100px"
            radius="5px"
            :img_url="courseDeail.thumb"
            :user_name="courseDeail.name"
          ></userImage>
          </div>
          <div class="cursor"  @click="showSelectImg(1)">
            <div><i class="el-icon-plus"></i></div>
          </div>
        </div> -->
      </el-form-item>
      <el-form-item label="价格:" prop="price">
        <!-- <el-input-number
          v-model="courseDeail.price"
          :min="0"
          :max="10000000"
          label="课程价格"
        ></el-input-number> -->
        <el-input v-model="courseDeail.price" maxlength="6" style="width: 150px;" placeholder="请输入价格" size="normal" clearable></el-input>
      </el-form-item>
      <el-form-item label="浏览量:" prop="price">
        <el-input-number
          v-model="courseDeail.baseClick"
          :min="0"
          :max="10000000"
          label="浏览次数"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="是否上架:">
        <el-switch
          v-model="courseDeail.enable"
          active-color="#13ce66"
          inactive-color="#999"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="课程介绍:" prop="images">
        <uploadOss
          :headers="$xtoken"
          :action="$action"
          :limit="23"
          list_type="picture-card"
          :accept="$acceptImg"
          :multiple="true"
          ref="clearPicture"
          coursePath="course"
          :show-file-list="true"
          :file-list="courseDeail.images"
          :on-success="handleFilesSuccess"
          :on-preview="onFilePreView"
          :before-upload="beforeUpload"
          :on-remove="onFileRemove"
        >
          <i class="el-icon-plus"></i>
        </uploadOss>
      </el-form-item>
      
      <el-form-item label="课程章节" size="normal">
        <div class="sectionout">
          <div
            class="sectionInner"
            v-for="(item, index) in courseDeail.sections"
            :key="index"
          >
            <div class="sectionName">
              <el-input v-model.trim="item.name" placeholder="请输入章节名..."></el-input>
            </div>
            <div class="sectionUrl">
              <el-input v-model.trim="item.link" placeholder="请输入章节链接..."></el-input>
            </div>
            <div class="del">
              <el-button
                type="text"
                size="mini"
                plain
                @click="sectionDel(index, item)"
                style="color: #f89881"
                >删除</el-button
              >
            </div>
          </div>
          <div class="addSection">
            <el-button plain @click="addSection">+</el-button>
          </div>
        </div>
      </el-form-item>

      <el-form-item style="display: flex; flex-direction: row-reverse">
        <el-button @click="$router.go(-1)">取消</el-button>
        <el-button @click="iffirm">{{ alterCreate }}</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <image-cropper
      v-loading="company_img_loading"
      field="file"
      :width="imgWidth"
      :height="imgHeight"
      :url="'https://integralsys.oss-cn-shenzhen.aliyuncs.com'"
      @close="company_img_show = false"
      @crop-upload-success="company_img_success"
      langType="zh"
      v-if="company_img_show"
    ></image-cropper>
  </div>
</template>
<script>
import ImageCropper from "@/components/ImageCropper";
import uploadOss from '@/components/upload';
import { validateURL } from "@/utils/validate";
import {createCourse,updataCourse,getCourseDetail} from '../api'
export default {
  name: "courseEdit",
  components: { ImageCropper,uploadOss },
  data() {
    return {
      curId: 0,
      title: "",
      company_img_show: false,
      company_img_loading: false,
      alterCreate: "保存",
      imgIndex: 1,
      imgWidth: 300,
      imgHeight: 300,
      // 个人信息
      courseDeail: {
        name: "",
        price: 0,
        baseClick:100,
        thumb: [],
        enable: true,
        images: [],
        sections: [],
      },
      dialogVisible: false,
      dialogImageUrl: "",
      rules: {
          name: [
            { required: true, message: '请输入课程名称', trigger: 'blur' },
            { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
          ],
          price: [
            { required: true, message: '请输入课程价格', trigger: 'blur' },
          ],
          baseClick: [
            { required: true, message: '请输入浏览量', trigger: 'blur' },
          ],
          thumb: [
            { required: true, message: '请选择预览图', trigger: 'change' },
            {type:'array',trigger:'change'}
          ],
          images: [
            { required: true, message: '请选择介绍图', trigger: 'change' },
            {type:'array',trigger:'change'}
          ],
        }
    };
  },
  computed: {
    courseImages() {
      if (this.courseDeail.images) {
        return this.courseDeail.images.split(",");
      } else {
        return [];
      }
    },
  },
  methods: {
    // 介绍图上传格式
    beforeUpload(file) {
      const isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG,PNG,JPEG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return isJPG && isLt2M;
    },
    //介绍图预览
    onFilePreView(file) {
      this.showApm(file.url)
    },
    // 介绍图删除
    onFileRemove(file, fileList) {
      this.courseDeail.images = fileList
    },
    // 介绍图上传
    handleFilesSuccess(response, file, fileList) {
      let fileListData = fileList.filter(e => {
        return e.url;
      });
      this.courseDeail.images = fileListData
    },
    // 预览图删除
    onFileRemove2(file, fileList) {
      this.courseDeail.thumb = fileList
    },
    // 预览图上传
    handleFilesSuccess2(response, file, fileList) {
      let fileListData = fileList.filter(e => {
        return e.url;
      });
      this.courseDeail.thumb = fileListData
    },
    //章节信息校验
    validateURL() {
      let result = false;
      result = this.courseDeail.sections.every((item) => {
        let reg = /^[^\u4e00-\u9fff]*$/
        return item.link !== "" &&  reg.test(item.link) && item.name !== "";
        // return validateURL(item.link) && item.name !== "";
      });
      return result;
    },
    // 获取课程详情
    getCourseDetail() {
      getCourseDetail(this.curId).then((res) => {
          this.courseDeail = this.uploadToData(res);
      }).catch(err=>{
        console.error(err)
      });
    },
    //课程详情数据转换展示
    uploadToData(data) {
      data.enable = data.enable == 1 ? true : false;
      // data.price = Number(data.price);
      let arr = []
      data.images.forEach(item=>{
        arr.push({name:item,url:item})
      })
      data.images = arr
      let arr2 = []
      data.thumb.split(',').forEach(item=>{
        arr2.push({name:item,url:item})
      })
      data.thumb = arr2
      return data;
    },
    //预览图上传成功回调
    company_img_success(resData) {
      if (this.imgIndex == 1) {
        this.courseDeail.thumb = resData.url;
      } else {
        if (
          this.courseDeail.images.split(",").length == 1 &&
          this.courseDeail.images.split(",")[0] == ""
        ) {
          this.courseDeail.images = resData.url;
        } else {
          this.courseDeail.images = `${this.courseDeail.images},${resData.url}`;
        }
      }
      this.company_img_show = false;
    },
    // 查看预览图
    showApm(url){
      this.dialogVisible = true;
      this.dialogImageUrl = url;
    },
    //打开上传预览图片组件
    showSelectImg(type) {
      this.imgIndex = type;
      this.company_img_show = true;
    },
    //展示数据转换成上传数据
    toUpdata() {
      let data = JSON.parse(JSON.stringify(this.courseDeail));
      data.enable = data.enable ? 1 : 0;
      data.sections = JSON.stringify(data.sections);
      let arr = data.images.map(item=>{
        return item.url
      })
      data.images = arr.join(',')
      let arr2 = data.thumb.map(item=>{
        return item.url
      })
      data.thumb = arr2.join(',')
      return data;
    },
    // 添加课程
    addSection() {
      let section = {
        name: "",
        link: "",
      };
      this.courseDeail.sections.push(section);
    },
    // 删除章节
    sectionDel(index, item) {
      this.$confirm("确定删除当前章节？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.courseDeail.sections.splice(index, 1);
        })
        .catch((err) => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    //保存
    iffirm() {
      if (
        !this.courseDeail.name == "" &&
        this.courseDeail.images.length &&
        this.courseDeail.thumb.length &&
        this.courseDeail.price &&
        this.courseDeail.baseClick != undefined &&
        this.validateURL()
      ) {
        this.$confirm("确定保存当前课程信息？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "info",
        })
          .then(() => {
            if (this.$route.params.id) {
              this.saveAlter();
            } else {
              this.saveCreate();
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
      } else if (!this.validateURL()) {
        this.$message({
          type: "warning",
          message: "章节列表未填写正确",
        });
      } else {
        this.$message({
          type: "warning",
          message: "课程信息未填写完整",
        });
      }
    },
    //修改保存
    saveAlter() {
      let data = this.toUpdata();
      updataCourse(this.curId,data).then(res=>{
        this.$message({
            message: "修改成功！",
            type: "success",
            showClose: true,
            duration: 2000,
          });
          this.$router.push("/course/courseManage");
      }).catch(err=>{
        console.error(err)
      })
    },
    //保存新建课程
    saveCreate() {
      let data = this.toUpdata();
      createCourse(data).then(res=>{
        this.$message({
            message: "新建成功！",
            type: "success",
            showClose: true,
            duration: 2000,
          });
          this.$router.push("/course/courseManage");
      }).catch(err=>{
        console.error(err)
      })
    },
    //判断新建/修改
    init() {
      if (this.$route.params.id == undefined) {
        this.title = "添加课程";
        this.courseDeail = {
          name: "",
          price: 0,
          thumb: [],
          enable: true,
          baseClick:100,
          images: [],
          sections: [],
        };
      } else {
        this.curId = this.$route.params.id;
        this.title = "编辑课程";
        this.getCourseDetail();
      }
    },
  },
  created() {
    this.init();
  },
};
</script>

<style scoped lang="scss">
.pjc {
  width: 900px;
  height: auto;
  margin: 0 auto;
  margin-top: 10px;
  background-color: #fff;
  border-radius: 5px;
  padding: 30px 60px;
  h3 {
    color: #000;
    text-align: center;
    margin: 30px 0;
  }
  form {
    legend {
      font-size: 20px;
      color: #000;
      line-height: 30px;
      font-weight: bold;
      margin-bottom: 22px;
    }
    .el-form-item {
      .el-select {
        width: 380px;
      }
    }
  }
}
.sectionout {
  .sectionInner {
    display: flex;
    // justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    .sectionName {
      width: 150px;
      margin-right: 20px;
    }
    .sectionUrl {
      width: 250px;
      margin-right: 20px;
    }
    .sectionDel {
    }
  }
}
.img_all {
  display: flex;
  flex-wrap: wrap;
  & > div {
    margin-right: 10px;
    margin-bottom: 10px;
  }
  .imgout{
    position: relative;
    .imgDelete{
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      position: absolute;
      left:0;
      top:0;
      background-color: rgba(0,0,0,.3);
      opacity: 0;
      transition: opacity 0.3s ease;
    } 
    &:hover{
      .imgDelete{
        opacity:1;
      }
    }
  }
}
.cursor {
  & > div {
    height: 100px;
    width: 100px;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 5px;
    font-size: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    i{
      font-size: 28px;
      color: #8c939d;
    }
  }
}
</style>
