<template>
  <div class="knowledge"
       :style="heights">
    <div style="padding: 3px 10px;position: fixed;width: 100%;background:#f2f3f5;z-index: 999">
      <i style="font-size: 18px;color:#000"
         class="awsui-iconfont"
         @click="backHome">&#xe6fa;</i>
    </div>
    <van-form style="margin-top: 30px;">
      <van-field
          class="border"
          v-model="knwlName"
          required
          label="标题"
          placeholder="请输入标题"
      />
      <van-field-date
          class="border"
          v-model="validDate"
          :minDate="minDate"
          cancel-button-text="清除"
          type="date"
          label="有效期"
          placeholder="默认长期有效"
          @change="confirmDate"
          @cancelDate="cancelDate"
      />
      <van-field-select
          class="border"
          label="格式转换"
          placeholder="请选择"
          :defaultIndex="defaultIndex2"
          ref="control"
          v-model="control"
          :columns="controlOption"
      />
      <van-field-select
          class="border"
          label="保密级别"
          placeholder="请选择"
          :defaultIndex="defaultIndex3"
          v-model="secrecyLevel"
          ref="secrecyLevel"
          :columns="secrecyLevelOption"
      />
      <van-field-select
          class="border"
          label="评论"
          placeholder="请选择"
          ref="comment"
          :defaultIndex="defaultIndex4"
          v-model="comment"
          :columns="commentOption"
      />
      <van-field-select
          class="border"
          label="打分"
          placeholder="请选择"
          v-model="grade"
          :defaultIndex="defaultIndex1"
          ref="rate"
          :columns="gradeOption"
          @change="onSelectChange"
      />
      <van-field
          v-show="displayContent"
          ref="knowContent"
          v-html="remarks"
          :autosize="{ maxHeight: 100, minHeight: 100 }"
          type="textarea"
          label="内容"
          placeholder="请输入知识正文描述"
      />
    </van-form>
    <div style="display: none"
         v-html="remarksTmp"
         ref="tmpcontent">{{ remarksTmp }}
    </div>
    <div style="width: 100%;text-align: center;"><span class="upfile-title">请到PC端上传附件</span></div>
    <div class="divide"></div>
    <ul v-if="list.length > 0"
        class="list">
      <li v-for="(item,index) in list"
          :key="index">
        <div class="icon">
          <i class="awsui-iconfont"
             v-html="getIcon(item.fileSuffixIcon)"></i>
        </div>
        <div class="left">
          <div class="title"
               style="color: #378DEC;"
               @click="fileOperatePreview(item)">
            {{ item.fileName }}
          </div>
          <div class="description">
            {{ item.createTime }} <span style="color: #dcdee0">|</span> {{ item.createUsername }} <span style="color: #dcdee0">|</span>
            {{ formatSize(item.fileSize) }} <span style="color: #dcdee0">|</span> v{{ item.fileVer }}

          </div>
        </div>
        <div class="right">
          <i v-show="item.fileState!=2"
             class="awsui-iconfont"
             @click="downloadFile(item)"
             style="color: #4A90E2;margin-right: 10px;">&#xe653;</i>
          <i class="awsui-iconfont"
             @click="deleteFile(item)">&#xe626;</i>
        </div>
      </li>
    </ul>
    <div v-else
         class="content">
      <div class="img">
        <img src="../assets/no_content.png"
             alt=""
             style="width: 88px;">
      </div>
      <span style="font-size: 13px; margin: 2px 0 5px;">暂无知识文件</span>
    </div>
    <div class="footer">
      <van-button plain
                  type="info"
                  @click="onSave('')">保存
      </van-button>
      <van-button type="info"
                  :disabled="disableRelease"
                  @click="onRelease">发布
      </van-button>
    </div>
    <van-dialog v-model="showDialog"
                show-cancel-button
                @confirm="handleDialog">
      <span style="text-align: center;padding: 20px 0;display: inline-block;width: 100%;">确定要删除该文件吗？</span>
    </van-dialog>
  </div>
