<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="课堂分类" prop="cateId">
        <el-select v-model="queryParams.cateId" placeholder="请选择" clearable size="small"  @change="getQuerySubCateList(queryParams.cateId)">
          <el-option
              v-for="dict in categoryOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
        </el-select>
      </el-form-item>
      <el-form-item label="课堂子分类" prop="subCateId">
        <el-select v-model="queryParams.subCateId" placeholder="请选择" clearable size="small">
          <el-option
              v-for="dict in querySubCateOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
        </el-select>
      </el-form-item>
      <el-form-item label="课堂名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课堂名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课堂类型" prop="isPrivate">
        <el-select v-model="queryParams.isPrivate" placeholder="请选择" clearable size="small">
          <el-option
              v-for="dict in courseTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs type="card" v-model="queryParams.isShow" @tab-click="handleClick">
      <el-tab-pane label="已上架" name="1"></el-tab-pane>
      <el-tab-pane label="待上架" name="0"></el-tab-pane>
    </el-tabs>
    <el-table height="600" border v-loading="loading" :data="userCourseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程ID" align="center" prop="courseId" />
      <el-table-column label="封面图片" align="center" prop="imgUrl" width="120">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="hover"
          >
            <img slot="reference" :src="scope.row.imgUrl" width="100" >
            <img :src="scope.row.imgUrl" style="max-width: 300px;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="小封面" align="center" prop="secondImg" width="100">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="hover"
          >
            <img slot="reference" :src="scope.row.secondImg" width="50">
            <img :src="scope.row.secondImg" style="max-width: 100px;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="课堂名称" align="center" show-overflow-tooltip prop="courseName" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="分类名称" align="center" prop="cateName" />
      <el-table-column label="子分类名称" align="center" prop="subCateName" />
      <el-table-column label="原价" align="center" prop="price" />
      <el-table-column label="售价" align="center" prop="sellPrice" />
      <el-table-column label="单节积分" align="center" prop="integral" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleCatalog(scope.row)"
          >目录管理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程对话框 -->
    <el-drawer
        :with-header="false"
        size="75%"
         :title="show.title" :visible.sync="show.open" append-to-body>
     <userCourseCatalogDetails  ref="userCourseCatalogDetails" />
   </el-drawer>
  </div>
</template>

<script>
import { listUserCourse, getUserCourse, delUserCourse, addUserCourse, updateUserCourse, exportUserCourse,updateIsShow,putOn,pullOff } from "@/api/course/userCourse";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Editor from '@/components/Editor/wang';
import ImageUpload from '@/components/ImageUpload/index';
import userCourseCatalogDetails from '../../components/course/userCourseCatalogDetails.vue';
import { getAllCourseCategoryList,getCatePidList ,getCateListByPid} from "@/api/course/userCourseCategory";

