<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--分类数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-tree
            :data="categoryOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" @submit.native.prevent>
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入标题"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="是否置顶" prop="isTop">
            <el-select v-model="queryParams.isTop" placeholder="请选择" clearable >
              <el-option
                v-for="item in [{'label':'是','value': true},{'label':'否','value':false}]"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </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-row :gutter="10" class="mb8">
          <el-col :span="1.5" >
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['business:cmsNews:add']"
              :disabled="disabledAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['business:cmsNews:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['business:cmsNews:remove']"
            >删除</el-button>
          </el-col>

          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="cmsNewsList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="标题" align="left">
            <template slot-scope="scope">
              <span style="color: #6495ED;cursor: pointer" @click="handleView(scope.row)">{{ scope.row.title }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属分类" align="center" prop="cmsCategory.name" width="200"/>
          <el-table-column label="浏览量" align="center" prop="viewCount" width="140"/>
          <el-table-column label="置顶" align="center" prop="isTop" width="140">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isTop"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="轮播" align="center" prop="carousel" width="140">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.carousel"
                @change="handleCarouselStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="center" prop="createBy" width="150"/>
          <el-table-column label="创建时间" align="center" prop="createTime" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleView(scope.row)"
                v-hasPermi="['production:cmsNews:query']"
              >预览</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['business:cmsNews:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['business:cmsNews:remove']"
              >删除</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-col>
    </el-row>


    <!-- 添加或修改信息管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" style="height: 600px; margin-top: 100px" append-to-body append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择">
            <el-option-group
              v-for="group in selectCategoryOptions"
              :key="group.label"
              :label="group.label">
              <el-option
                v-for="item in group.children"
                :disabled="item.type != 0"
                :key="item.id"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" type="text" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容">
          <wang-editor v-model="form.content" :file-size="1024" v-if="open"/>
        </el-form-item>
        <el-form-item label="浏览量" prop="viewCount">
            <el-input-number v-model="form.viewCount" controls-position="right"   :min="0" placeholder="请输入浏览量" />
        </el-form-item>
        <el-form-item label="是否置顶">
            <el-switch v-model="form.isTop"></el-switch>
        </el-form-item>
        <el-form-item label="是否轮播">
          <el-switch v-model="form.carousel"></el-switch>
        </el-form-item>
        <el-form-item label="缩略图">
          <image-upload :limit="1" :file-size="10" :file-type="['.png', '.jpg', '.jpeg', '.gif']"  v-model="form.thumbnail"></image-upload>
        </el-form-item>
        <el-form-item label="轮播图" v-show="false">
          <image-upload :limit="5" :file-size="10" :file-type="['.png', '.jpg', '.jpeg', '.gif']"  v-model="form.focusImgsStr"></image-upload>
        </el-form-item>
        <el-form-item label="视频" v-show="false">
          <file-upload :limit="1" :file-size="2048" :file-type="['.mp4', '.flv', '.mov', '.mkv']" v-model="form.videoUrl"></file-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 知识库详情 -->
    <el-dialog title="预览详情" :visible.sync="viewOpen"  width="1000px" append-to-body :close-on-click-modal="false">
      <el-row>
        <el-col :span="24" align="center">
          <h2>{{ cmsNewsInfo.title }}</h2>
        </el-col>
        <el-col :span="24" align="center">
          {{cmsNewsInfo.createBy}} <span style="color: #ffba00">|</span> <span style="color: #b4bccc">{{ parseTime(cmsNewsInfo.createTime) }} 浏览量 {{cmsNewsInfo.viewCount}}</span>
          <el-divider></el-divider>
        </el-col>

        <el-col :span="24" align="center" v-if="cmsNewsInfo.videoUrl">
          <div v-if="viewOpen" class="player">
            <video-player
              class="vjs-custom-skin"
              ref="videoPlayer"
              :playsinline="true"
              :options="playerOptions"
            ></video-player>
          </div>
        </el-col>
        <el-col :span="24">
          <!--需v-if 避免有视频播放时，关闭dialog无法销毁播放器 -->
          <div class="editor-show" v-html="cmsNewsInfo.content" v-if="viewOpen"/>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCmsNews, getCmsNews, delCmsNews, addCmsNews, updateCmsNews, exportCmsNews, updateTopStatus ,getCmsNewsByCategoryId, frontView, updateCarouselStatus} from "@/api/business/cmsNews";
import { treeselect } from "@/api/business/cmsCategory";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import "video.js/dist/video-js.css";
export default {
  name: "CmsNews",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      disabledAdd: false,
      // 分类树选项
      categoryOptions: undefined,
      selectCategoryOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 信息管理表格数据
      cmsNewsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      viewOpen: false,
      cmsNewsInfo:{
        cmsCategory:{}
      },
      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: true, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [],
        notSupportedMessage: "此视频暂无法播放，请稍后再试", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: true,
          fullscreenToggle: true, //全屏按钮
        },
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        isTop: null,
        categoryId:undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryId: [
          { required: true, message: "所属分类不能为空", trigger: "change" }
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        viewCount: [
          { required: true, message: "浏览量不能为空", trigger: "blur" }
        ],
        isTop: [
          { required: true, message: "是否置顶不能为空", trigger: "blur" }
        ],
        carousel: [
          { required: true, message: "是否轮播不能为空", trigger: "blur" }
        ],
      }
    };
  },

  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    /** 查询信息管理列表 */
    getList() {
      this.loading = true;
      listCmsNews(this.queryParams).then(response => {
        this.cmsNewsList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 查询分类下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.selectCategoryOptions = response.data
        this.categoryOptions = [{
          id: 0,
          label: '全部',
          type: -1,
          children: response.data
        }];
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      switch (data.type){
        case -1:
          this.disabledAdd = false
          this.queryParams.categoryId = undefined
          this.getList();
          break;
        case 0:
          this.disabledAdd = false
          this.queryParams.categoryId = data.id;
          this.getList();
          break;
        case 1:
          this.disabledAdd = true
          this.reset();
          getCmsNewsByCategoryId(data.id).then(response => {
            if (response.data){
              this.form = response.data;
              if (response.data){
                this.form.focusImgsStr = response.data.focusImgs.map(item => item.imgUrl).join(",")
              }
            }else{
              this.form.categoryId = data.id
            }
            this.open = true;
            this.title = data.label;
          });
          break;
        case 2:
          this.disabledAdd = true
          this.queryParams.categoryId = data.id;
          this.getList();
          break;
        default:
          break;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        newsId: null,
        categoryId: null,
        title: null,
        content: null,
        viewCount: null,
        isTop: false,
        carousel: false,
        thumbnail: null,
        focusImgs:[],
        focusImgsStr: '',
        videoUrl: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.newsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加信息";
    },
    /** 修改轮播状态*/
    handleCarouselStatusChange(row){
      let text = row.carousel ? "轮播" : "取消轮播";
      this.$modal.confirm('确认要' + text + '吗？').then(function() {
        return updateCarouselStatus({
          'newsId': row.newsId,
          'carousel': row.carousel
        });
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.carousel = row.carousel ? false : true;
      });
    },
    /**修改置顶状态**/
    handleStatusChange(row){
      let text = row.isTop ? "置顶" : "取消置顶";
      this.$modal.confirm('确认要' + text + '吗？').then(function() {
        return updateTopStatus({
          'newsId': row.newsId,
          'isTop': row.isTop
        });
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.isTop = row.isTop ? false : true;
      });

    },
    handleView(row){
      frontView(row.newsId).then(response => {
        this.cmsNewsInfo = response.data;
        if (response.data.videoUrl){
          this.playerOptions.sources = [
            {
              src: BASE_URL + response.data.videoUrl,
            },
          ];
        }
        this.viewOpen = true;
        this.getList()
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const newsId = row.newsId || this.ids
      getCmsNews(newsId).then(response => {
        this.form = response.data;
        if (response.data){
          this.form.focusImgsStr = response.data.focusImgs.map(item => item.imgUrl).join(",")
        }
        this.open = true;
        this.title = "修改信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.focusImgs = [];
          if (this.form.focusImgsStr !== null && this.form.focusImgsStr !== ''){
            const list = this.form.focusImgsStr.split(',');
            this.form.focusImgs = list.map(item => {
              if (typeof item === "string") {
                item = { imgUrl: item };
              }
              return item;
            });
          }
          if (this.form.newsId != null) {
            updateCmsNews(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCmsNews(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const newsIds = row.newsId || this.ids;
      this.$modal.confirm('是否确认删除？').then(function() {
        return delCmsNews(newsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有数据项？').then(() => {
        this.exportLoading = true;
        return exportCmsNews(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }
  }
};
</script>
<style lang="scss" scoped>
.editor-show * {word-wrap: break-word;}
</style>
<style type="text/css" lang="scss">
.editor-show {
  margin-top: 10px;
  max-height: 500px;
}
.editor-show img{max-width: 100% !important;}
.editor-show table{
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
}
.editor-show table th {
  border-bottom: 2px solid #ccc;
  text-align: center;
  background-color: #f1f1f1;
}
.editor-show table td, .editor-show table th {
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  padding: 3px 5px;
  min-height: 30px;
  height: 30px;
}
</style>
