<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable size="small">
          <el-option
            v-for="dict in categoryOptions"
            :key="dict.categoryId"
            :label="dict.categoryName"
            :value="dict.categoryId"
          />
        </el-select>
      </el-form-item>
      <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="publicStatus">
        <el-select v-model="queryParams.publicStatus" placeholder="请选择发布状态" clearable size="small">
          <el-option label="已发布" value="1" />
          <el-option label="草稿" value="2" />
        </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"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['store:homeArticle:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['store:homeArticle:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['store:homeArticle:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['store:homeArticle:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="homeArticleList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类" align="center" prop="categoryName" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="封面图片" align="center" prop="imageUrl">
        <template slot-scope="scope">
          <el-image
            style="width: 80px; height: 50px"
            :src="scope.row.imageUrl"
            :preview-src-list="[scope.row.imageUrl]"
            fit="cover">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="浏览数" align="center" prop="views" width="80" />
      <el-table-column label="发布时间" align="center" prop="publishTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160"/>
      <el-table-column label="发布状态" align="center" prop="publicStatus" width="100">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.publicStatus == 1">已发布</el-tag>
          <el-tag type="info" v-else-if="scope.row.publicStatus == 2">草稿</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['store:homeArticle:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['store:homeArticle: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-dialog :title="title" :visible.sync="open" width="900px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类" filterable>
            <el-option
              v-for="dict in categoryOptions"
              :key="dict.categoryId"
              :label="dict.categoryName"
              :value="dict.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" maxlength="100"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述内容" maxlength="200"/>
        </el-form-item>
        <el-form-item label="封面图片" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleImageUrlSuccess"
            :before-upload="beforeImageUrlUpload">
            <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" width="200px">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否推荐" prop="isTui">
          <el-radio-group v-model="form.isTui">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="视频地址" prop="videoUrl">
          <div>
            <el-upload
              ref="upload"
              class="upload-demo"
              :action="uploadUrl"
              :on-success="handleVideoSuccess"
              :before-upload="beforeVideoUpload"
              :limit="1"
              :accept="videoAccept"
            >
              <el-button size="small" type="primary">点击上传视频</el-button>
            </el-upload>
            <video v-if="form.videoUrl" :src="form.videoUrl" controls style="max-width: 400px; max-height: 200px;"></video>
          </div>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <Editor ref="myeditor" @on-text-change="updateText"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="浏览数" prop="views">
              <el-input-number v-model="form.views" :min="0" placeholder="请输入浏览数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="发布状态" prop="publicStatus">
          <el-select v-model="form.publicStatus" placeholder="请选择发布状态">
            <el-option label="已发布" value="1" />
            <el-option label="草稿" value="2" />
          </el-select>
        </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>
  </div>
</template>

<script>
import { listHomeArticle, getHomeArticle, delHomeArticle, addHomeArticle, updateHomeArticle, exportHomeArticle } from "@/api/his/homeArticle";
import { listHomeCategory, allListHomeCategory } from "@/api/his/homeCategory";
import Editor from '@/components/Editor/wang';

export default {
  name: "HomeArticle",
  components: { Editor },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文章表格数据
      homeArticleList: [],
      // 分类选项
      categoryOptions: [],
      // 上传URL
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/uploadOSS",
      // 视频接受类型
      videoAccept: "video/*",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        title: null,
        publicStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryId: [
          { required: true, message: "分类不能为空", trigger: "change" }
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        description: [
          { required: true, message: "发布状态不能为空", trigger: "change" }
        ],
        imageUrl: [
          { required: true, message: "封面图片不能为空", trigger: "change" }
        ],
        publicStatus: [
          { required: true, message: "发布状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getCategoryOptions();
  },
  methods: {
    /** 获取分类选项 */
    getCategoryOptions() {
      allListHomeCategory().then(response => {
        this.categoryOptions = response.rows;
      });
    },
    /** 查询文章列表 */
    getList() {
      this.loading = true;
      listHomeArticle(this.queryParams).then(response => {
        this.homeArticleList = response.rows.list;
        this.total = response.rows.total;
        this.loading = false;
      });
    },
    // 视频上传成功处理
    handleVideoSuccess(response, file) {
      if (response.code == 200) {
        this.form.videoUrl = response.url;
        this.$refs.upload.clearFiles();
      } else {
        this.msgError(response.msg);
      }
    },
    // 视频上传前的验证
    beforeVideoUpload(file) {
      const isLt200M = file.size / 1024 / 1024 < 200;
      if (!isLt200M) {
        this.$message.error('上传视频文件大小不能超过200MB!');
        return false;
      }
      return isLt200M;
    },
    // 更新富文本内容
    updateText(text) {
      this.form.content = text;
    },
    // 图片上传成功处理
    handleImageUrlSuccess(res, file) {
      if (res.code == 200) {
        this.form.imageUrl = res.url;
        this.$forceUpdate();
      } else {
        this.msgError(res.msg);
      }
    },
    // 图片上传前的验证
    beforeImageUrlUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过1MB!');
      }
      return isLt1M;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        articleId: null,
        categoryId: null,
        title: null,
        description: null,
        imageUrl: null,
        isTui: 0,
        videoUrl: null,
        content: null,
        views: 0,
        sort: 0,
        publishTime: null,
        publicStatus: "1"
      };
      this.resetForm("form");
      if (this.$refs.myeditor) {
        this.$refs.myeditor.setText("");
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.articleId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文章";
      setTimeout(() => {
        if (this.$refs.myeditor) {
          this.$refs.myeditor.setText("");
        }
      }, 100);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const articleId = row.articleId || this.ids
      getHomeArticle(articleId).then(response => {
        this.form = response.data;
        // 确保状态是字符串类型
        this.form.publicStatus = this.form.publicStatus ? this.form.publicStatus.toString() : "1";
        this.open = true;
        this.title = "修改文章";
        setTimeout(() => {
          if (this.$refs.myeditor) {
            if (this.form.content == null) {
              this.$refs.myeditor.setText("");
            } else {
              this.$refs.myeditor.setText(this.form.content);
            }
          }
        }, 100);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.articleId != null) {
            updateHomeArticle(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addHomeArticle(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const articleIds = row.articleId || this.ids;
      this.$confirm('是否确认删除该文章?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delHomeArticle(articleIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    // /** 导出按钮操作 */
    // handleExport() {
    //   const queryParams = this.queryParams;
    //   this.$confirm('是否确认导出所有文章数据项?', "警告", {
    //       confirmButtonText: "确定",
    //       cancelButtonText: "取消",
    //       type: "warning"
    //     }).then(function() {
    //       return exportHomeArticle(queryParams);
    //     }).then(response => {
    //       this.download(response.msg);
    //     }).catch(function() {});
    // }
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>
