<template>
  <div>
    <!-- 搜索标题 -->
    <auth auths="news/add">
      <el-button
        @click="openTeaching('create')"
        type="primary"
        style="margin-bottom:20px"
      >
        新建
      </el-button>
    </auth>
    <!-- 搜索标题 -->
    <save-form
      :inline="true"
      class="searchForm"
      saveKey="contentKnowledge"
      @submit="search"
      :model="searchForm"
    >
      <el-form-item prop="subType">
        <el-select
          v-model="searchForm.subType"
          clearable
          placeholder="请选择分类"
        >
          <el-option
            v-for="item in typeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button native-type="submit" type="danger">搜索</el-button>
      </el-form-item>
    </save-form>
    <!-- 列表 -->
    <div class="tableWrap">
      <el-table
        :data="tableList"
        :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
      >
        <el-table-column align="center" label="封面图">
          <template slot-scope="scope">
            <img class="bannerImg" :src="scope.row.coverImage" alt="" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="title" label="标题">
        </el-table-column>
        <el-table-column align="center" label="跳转链接">
          <template slot-scope="scope">
            <overflow-text
              width="100%"
              :text="scope.row.linkUrl"
            ></overflow-text>
            <!-- {{ scope.row.linkUrl + '/' + scope.row.id }} -->
          </template>
        </el-table-column>
        <el-table-column align="center" prop="remark" label="是否使用">
          <template slot-scope="scope">
            {{ scope.row.status == 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="subType" label="分类">
          <template slot-scope="scope">
            {{ formatSubType(scope.row.subType) }}
          </template>
        </el-table-column>

        <el-table-column align="center" prop="memo" label="版本号">
        </el-table-column>

        <el-table-column align="center" prop="order" label="排序">
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <div>
              <auth auths="news/update" style="margin-left: 10px">
                <el-button
                  @click="openTeaching('update', scope.row)"
                  v-if="!scope.row.memo || permission('banner/copyrightbtn')"
                  type="text"
                  >修改</el-button
                >
                <div
                  style="display: inline-block"
                  v-if="!scope.row.memo || permission('banner/copyrightbtn')"
                >
                  <el-button
                    v-if="scope.row.status == 1"
                    @click="onStop(scope.row, 0)"
                    type="text"
                    >停用</el-button
                  >
                  <el-button v-else @click="onStop(scope.row, 1)" type="text"
                    >启用</el-button
                  >
                </div>
              </auth>
              <auth auths="news/del">
                <el-button
                  @click="onDel(scope.row)"
                  v-if="!scope.row.memo || permission('banner/copyrightbtn')"
                  type="text"
                  >删除</el-button
                >
              </auth>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        saveKey="contentKnowledge"
        sync
        :total.sync="pageInfo.total"
        :page.sync="pageInfo.page"
        :limit.sync="pageInfo.limit"
        :page-sizes="pageInfo.page_size"
        @pagination="getList"
      />
    </div>

    <el-dialog
      :title="formTitle[pageType]"
      :visible.sync="teacherStatus"
      width="500px"
    >
      <el-form :model="form" ref="form" label-width="80px">
        <el-form-item
          label="标题"
          prop="title"
          :rules="[
            {
              required: true,
              message: '请输入标题',
              trigger: 'blur'
            }
          ]"
        >
          <el-input
            v-model.trim="form.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序值" prop="order">
          <el-input
            v-model.trim="form.order"
            placeholder="请输入排序值"
          ></el-input>
        </el-form-item>
        <el-form-item label="链接地址" prop="linkUrl">
          <el-input
            v-model.trim="form.linkUrl"
            placeholder="请输入链接地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="版本号" prop="memo">
          <el-input v-model="form.memo" placeholder="请输入版本号"></el-input>
        </el-form-item>
        <el-form-item
          label="分类"
          prop="subType"
          :rules="[
            { required: true, message: '请选择分类', trigger: 'change' }
          ]"
        >
          <el-select
            v-model="form.subType"
            style="width: 100% !important"
            placeholder="请选择分类"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="封面图"
          prop="coverImage"
          :rules="[
            { required: true, message: '请上传封面图', trigger: 'blur' }
          ]"
        >
          <image-cropper
            :options="cropperOptions"
            :imgSize="2"
            showSize
            :imageUrl="form.coverImage"
            @crop-upload-success="cropSuccess"
          />
          <p class="imageSize">图片不能超过 2M；图片尺寸：80*80；</p>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="teacherStatus = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  newsList,
  newsUpdate,
  newsDel,
  newsTypeList,
  newsAdd
} from "@/api/contentManager";
import ImageCropper from "@/components/ImageCropper";
import pagination from "@/components/Pagination/index";
import cleanDeep from "clean-deep";
import { permission } from "@/utils/directivePage";
export default {
  name: "teacherButton",
  components: {
    pagination,
    ImageCropper
  },
  data() {
    return {
      teacherStatus: false,
      formTitle: {
        create: "新建老师端按钮",
        update: "修改老师端按钮"
      },
      pageType: "create",
      cropperOptions: {
        autoCrop: true, //是否默认生成截图框
        autoCropWidth: 80, //默认生成截图框宽度
        autoCropHeight: 80, //默认生成截图框高度
        fixedBox: true, //是否固定截图框大小 不允许改变
        previewsCircle: false, //预览图是否是圆形
        full: true, // 是否输出原图比例的截图
        title: "上传图片" //模态框上显示的标题
      },
      form: {
        title: "",
        order: null,
        linkUrl: "",
        coverImage: "",
        subType: null,
        type: 23,
        memo: "",
        status: 1,
        content: ""
      },
      searchForm: {
        subType: null
      },
      tableList: [],
      teacherId: this.$route.query.teacherId,
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 1, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      typeList: [] // 子分类
    };
  },
  async mounted() {
    await newsTypeList({ parentId: 23 }).then(res => {
      if (res.code == 200) {
        this.typeList = res.data;
      }
    });
    this.getList();
  },
  methods: {
    //上传图片成功
    cropSuccess(data) {
      this.form.coverImage = data.data.url;
    },
    onSubmit() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          let form = {
            ...this.form
          };
          if (this.pageType == "create") {
            if (form.id) {
              // 判断有没有Id，如果有则删除
              delete form.id;
            }
            await newsAdd(form).then(res => {
              this.messageTips("添加", res);
            });
          } else if (this.pageType == "update") {
            await newsUpdate(form).then(res => {
              this.messageTips("修改", res);
            });
          }
        }
      });
    },
    messageTips(title, res) {
      if (res.code == 200) {
        this.$message.success(title + "成功");
        this.getList();
        this.teacherStatus = false;
      } else {
        this.$message.error(res.msg);
      }
    },
    search() {
      this.pageInfo.page = 1;
      this.getList();
    },
    permission(str) {
      return permission(str);
    },
    getList() {
      let params = {
        clientName: "manage",
        subType: this.searchForm.subType,
        rows: this.pageInfo.limit,
        page: this.pageInfo.page,
        type: 23
      };
      newsList(cleanDeep(params)).then(res => {
        if (res.code == 200) {
          this.tableList = res.data.rows;
          this.pageInfo.total = res.data.total;
        }
      });
    },
    openTeaching(type, rows) {
      this.teacherStatus = true;
      this.$nextTick(() => {
        if (this.$refs["form"]) {
          this.$refs["form"].resetFields();
        }
        this.pageType = type;
        if (type == "update") {
          this.form.id = rows.id;
          this.form.title = rows.title;
          this.form.order = rows.order;
          this.form.linkUrl = rows.linkUrl;
          this.form.coverImage = rows.coverImage;
          this.form.subType = rows.subType;
        }
      });
    },
    onDel(row) {
      // 删除
      this.$confirm("确定是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          newsDel({ id: row.id }).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.getList();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {});
    },
    onStop(row, status) {
      // 停止
      // newsUpdate
      let tempStr = ["停用", "启用"];
      newsUpdate({
        id: row.id,
        status: status
      }).then(res => {
        if (res.code == 200) {
          this.$message.success(tempStr[status] + "成功");
          this.getList();
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    formatSubType(val) {
      let tempName = null;
      this.typeList.forEach(item => {
        if (item.id == val) {
          tempName = item.name;
        }
      });
      return tempName;
    }
  }
};
</script>
<style lang="scss" scoped>
.bannerImg {
  height: 60px;
}
</style>