export default {
  name: "UserCourse",
  components: {
    Treeselect,
    Editor,ImageUpload,userCourseCatalogDetails
  },
  data() {
    return {
      talentParam:{
        phone:null,
        talentId:null
      },
      talentList:[],
      show:{
        title:"目录管理",
        open:false
      },
      activeName:"1",
      projectOptions:[],
      tagsOptions:[],
      tags:[],
      courseTypeOptions:[],
      orOptions: [],
      specShowOptions: [],
      specTypeOptions: [],
      categoryOptions:[],
      subCategoryOptions:[],
      querySubCateOptions:[],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程表格数据
      userCourseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cateId: null,
        subCateId:null,
        title: null,
        imgUrl: null,
        userId: null,
        sort: null,
        status: null,
        isVip: null,
        isHot: null,
        isShow: "1",
        views: null,
        duration: null,
        description: null,
        hotRanking: null,
        integral: null,
        price: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // talentId: [
        //   { required: true, message: "归属达人不能为空", trigger: "change" }
        // ],
        cateId: [
          { required: true, message: "分类不能为空", trigger: "change" }
        ],
        subCateId: [
          { required: true, message: "子分类不能为空", trigger: "change" }
        ],
        courseName: [
          { required: true, message: "课堂名称不能为空", trigger: "blur" }
        ],
        imgUrl: [
          { required: true, message: "封面图片不能为空", trigger: "blur" }
        ],
        secondImg: [
          { required: true, message: "小封面图片不能为空", trigger: "blur" }
        ],
        isTui: [
          { required: true, message: "是否推荐不能为空", trigger: "blur" }
        ],
        isBest: [
          { required: true, message: "是否精选不能为空", trigger: "blur" }
        ],
        isFast: [
          { required: true, message: "是否允许快进不能为空", trigger: "blur" }
        ],
        isAutoPlay: [
          { required: true, message: "是否自动播放不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
        views: [
          { required: true, message: "播放量不能为空", trigger: "blur" }
        ],
        likes: [
          { required: true, message: "点赞数不能为空", trigger: "blur" }
        ],
        favoriteNum: [
          { required: true, message: "收藏数不能为空", trigger: "blur" }
        ],
        shares: [
          { required: true, message: "分享数不能为空", trigger: "blur" }
        ],
        isIntegral: [
          { required: true, message: "是否允许积分兑换不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "原价不能为空", trigger: "blur" }
        ],
        sellPrice: [
          { required: true, message: "售价不能为空", trigger: "blur" }
        ],
        isShow: [
          { required: true, message: "上架状态不能为空", trigger: "blur" }
        ],
        isPrivate: [
          { required: true, message: "公私域不能为空", trigger: "blur" }
        ],
        integral: [
          { required: true, message: "小节兑换积分不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    getCatePidList().then(response => {
        this.categoryOptions = response.data;
    });
    // this.getTreeselect();
    this.getDicts("sys_spec_show").then(response => {
      this.specShowOptions = response.data;
    });
    this.getDicts("sys_spec_type").then(response => {
      this.specTypeOptions = response.data;
    });
    this.getDicts("sys_course_type").then(response => {
      this.courseTypeOptions = response.data;
    });
    this.getDicts("sys_course_project").then(response => {
      this.projectOptions = response.data;
    });
    this.getDicts("sys_course_tags").then(response => {
      this.tagsOptions = response.data;
    });
    this.getDicts("sys_company_or").then(response => {
      this.orOptions = response.data;
    });
  },
  methods: {


    getQuerySubCateList(pid){
      this.queryParams.subCateId=null;
      if(pid == ''){
        this.querySubCateOptions=[];
        return
      }
      this.queryParams.subCateId=null;
      getCateListByPid(pid).then(response => {
        this.querySubCateOptions = response.data;
      });
    },
    handleShow(row) {
      var isShowValue = row.isShow === 0 ? 1 : 0;
      var course = { courseId: row.courseId, isShow: isShowValue };
      updateIsShow(course).then(response => {
        this.msgSuccess("修改成功");
        this.getList();
      });
    },
    handleCatalog(row){
      const courseId = row.courseId;
      this.show.open=true;
        setTimeout(() => {
             this.$refs.userCourseCatalogDetails.getDetails(courseId,row.courseName);
        }, 200);
    },
    handleClick(tab, event) {
      this.queryParams.isShow=tab.name;
      this.getList();
    },
    /** 转换课堂分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.cateId,
        label: node.cateName,
        children: node.children
      };
    },
    getTreeselect() {
      getAllCourseCategoryList().then(response => {
        this.categoryOptions = [];
        const data = this.handleTree(response.data, "cateId", "pid");
        this.categoryOptions=data;
      });
    },
    /** 查询课程列表 */
    getList() {
      this.loading = true;
      listUserCourse(this.queryParams).then(response => {
        this.userCourseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        courseId: null,
        cateId: null,
        subCateId:null,
        title: null,
        imgUrl: null,
        secondImg:null,
        userId: null,
        sort: null,
        createTime: null,
        updateTime: null,
        status: 0,
        isVip: null,
        isAutoPlay: "1",
        isIntegral:"0",
        isShow: "1",
        isFast:"1",
        isTui:"1",
        isBest:"1",
        isNext:"1",
        isPrivate:"0",
        views: 100000,
        duration: null,
        description: null,
        hotRanking: null,
        integral: null,
        price: null,
        likes:100000,
        shares:100000,
        favoriteNum:100000,
        hotNum:100000
      };
      this.tags=[];
      this.subCategoryOptions=[]
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.isShow=this.activeName
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.courseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.talentList=[];
      this.open = true;
      this.title = "添加课程";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.talentList=[];
      const courseId = row.courseId || this.ids
      getUserCourse(courseId).then(response => {
        this.form = response.data;
        // this.form.cateId = response.data.cateId.toString();
        getCateListByPid(this.form.cateId).then(response => {
          this.subCategoryOptions = response.data;
        });
        // this.form.courseType = response.data.courseType.toString();
        if(response.data.project!=null){
          this.form.project = response.data.project.toString();
        }
        if(response.data.tags!=null){
          this.tags = response.data.tags.split(",")
        }
        this.form.isAutoPlay = response.data.isAutoPlay.toString();
        this.form.isShow = response.data.isShow.toString();
        this.form.isBest = response.data.isBest.toString();
        this.form.isFast = response.data.isFast.toString();
        this.form.isIntegral = response.data.isIntegral.toString();
        this.form.isTui = response.data.isTui.toString();
        this.form.isNext = response.data.isNext.toString();
        this.form.isPrivate = response.data.isPrivate.toString();
        this.talentParam.talentId = response.data.talentId;
        this.open = true;
        this.title = "修改课程";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.tags.length>0){
              this.form.tags=this.tags.toString();
            }
            else{
              this.form.tags=null
            }
          if (this.form.courseId != null) {
            updateUserCourse(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUserCourse(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const courseIds = row.courseId || this.ids;
      this.$confirm('是否确认删除课程编号为"' + courseIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUserCourse(courseIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有课程数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportUserCourse(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    putOn() {
      const courseIds =this.ids;
      if(courseIds==null||courseIds==""){
         return this.$message("未选择课程");
      }
      this.$confirm('是否确认批量上架课程?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return putOn(courseIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("上架成功");
        }).catch(function() {});
    },
    pullOff() {
      const courseIds =this.ids;
      if(courseIds==null||courseIds==""){
         return this.$message("未选择课程");
      }
      this.$confirm('是否确认批量下架课程?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return pullOff(courseIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("下架成功");
        }).catch(function() {});
    }
  }
};
</script>