</template>

<script>
import vanFieldSelect from "@/components/fieldSelect";
import vanFieldDate from "@/components/fieldDate";
import awsuiAxios from "../awsuiAxios";

export default {
  name: "new-knowledge",
  components: {
    vanFieldSelect,
    vanFieldDate
  },
  data() {
    return {
      kmsSetting: {},
      heights: "",
      disableRelease: false,
      defaultIndex1: 0,
      defaultIndex2: 0,
      defaultIndex3: 0,
      defaultIndex4: 0,
      cardSetting: {},
      displayContent: true,//隐藏编辑页面知识简介
      knwlName: "",
      validDate: "",
      formatter: "date",
      minDate: new Date(),
      showDialog: false,
      control: "转换PDF格式在线阅读，允许下载",
      controlOption: [{
        text: "常规",
        children: [{
          text: "转换PDF格式在线阅读，允许下载",
          value: "1"
        }, {
          text: "转换PDF格式在线阅读，禁止下载",
          value: "2"
        }]
      }, {
        text: "安全",
        children: [{
          text: "转换图片格式在线阅读，禁止下载（首次转换时间较长）",
          value: "0"
        }]
        // defaultIndex: 0
      }],
      secrecyLevel: "普通",
      secrecyLevelOption: ["普通", "秘密", "机密"],
      comment: "允许评论",
      commentOption: ["允许评论", "禁止评论"],
      grade: "允许打分",
      gradeOption: ["允许打分", "禁止打分"],
      remarks: "",
      remarksTmp: "",
      id: 1,
      list: [],
      deleteFileItem: {}
    };
  },
  methods: {
    backHome() {
      window.history.back();
    },
    handleDialog() {
      this.showDialog = false;
      let that = this;
      that.deleteFileId = this.deleteFileItem.id;
      // 获取知识列表数据
      awsuiAxios.post({
        url: "jd",
        data: {
          cardId: this.cardSetting.cardId,
          cmd: "com.actionsoft.apps.kms_knwl_center_delete_file",
          fileId: this.deleteFileItem.id
        }
      }).then(function (r) {
        if (r.result == "error") {
          that.$toast({message: r.data ? r.data.desc : r.msg, overlay: true});
        } else {
          that.$toast({message: "删除成功", overlay: true});
          let size = that.list.length;
          for (let i = 0; i < size; i++) {
            if (that.list[i]["id"] == that.deleteFileId) {
              that.list.splice(i, 1);
              break;
            }
          }
        }
      });
    },
    getIcon(fileSuffixIcon) {
      if (["jpg", "gif", "tif", "tiff", "bmp", "jpeg2000", "psd", "png", "svg", "pcx", "dxf", "wmf", "emf", "eps", "tga"].includes(fileSuffixIcon)) {
        return "&#xe74d;";
      } else if (["ppt", "pptx"].includes(fileSuffixIcon)) {
        return "&#xe7d4;";
      } else if (["doc", "docx"].includes(fileSuffixIcon)) {
        return "&#xe7ea;";
      } else if (["xls", "xlsx"].includes(fileSuffixIcon)) {
        return "&#xe7d0;";
      } else if (["pdf"].includes(fileSuffixIcon)) {
        return "&#xe684;";
      } else if (["zip"].includes(fileSuffixIcon)) {
        return "&#xe687;";
      } else {
        return "&#xe72b;";
      }
    },
    deleteFile(item) {
      this.showDialog = true;
      this.deleteFileItem = item;
    },
    onSave(type) {
      let knwlName = this.knwlName;
      if (knwlName == "") {
        this.$toast({message: "[标题]不允许为空", overlay: true});
        return false;
      }
      if (knwlName.length > 128) {
        this.$toast({message: "[标题]长度不能超过128个字符", overlay: true});
        return false;
      }
      let commentVal = this.comment == "允许评论";
      let control = "1";
      let secrecyLevel = 0;
      let grade = this.grade == "允许打分";
      if (this.secrecyLevel == "秘密") {
        secrecyLevel = "1";
      } else if (this.secrecyLevel == "机密") {
        secrecyLevel = "2";
      }
      if (this.control == "转换PDF格式在线阅读，禁止下载") {
        control = "2";
      } else if (this.control.indexOf("首次转换时间较长") > -1) {
        control = "0";
      }
      let vali = this.validDate;
      if (vali != "") {
        let date = new Date(this.validDate);
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        month = month < 10 ? "0" + month : month;
        day = day < 10 ? "0" + day : day;
        vali = year + "-" + month + "-" + day;
      }
      let cardId = this.cardSetting.cardId;
      let that = this;
      that.saveType = type;
      // 获取知识列表数据
      awsuiAxios.post({
        url: "jd",
        data: {
          cmd: cardId == "" ? "com.actionsoft.apps.kms_knwl_center_insert_card" : "com.actionsoft.apps.kms_knwl_center_update_card",
          cardId: cardId,
          cardName: knwlName,
          validDate: vali,
          onlineLevel: control,
          securityLevel: secrecyLevel,
          cardType: 0,
          isComment: commentVal,
          isRate: grade,
          cardContext: this.remarks
        }
      }).then(function (r) {
        that.loading = false;
        if (r.result == "error") {
          that.$toast({message: r.data ? r.data.desc : r.msg, overlay: true});
        } else {
          if (r.data && !that.cardSetting.cardId) {
            that.cardSetting.cardId = r.data.cardId;
          }
          if (that.saveType == "release") {
            if (that.remarks.length == 0 && that.list.length == 0) {
              that.$toast({message: "知识[" + that.knwlName + "]没有文件或知识内容，不允许发布该知识", overlay: true});
            } else {
              that.cardSetting.type = "editor";
              localStorage.setItem("cardSetting", JSON.stringify(that.cardSetting));
              that.$router.push({
                name: "release-knowledge",
                params: {
                  id: r.data ? r.data.cardId : that.cardSetting.cardId,
                  name: that.knwlName,
                  type: "myknowledge"
                }
              });
            }
          } else {
            that.$toast({message: "保存成功", overlay: true});
          }
        }
      });
    },
    formatSize(size) {
      if (size == "0") {
        return "-";
      }
      size = parseFloat(size);
      let units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "BB"];
      let step = 1024;
      let unitIndex = 0;
      while (true) {
        if (size > 1024) {
          size = parseFloat(size / step).toFixed(2);
          unitIndex++;
        } else {
          break;
        }
      }
      return size + units[unitIndex];
    },
    getFiles() {
      let that = this;
      awsuiAxios.post({
        url: "jd",
        data: {
          cardId: this.cardSetting.cardId,
          cmd: "com.actionsoft.apps.kms_knwl_center_file_list_json"
        }
      }).then(function (r) {
        if (r.result == "error") {
          that.$toast({message: r.data ? r.data.desc : r.msg, overlay: true});
        } else {
          that.list = r.data;
        }
      });
    },
    getCardDetail() {
      let that = this;
      // 获取知识列表数据
      awsuiAxios.post({
        url: "jd",
        data: {
          cmd: "com.actionsoft.apps.kms_knwl_center_browse_card_info_json",
          cardId: this.cardSetting.cardId,
          isBorrow: false,
          boId: "",
          isEdit: true,
          dimensionId: this.cardSetting.dimensionId
        }
      }).then(function (r) {
        that.loading = false;
        if (r.result == "error") {
          that.$toast({message: r.data ? r.data.desc : r.msg, overlay: true});
        } else {
          that.cardSetting.type = "editor";
          let data = r.data;
          let card = data.card;
          that.validDate = card.validDate;
          let secrecyLevel = card.securityLevel;
          let secrecy = "普通";
          if (secrecyLevel == 1) {
            that.defaultIndex3 = 1;
            secrecy = "秘密";
          } else if (secrecyLevel == 2) {
            secrecy = "机密";
            that.defaultIndex3 = 2;
          }
          let commentl = "允许评论";
          if (!card.isComment || card.isComment == 0) {
            that.defaultIndex4 = 1;
            commentl = "禁止评论";
          }
          let rate = "允许打分";
          if (!card.isRate || card.isRate == 0) {
            that.defaultIndex1 = 1;
            rate = "禁止打分";
          }
          let onlineLevel = "转换PDF格式在线阅读，允许下载";
          if (card.onlineLevel == 2) {
            that.defaultIndex2 = 1;
            onlineLevel = "转换PDF格式在线阅读，禁止下载";
          } else if (card.onlineLevel == 0) {
            that.defaultIndex2 = 2;
            onlineLevel = "转换图片格式在线阅读，禁止下载（首次转换时间较长)";
          }
          that.secrecyLevel = secrecy;
          that.comment = commentl;
          that.grade = rate;
          that.control = onlineLevel;
          that.$refs.secrecyLevel.changeValue(secrecy);
          that.$refs.comment.changeValue(commentl);
          that.$refs.rate.changeValue(rate);
          that.$refs.control.changeValue(onlineLevel);
          that.knwlName = data.cardName;
          /*let re1 = new RegExp("<.+?>", "g");
          that.remarks = card.cardContext.replace(re1, "");*/
          //隐藏编辑页面的知识编辑
          that.remarks = card.cardContext;
          let validDateTmp = card.validDate;
          let datee = new Date();
          let mm = datee.getMonth() + 1;
          let day = datee.getDate();
          let currentDate = datee.getFullYear() + "-" + (mm < 10 ? "0" : "") + mm + "-" + (day < 10 ? "0" : "") + day;
          if (validDateTmp && validDateTmp != "" && validDateTmp < currentDate) {
            that.disableRelease = true;
          }
        }
      });
    },
    onSelectChange(indx) {
    },
    onRelease() {
      this.onSave("release");
    },
    confirmDate(tmpdate) {
      if (tmpdate != "") {
        let date = new Date(tmpdate);
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        month = month < 10 ? "0" + month : month;
        day = day < 10 ? "0" + day : day;
        tmpdate = year + "-" + month + "-" + day;
        let datee = new Date();
        let mm = datee.getMonth() + 1;
        let currDay = datee.getDate();
        let currentDate = datee.getFullYear() + "-" + (mm < 10 ? "0" : "") + mm + "-" + (currDay < 10 ? "0" : "") + currDay;
        if (tmpdate < currentDate) {
          this.disableRelease = true;
        } else {
          this.disableRelease = false;
        }
      } else {
        this.disableRelease = false;
      }
    },
    cancelDate() {
      this.validDate = "";
    },
    downloadFile(obj) {
      localStorage.setItem("cardSetting", JSON.stringify(this.cardSetting));
      window.location.href = obj.fileDownloadURL;
    },
    fileOperatePreview(obj) {
      localStorage.setItem("cardSetting", JSON.stringify(this.cardSetting));
      let fileType = obj.fileName.lastIndexOf(".") > -1 ? obj.fileName.substring(obj.fileName.lastIndexOf(".") + 1, obj.fileName.length) : "";
      let tmpSetting = this.kmsSetting;
      let previewTypes = tmpSetting.browserPreview.split(",");
      let hasType = false;
      previewTypes.forEach((ob, index) => {
        if (ob == fileType) {
          hasType = true;
        }
      });
      let data = {};
      if (hasType || obj.fileState == 2) {// 浏览器直接预览，不调用onlinedoc
        data = {
          cmd: "com.actionsoft.apps.kms_knwl_browser_preview",
          fileId: obj.id
        };
      } else {
        if (tmpSetting.isOnlinedocAppActive) {
          //showFullScreenPanel
          data = {
            cmd: "com.actionsoft.apps.kms_knwl_center_preview_file",
            isDownload: false,
            isCopy: true,
            fileId: obj.id
          };
        } else {
          return;
        }
      }
      let that = this;
      awsuiAxios.post({
        url: "jd",
        data: data
      }).then(function (r) {
        if (r.result == "error") {
          that.$toast({message: r.data ? r.data.desc : r.msg, overlay: true});
        } else {
          let url = r.data.url;
          var head = document.location.origin + "/portal";
          if (url.indexOf("./df") > -1) {
            url = url.replace("./df", head + "/r/df");
          } else {
            url = url.replace("./w", head + "/r/w");
          }
          try {
            if (awsWebview.openWebviewPost(url, null) === false) {
              window.location.href = url;
            }
          } catch (e) {
          }
        }
      });
    },
    getSettingFile() {
      // 获取知识列表数据
      let that = this;
      awsuiAxios.post({
        url: "jd",
        data: {
          cmd: "com.actionsoft.apps.kms_knwl_center_mobile_check_fullsearch"
        }
      }).then(function (r) {
        that.kmsSetting = r.data.setting;
      });
    }
  },
  watch: {},
  mounted() {
    this.displayContent = false;
    let h = window.innerHeight - 64;
    this.heights = "height:" + h + "px;";
    let tmpParams = this.$route.params;
    if (tmpParams.cardId == undefined) {
      tmpParams = JSON.parse(localStorage.getItem("cardSetting"));
      localStorage.setItem("cardSetting", "");
    }
    this.getSettingFile();
    this.cardSetting = tmpParams;
    if (this.cardSetting.type != "create") {
      this.getCardDetail();
      this.getFiles();
    }
  }
};
</script>

