<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        v-model="form"
        :before-open="beforeOpen"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="rowDel"
      >
        <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="handleEdit(scope.row, scope.index)"
            >修改
          </el-button>
          <el-button
            v-if="scope.row.enableFlag == 0"
            type="text"
            size="small"
            icon="el-icon-sold-out"
            @click="updateTy(scope.row, scope.index)"
            >下架
          </el-button>
          <el-button
            v-if="scope.row.enableFlag == 1"
            type="text"
            size="small"
            icon="el-icon-sell"
            @click="updateQy(scope.row, scope.index)"
            >上架
          </el-button>
        </template>
        <template slot-scope="scope" slot="menuLeft">
          <div class="add-btn">
            <el-button
              type="primary"
              class="btn"
              icon="el-icon-plus"
              size="small"
              @click="$refs.crud.rowAdd()"
              >新增</el-button
            >
            <span class="tips">
              注：温馨提示：请确认您上传的内容已经过专业人员的广告合规审查，上传内容不构成广告!若经专业人士审查认为构成广告，则应在经过监管部门广审后方可上传发布，且应符合《广告法》等法律法规的要求！
            </span>
          </div>
        </template>
        <template slot="temp1Form" slot-scope="scope">
          <!-- element 上传图片按钮 -->
          <el-upload
            id="sbnnn1"
            class="avatar-uploader"
            action="/admin/sys-file/upload"
            :headers="headers"
            drag
            :auto-upload="true"
            :show-file-list="false"
            :on-success="changeUpload"
          >
            <img v-show="imageUrl != ''" :src="imageUrl" class="avatar" />

            <i
              v-show="imageUrl == ''"
              class="el-icon-plus avatar-uploader-icon"
            ></i>
            <div class="el-upload__tip">
              相册封面尺寸比例(84*104)
            </div> </el-upload
          >Ï
        </template>

        <template slot="contentForm" slot-scope="scope">
          <avue-ueditor
            v-model="form.content"
            :options="upload"
            :upload="upload"
          ></avue-ueditor>
        </template>
      </avue-crud>

      <!-- vueCropper 剪裁图片实现-->
      <el-dialog
        title="图片剪裁"
        :visible.sync="dialogVisible"
        :append-to-body="true"
        :modal-append-to-body="true"
      >
        <div class="cropper-content">
          <div class="cropper" style="text-align:center">
            <vueCropper
              ref="cropper"
              :img="option.img"
              :outputSize="option.outputSize"
              :outputType="option.outputType"
              :info="true"
              :full="option.full"
              :canMove="option.canMove"
              :canMoveBox="option.canMoveBox"
              :original="option.original"
              :autoCrop="option.autoCrop"
              :fixed="option.fixed"
              :fixedNumber="option.fixedNumber"
              :centerBox="option.centerBox"
              :infoTrue="option.infoTrue"
              :fixedBox="option.fixedBox"
              @realTime="realTime"
            ></vueCropper>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="finish" :loading="loading"
            >确认</el-button
          >
        </div>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  uploadImg
} from "@/api/wmwkarticle";
import { tableOption } from "@/const/crud/wmwkarticle";
import { mapGetters } from "vuex";
import store from "@/store";
import { VueCropper } from "vue-cropper";
import Config from "@/settings";

