<template>
  <div class="app-container">
    <div class="common-card basic-information-box">
      <div class="basic-information-title">基本信息</div>
      <div class="basic-information-form">
        <a-form
          :form="form"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
          style="width: 515px"
          @submit="handleSubmit"
        >
          <a-form-item label="文章标题">
            <a-input
              placeholder="请输入文章标题"
              :maxLength="100"
              v-decorator="[
                'name',
                {
                  rules: [{ required: true, message: '请输入文章标题' }],
                },
              ]"
            />
          </a-form-item>
          <!-- <a-form-item label="文章描述">
            <a-textarea
              placeholder="请输入文章描述"
              :auto-size="{ minRows: 3, maxRows: 5 }"
              :maxLength="100"
              v-decorator="[
                'description',
                {
                  rules: [{ message: '请输入文章描述' }],
                  initialValue: description,
                },
              ]"
            />
          </a-form-item> -->
          <a-form-item label="文章分类">
            <!-- 文章分类父类 -->
            <a-select
              v-decorator="[
                'articleParentClass',
                {
                  rules: [
                    {
                      required: optionType == 'create',
                      message: '请选择文章分类父类',
                    },
                  ],
                  initialValue: articleParentClass.name,
                },
              ]"
              @change="articleClassParentChange"
            >
              <a-select-option
                v-for="(item, index) in articleParentClassArr"
                :key="index"
                >{{ articleParentClassArr[index].name }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item label="文章子类">
            <!-- 文章分类子类 -->
            <a-select
              v-decorator="[
                'articleChildClass',
                {
                  rules: [
                    {
                      required: optionType == 'create',
                      message: '请选择文章分类子类',
                    },
                  ],
                  initialValue: articleChildClass.name,
                },
              ]"
              :disabled="!articleChildClass || !articleChildClass.id"
              @change="articleClassChildChange"
            >
              <a-select-option
                v-for="(item, index) in articleChildClassArr"
                :key="index"
                >{{ articleChildClassArr[index].name }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item label="工种类别">
            <a-select
              v-decorator="[
                'engineerType',
                {
                  rules: [{ required: true, message: '请选择工种' }],
                  initialValue: engineerType.name,
                },
              ]"
              @change="engineerTypeChange"
            >
              <a-select-option
                v-for="(item, index) in engineerTypeArray"
                :key="index"
                >{{ engineerTypeArray[index].name }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item label="必学日期:">
            <!-- <a-date-picker
              :defaultValue="learnDate"
              @change="learnDateChoose"
              style="width:100%;"
            />-->
            <a-date-picker
              placeholder="请选择日期"
              @change="learnDateChoose"
              v-decorator="[
                'learnDate',
                {
                  initialValue: learnDate,
                },
              ]"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item v-show="false" :wrapper-col="{ span: 20, offset: 10 }">
            <a-button id="articleCreateSubmit" type="primary" html-type="submit"
              >提交</a-button
            >
          </a-form-item>
        </a-form>
      </div>
    </div>
    <div class="common-card a-card-margin-top">
      <div class="information-title">文章内容</div>
      <TinymceEditor v-model="content"></TinymceEditor>
      <div class="upload-oss-file-div">
        <div class="information-title">上传附件</div>
        <div>
          <a-upload
            :customRequest="uploadOssFile"
            :default-file-list="defaultFileList"
            :remove="removeOssFile"
          >
            <a-button> <a-icon type="upload" />点击上传 </a-button>
          </a-upload>
        </div>
      </div>
      <div class="submit-row">
        <a-button type="primary" @click="handleSubmitBtnFun">提交</a-button>
        <a-button :style="{ marginLeft: '160px' }" @click="preview"
          >预览</a-button
        >
      </div>
    </div>
    <!-- 预览弹出框 -->
    <a-drawer
      title
      placement="left"
      :closable="true"
      :visible="previewVisible"
      :bodyStyle="bodyStyle"
      @close="closepreview"
      width="30%"
    >
      <p class="p-content" v-html="content">{{ content }}</p>
    </a-drawer>
    <!-- <div class="company-info">
      <span>
        copyright © 浮游科技有限公司出品
      </span>
    </div>-->
  </div>