<style scoped>
.knowledge {
  height: calc(100% - 64px);
  overflow-y: auto;
}

.list {
  padding: 0 12px;
  width: calc(100% - 24px);
}

.list span, .list label {
  display: inline-block;
}

.list li {
  float: left;
  padding: 11px 0;
  width: 100%;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.list li:not(:last-child) {
  border-bottom: 0.33px solid #e9e9e9;
}

.list li .icon {
  float: left;
  padding-right: 8px;
}

.list li .icon .awsui-iconfont {
  font-size: 16px;
  color: #FFB800;
}

.list li .left {
  width: calc(100% - 35px);
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  float: left;

}

.list li .left .title {
  font-size: 13px;
  color: #333;
  line-height: 18px;
  margin-bottom: 4px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;

}

.list li .left .description {
  color: #999999;
  line-height: 15px;
  font-size: 12px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.list li .left .description .line {
  display: inline-block;
  margin: 0 6px;
}

.list li .right {
  /*width: 50px;*/
  text-align: right;
  float: right;
  /*margin-top: 18px;*/
  color: #D54C4C;
}

.list li .right .awsui-iconfont {
  font-size: 14px;
}

.content {
  position: relative;
  padding: 16px 0 20px;
  text-align: center;
  display: inline-block;
  width: 100%;
}

.content span {
  width: 100%;
  display: inline-block;
  color: #999;
  line-height: 18px;
}

.content .img {
  width: 86px;
  height: 86px;
  margin: 0 auto;
}

.footer {
  padding: 12px;
  position: fixed;
  border-top: 0.33px solid #e9e9e9;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  z-index: 1;
}

.footer .van-button {
  height: 38px;
  line-height: 38px;
  /*width: 100%;*/
  width: calc(100% / 2 - 12px);
  margin-right: 12px;
  border-radius: 2px;
  padding: 0 !important;
}

.footer .van-button:last-child {
  margin-right: 0;
}

.upfile-title {
  border: 1px dashed #ccc;
  width: calc(100% - 40px);
  display: inline-block;
  padding: 8px;
  border-radius: 3px;
  font-size: 13px;
  color: #CCCCCC;
}

textarea {
  border: 1px solid #e9e9e9 !important;
}

.van-picker-column {
  overflow: unset !important;
  width: calc(100% - 64px) !important;
}
</style>
<style>
/*控制输入框的内容不与下拉箭头重叠*/
.knowledge .van-field__body {
  width: 90%;
}
</style>