export default {
  name: "wmwkarticle",
  data() {
    return {
      headers: {
        Authorization: "Bearer " + store.getters.access_token
      },
      previews: null,
      fileinfo: {},
      imageUrl: "",
      imageTruePath: "",
      dialogVisible: false,
      // 裁剪组件的基础配置option
      option: {
        img: "", // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 0.8, // 裁剪生成图片的质量
        outputType: "jpeg", // 裁剪生成图片的格式
        canScale: false, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        // autoCropWidth: 84, // 默认生成截图框宽度
        // autoCropHeight: 104, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [21, 26], // 截图框的宽高比例
        full: true, // 是否输出原图比例的截图
        canMoveBox: false, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
      picsList: [], //页面显示的数组
      // 防止重复提交
      loading: false,
      form: {},
      upload: {
        //普通图片上传
        action: "/admin/sys-file/uploadAllUrl",
        props: {
          res: "data",
          url: "url"
        },
        customConfig: {
          uploadImgShowBase64: true
        }
      },
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption
    };
  },
  components: {
    VueCropper
  },
  computed: {
    ...mapGetters(["permissions"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.admin_wmwkarticle_add, false),
        delBtn: this.vaildData(this.permissions.admin_wmwkarticle_del, false),
        editBtn: this.vaildData(this.permissions.admin_wmwkarticle_edit, false)
      };
    }
  },
  methods: {
    beforeOpen(show, type) {
      if (type == "add") {
        this.imageUrl = "";
      }

      window.boxType = type;
      show();
    },
    handleEdit(row, index) {
      if (null != row.fm && "" != row.fm) {
        this.imageUrl = row.fm;
        this.imageTruePath = row.fm;
      }
      this.$refs.crud.rowEdit(row, index);
    },
    updateTy: function(row, index, done, loading) {
      row.enableFlag = "1";
      putObj(row)
        .then(data => {
          this.$message.success("下架成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    updateQy: function(row, index, done, loading) {
      row.enableFlag = "0";
      putObj(row)
        .then(data => {
          this.$message.success("上架成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    getList(page, params) {
      this.tableLoading = true;

      if (
        undefined != this.searchForm.createTime &&
        this.searchForm.createTime.length == 10
      ) {
        this.searchForm.createTime = this.searchForm.createTime + " 00:00:00";
      }

      if (
        undefined != this.searchForm.updateTime &&
        this.searchForm.updateTime.length == 10
      ) {
        this.searchForm.updateTime = this.searchForm.updateTime + " 23:59:59";
      }

      fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    rowDel: function(row, index) {
      this.$confirm("是否确认删除ID为" + row.id, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delObj(row.id);
        })
        .then(data => {
          this.$message.success("删除成功");
          this.getList(this.page);
        });
    },
    handleUpdate: function(row, index, done, loading) {
      if (this.imageUrl.length > 1) {
        row.fm = this.imageTruePath;
      }
      row.content = row.content.replace(
        /\<p>/gi,
        '<p style="line-height:1.5;margin: 10px 0">'
      );

      putObj(row)
        .then(data => {
          this.$message.success("修改成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    handleSave: function(row, done, loading) {
      if (this.imageUrl.length > 1) {
        row.fm = this.imageTruePath;
      }

      row.content = row.content.replace(
        /\<p>/gi,
        '<p style="line-height:1.5;margin: 10px 0">'
      );

      addObj(row)
        .then(data => {
          this.$message.success("添加成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    refreshChange() {
      this.getList(this.page);
    },
    changeUpload(response, file, fileList) {
      if (null != file && undefined != file) {
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 5MB!");
          return false;
        }
        this.fileinfo = file;

        // 上传成功后将图片地址赋值给裁剪框显示图片
        this.$nextTick(() => {
          this.option.img = Config.imgUrl + response.data.fileName;
          this.dialogVisible = true;
        });
      }
    },
    // 点击裁剪，这一步是可以拿到处理后的地址
    finish() {
      this.$refs.cropper.getCropBlob(data => {
        var formData = new FormData();
        this.loading = true;
        //上传阿里云服务器
        formData.append("file", data); //fileImg     base64编码
        uploadImg(data, this.headers, formData)
          .then(data => {
            this.imageUrl = Config.imgUrl + data.data.data.fileName;
            this.imageTruePath = data.data.data.url;
            this.dialogVisible = false;
            this.option.img = "";
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      });
    },
    realTime(data) {
      this.previews = data;
    }
  }
};
</script>

<style lang="scss" scoped>
.cropper-content {
  .cropper {
    width: auto;
    height: 300px;
  }
}

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

.el-upload-dragger {
  width: 340px !important;
}

.add-btn {
  display: flex;
  align-items: center;
  .btn {
    width: 80px;
  }

  .tips {
    flex: 1;
    font-size: 12px;
  }
}
</style>