</template>

<script>
const OSS = require("ali-oss");
import {
  formatePathParams,
  formateStringDate,
  formateDateToString
} from "@/filters";
import TinymceEditor from "@/components/tinymce/TinymceEditor"; // 富文本编辑组件
export default {
  name: "articleCreate",
  props: {},
  components: {
    TinymceEditor
  },
  data() {
    return {
      content: "",
      //   展示预览
      previewVisible: false,
      form: this.$form.createForm(this, { name: "articleCreate" }),
      articleParentClassArr: [],
      articleChildClassArr: [],
      engineerTypeArray: [],
      articleParentClass: {},
      articleChildClass: {},
      engineerType: "",
      learnDate: "",
      optionType: "",
      description: "",
      bodyStyle: {
        img: "{max-width:100%;}",
        color: "red"
      },
      defaultFileList: []
    };
  },
  created() {
    this.initDataFun(); //初始化数据
  },
  mounted() {},
  beforeDestroy() {},
  watch: {},
  computed: {},
  methods: {
    //初始化数据
    async initDataFun() {
      await this.getArticleParentClass();
      await this.getEngineersWork();
      let type = this.$route.query.type;
      this.optionType = type ? type : "create";
      // 判断是新增文章还是编辑文章
      if ("edit" === type) {
        console.log("---edit---");
        await this.getArticleContent();
      } else if ("create" === type) {
        console.log("---create---");
      }
    },
    // 查询文章分类父级
    getArticleParentClass() {
      this.$_http
        .get(this.$_API.INTERFACE_GET_CATEGORIES)
        .then(res => {
          this.articleParentClassArr = res.data;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 查询文章分类子集
    getArticleChildClass() {
      if (!this.articleParentClass.id) {
        return;
      }
      let pathParamsData = { categoryId: this.articleParentClass.id };
      this.$_http
        .get(
          formatePathParams(
            this.$_API.INTERFACE_GET_CATEGORIES_CATEGROYID,
            pathParamsData
          )
        )
        .then(res => {
          if (res && res.data.length !== 0) {
            this.articleChildClassArr = res.data;
            this.articleChildClass = this.articleChildClassArr[0];
            this.form.setFieldsValue({
              articleChildClass: this.articleChildClass.name
            });
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 查询工作类别
    async getEngineersWork() {
      await this.$_http
        .get(this.$_API.INTERFACE_GET_ENGINEERINGWORK_LIST)
        .then(res => {
          this.engineerTypeArray = [...res.data];
          this.engineerType = this.engineerTypeArray[0];
        });
    },

    // 文章分类父类变化
    articleClassParentChange(value) {
      this.articleParentClass = this.articleParentClassArr[value];
      // 子类选项清空
      this.articleChildClassArr = [];
      this.form.setFieldsValue({
        articleChildClass: ""
      });
      // 获取子类的值
      this.getArticleChildClass();
    },
    // 文章分类子类变化
    articleClassChildChange(value) {
      this.articleChildClass = this.articleChildClassArr[value];
    },
    // 工种变化
    engineerTypeChange(index) {
      this.engineerType = this.engineerTypeArray[index];
    },
    // 必学日期选择
    learnDateChoose(date, dateString) {
      this.learnDate = dateString;
    },
    handleSubmitBtnFun() {
      document.getElementById("articleCreateSubmit").click();
    },
    // 查询文章内容
    getArticleContent() {
      let pathParamsData = { materialId: this.$route.query.id };
      this.$_http
        .get(
          formatePathParams(this.$_API.INTERFACE_GET_MATERIALS, pathParamsData)
        )
        .then(res => {
          console.log("----" + JSON.stringify(res));
          this.initEditArticleForm(res.data);
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    initEditArticleForm(item) {
      console.log("--------" + JSON.stringify(item));
      //   文章标题
      this.form.setFieldsValue({
        name: item.name
      });
      //   文章描述
      this.description = item.description ? item.description : "";
      // 文章分类-父类：
      this.articleParentClass = item.rootMaterialCategory;
      this.getArticleChildClass(); // 获取子类列表的值
      // 文章分类-子类
      this.articleChildClass = item.materialCategory;
      //   选中工种
      if (item.engineerTypes.length !== 0) {
        let engineerId = item.engineerTypes[0];
        for (let i = 0; i < this.engineerTypeArray.length; i++) {
          let element = this.engineerTypeArray[i];
          if (element.id === engineerId) {
            this.engineerTypeChange(i);
          }
        }
      }
      let learnDate = item.tags.length > 0 ? item.tags[0] : null;
      // 必学日期
      this.learnDate = learnDate ? formateStringDate(learnDate) : null;
      console.log("编辑初始化时间为YYYY-MM-DD", this.learnDate, learnDate);
      // 文章内容
      this.content = item.contents;
      // 附件内容
      item.links.forEach(element => {
        let upFile = {
          uid: this.getUid(),
          name: this.getUrlName(element),
          status: "done",
          url: element
        };
        this.defaultFileList.push(upFile);
      });
      console.log(this.defaultFileList);
    },
    // 截取路径名字
    getUrlName(url) {
      let strArr = url.split("/");
      console.log(strArr);
      let fileName = strArr[strArr.length - 1];
      console.log(fileName);
      fileName = decodeURIComponent(fileName);
      console.log(fileName);
      return fileName;
    },
    // 提交表单
    handleSubmit(e) {
      e.preventDefault();
      if ("create" === this.optionType) {
        console.log("创建文章");
        this.createArtical();
      } else if ("edit" === this.optionType) {
        console.log("更新文章");
        this.updateArtical();
      }
    },
    createArtical() {
      this.form.setFieldsValue({
        articleParentClass: this.articleParentClass.name
      });
      this.form.setFieldsValue({
        articleChildClass: this.articleChildClass.name
      });
      this.form.setFieldsValue({
        engineerType: this.engineerType.name
      });
      this.form.validateFields((err, values) => {
        if (!err) {
          // 新建文章
          let that = this;
          that.$confirm({
            title: "新建文章",
            content: `确认新建文章吗？`,
            okText: "确认",
            cancelText: "取消",
            onOk() {
              that.loading = true;
              let params = {
                categoryid: that.articleChildClass.id,
                engineertypeid: that.engineerType.id
              };
              let tag = formateDateToString(that.learnDate);
              let links = [];
              that.defaultFileList.forEach(element => {
                links.push(element.url);
              });
              let bodyParams = {
                name: values.name,
                description: values.description,
                type: "ARTICLE",
                contents: that.content,
                tags: tag ? [tag] : [],
                engineerTypes: [that.engineerType.id],
                links: links
              };
              that.$_http
                .post(that.$_API.INTERFACE_POST_ADMIN_MATERIALS, bodyParams, {
                  params
                })
                .then(() => {
                  that.$message.success("新建文章成功");
                });
            },
            onCancel() {}
          });
        }
      });
    },
    updateArtical() {
      let pathParamsData = { materialId: this.$route.query.id };
      this.form.validateFields((err, values) => {
        if (!err) {
          // 更新文章
          let that = this;
          that.$confirm({
            title: "更新文章",
            content: `确认更新文章吗？`,
            okText: "确认",
            cancelText: "取消",
            onOk() {
              that.loading = true;
              let params = {
                categoryid: that.articleChildClass.id,
                engineertypeid: that.engineerType.id
              };
              let tag = formateDateToString(that.learnDate);
              let links = [];
              that.defaultFileList.forEach(element => {
                links.push(element.url);
              });
              console.log(links);
              let bodyParams = {
                id: that.$route.query.id,
                name: values.name,
                description: values.description,
                type: "ARTICLE",
                contents: that.content,
                tags: tag ? [tag] : [],
                engineerTypes: [that.engineerType.id],
                links: links
              };
              console.log(
                "保存修改日期格式为YYYYMMDD",
                bodyParams.tags,
                that.learnDate
              );
              that.$_http
                .put(
                  formatePathParams(
                    that.$_API.INTERFACE_PUT_ADMIN_MATERIALS,
                    pathParamsData
                  ),
                  bodyParams,
                  {
                    params
                  }
                )
                .then(() => {
                  that.$message.success("更新文章成功");
                });
            },
            onCancel() {}
          });
        }
      });
    },
    uploadOssFile(fileData) {
      let file = fileData.file;
      let that = this;
      let bucket = "jtxt-file-public";
      // let filetype =
      //   ".pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx";
      let ossPath = "file/";
      that.$_http.get(that.$_API.INTERFACE_GET_ASSUME_OSS_WRITER).then(res => {
        console.log("--oss-writer--" + JSON.stringify(res));
        const client = new OSS({
          // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
          region: "oss-cn-beijing",
          // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
          accessKeyId: res.data.accessKeyId,
          accessKeySecret: res.data.accessKeySecret,
          // 从STS服务获取的安全令牌（SecurityToken）。
          stsToken: res.data.securityToken,
          // 填写Bucket名称。
          bucket: bucket
        });
        let fileName = new Date().getTime() + "_" + file.name;
        let options = {
          progress: function(p) {
            // 断点记录点。浏览器重启后无法直接继续上传，您需要手动触发上传操作。
            console.log("-----" + JSON.stringify(p));
            //   console.log("-----" + JSON.stringify(checkpoint));
          },
          patrtSize: 1000 * 1024, // 设置分片大小
          timeout: 1000 * 60 * 10 // 超时时间
        };
        try {
          client
            .multipartUpload(ossPath + fileName, file, options)
            .then(res => {
              console.log(res);
              let fileUrl = res.res.requestUrls[0].split("?")[0];
              console.log(fileUrl);
              let upFile = {
                uid: this.getUid(),
                name: fileName,
                status: "done",
                url: fileUrl
              };
              this.defaultFileList.push(upFile);
              fileData.onSuccess();
            });
        } catch (e) {
          fileData.onError();
          console.error(e);
        }
      });
    },
    removeOssFile(file) {
      for (let i = 0; i < this.defaultFileList.length; i++) {
        let tmpFile = this.defaultFileList[i];
        if (tmpFile.uid === file.uid) {
          this.defaultFileList.splice(i, 1);
          return;
        }
      }
    },
    getUid() {
      let uid = "";
      for (let i = 0; i < 5; i++) {
        uid += Math.floor(Math.random() * 10);
      }
      return uid;
    },
    // 预览
    preview() {
      this.previewVisible = true;
    },
    // 关闭预览
    closepreview() {
      this.previewVisible = false;
    }
  }
};
</script>

<style lang="less">
.p-content {
  max-width: 100%;
  img {
    max-width: 100%;
    width: auto;
    height: auto;
  }
}
</style>

<style lang="less" scoped>
@import "~@/styles/common/variable.less";
.app-container {
  .information-title {
    font-size: 18px;
    font-weight: bold;
    color: @mainColorBlack65;
    margin-bottom: @paddingMarginVal;
  }
  .submit-row {
    width: 100%;
    margin-top: 2 * @paddingMarginVal;
    padding: @paddingMarginVal 0 @navTopHight;
    display: flex;
    justify-content: center;
  }
  .upload-oss-file-div {
    margin: @paddingMarginVal 0;
  }
}
</style>
