<template>
  <a-layout :class="$style.layout">
    <sd-header>
      <template>
        <span :class="[$style.handleBtn, $style.printNone]">
          <span @click="close"><a-icon type="close-circle"></a-icon> 退出 </span>
        </span>
      </template>
    </sd-header>
    <a-layout-content :class="$style.layoutContent">
      <a-card :class="$style.bgcolor">
        <div :class="$style.newsMain">
          <div :class="$style.knowLedage">
            <div :class="$style.klArticle">
              <a-row type="flex">
                <a-col flex="1 1 200px">
                  <div :class="$style.leftContent">
                    <a-skeleton v-if="!isAlertShow" active />
                    <div v-else :class="$style.articeText">
                      <h3>{{ news.title }}</h3>
                      <div :class="$style.infos">
                        <span>日期：{{ news.creationTime | sdDateFormat('YYYY-MM-DD') }}</span>
                        <span>来源：{{ news.creatorName }}</span>
                        <span
                          >阅读次数：<a @click="gotoReaderList">{{ docReadNumber }}</a></span
                        >
                      </div>
                      <div v-if="news.type === 1" :class="$style.content">
                        <!-- eslint-disable-next-line vue/no-v-html -->
                        <div v-html="news.content"></div>
                      </div>
                      <div v-else-if="news.onlinePreview === '0'" :class="$style.content">
                        <p v-html="news.abstractMessage"></p>
                      </div>
                      <div v-else :class="$style.files">
                        <sd-wps-reader
                          v-if="attachments.length > 0"
                          :key="clickChange ? changeCode : attachments[0].code"
                          :class="$style.wpsread"
                          :code="clickChange ? changeCode : attachments[0].code"
                        />
                      </div>
                      <div v-if="news.onlinePreview === '0'">
                        <div
                          v-for="(item, index) in attachments"
                          :key="index"
                          :class="$style.files"
                        >
                          <div :class="$style.filesName">附件：{{ item.name }}</div>
                          <div :class="$style.filesBtn">
                            <a
                              :download="item.name"
                              :href="
                                `api/flow-mobile/v1/task-form-process/download-attachments/${item.code}`
                                  | sdResource
                              "
                              @click="attachmentRecord(item.name, item.code)"
                              >下载</a
                            >
                            &nbsp;&nbsp;&nbsp;
                            <a :download="item.name" @click.prevent="previewAttachment(item)"
                              >查看</a
                            >
                          </div>
                        </div>
                      </div>
                      <a-divider />
                      <!-- <div :class="$style.klOperation">
                        <span
                          :class="isClick === 'dz' ? $style.isActive : ''"
                          @click="handleLike('dz')"
                        >
                          <a-badge :class="$style.drage" :count="badgeCount">
                            <a-icon type="like" :theme="flag ? 'filled' : 'outlined'" /> </a-badge
                          >点赞
                        </span>
                      </div> -->
                    </div>
                    <!-- <div id="divId" :class="$style.comment">
                      <a-skeleton v-if="!isAlertShow" active />
                      <a-tabs v-else default-active-key="1" @change="callback">
                        <a-tab-pane key="1" tab="点评">
                          <div :class="$style.plContent">
                            <a-comment>
                              <a-avatar
                                slot="avatar"
                                icon="user"
                                :src="
                                  `api/mobile/v1/user-manager/userAvatar/${currentUser}`
                                    | sdResource
                                "
                              />
                              <div slot="content">
                                <a-form>
                                  <a-form-item :class="$style.commentText">
                                    <a-textarea
                                      ref="textarea"
                                      v-model="commentValue"
                                      placeholder="发表您的评价或意见建议！"
                                      :max-length="1000"
                                      :rows="4"
                                      @input="handleChange"
                                    />
                                  </a-form-item>
                                  <a-form-item :class="$style.commentScore">
                                    <div :class="$style.publish">
                                      <span :class="$style.textNum"
                                        >还可以输入<em>{{ still }}</em
                                        >字</span
                                      >
                                      <a-button
                                        html-type="submit"
                                        :loading="submitting"
                                        type="primary"
                                        @click="handleSubmit"
                                      >
                                        发表
                                      </a-button>
                                    </div>
                                  </a-form-item>
                                </a-form>
                              </div>
                            </a-comment>
                            <div v-if="comments.length === 0" :class="$style.noComment"
                              >暂无评论</div
                            >
                            <a-list
                              v-if="comments.length"
                              :class="$style.commentList"
                              :data-source="comments"
                              item-layout="horizontal"
                            >
                              <div v-if="showLoadingMore" slot="loadMore" :class="$style.moredata">
                                <a-spin v-if="loadingMore" />
                                <div @click="clickMore">
                                  查看更多
                                  <a-icon type="right" />
                                </div>
                              </div>
                              <div v-else :class="$style.moredata">到底了，没有更多数据了</div>
                              <a-list-item slot="renderItem" slot-scope="item">
                                <a-comment>
                                  <a slot="author">{{ item.creatorName }}</a>
                                  <a-avatar
                                    slot="avatar"
                                    icon="user"
                                    :src="
                                      `api/mobile/v1/user-manager/userAvatar/${item.creatorAccount}`
                                        | sdResource
                                    "
                                  />
                                  <p slot="content">
                                    {{ item.commentContent }}
                                  </p>
                                  <span slot="datetime">{{
                                    moment(item.creationTime).format('YYYY-MM-DD HH:mm:ss')
                                  }}</span>
                                </a-comment>
                              </a-list-item>
                            </a-list>
                          </div>
                        </a-tab-pane>
                        <a-tab-pane key="3" tab="访问">
                          <div v-if="spin" :class="$style.example">
                            <a-spin />
                          </div>
                          <div v-else>
                            <a-empty v-if="visitRecordData.length === 0" />
                            <a-table
                              v-else
                              bordered
                              :columns="columnsVisit"
                              :data-source="visitRecordData"
                              :pagination="pagination1"
                            >
                              <template slot="firstSeen" slot-scope="firstSeen">
                                {{ moment(firstSeen).format('YYYY-MM-DD HH:mm:ss') }}
                              </template>
                              <template slot="lastSeen" slot-scope="lastSeen">
                                {{ moment(lastSeen).format('YYYY-MM-DD HH:mm:ss') }}
                              </template>
                            </a-table>
                          </div>
                        </a-tab-pane>
                      </a-tabs>
                    </div> -->
                  </div>
                </a-col>
                <!-- <a-col flex="0 1 350px">
                  <div :class="$style.rightContent">
                    <a-skeleton v-if="!isAlertShow" active />
                    <div v-else :class="$style.articleInfo">
                      <p :class="$style.title">文档信息</p>
                      <a-divider />
                      <div :class="$style.userInfo">
                        <div :class="$style.user">
                          <p>上传者</p>

                          <a-row :class="$style.userImg" type="flex">
                            <a-col flex="80px">
                              <a-avatar
                                :class="$style.userinfo"
                                icon="user"
                                :size="65"
                                :src="
                                  `api/mobile/v1/user-manager/userAvatar/${news.creatorAccount}`
                                    | sdResource
                                "
                                alt="avatar"
                              />
                            </a-col>
                            <a-col flex="auto">
                              <p :class="$style.username">{{ news.creatorName }}</p>
                              <p>{{ news.createDeptName }}</p>
                            </a-col>
                          </a-row>
                          <a-divider />
                        </div>
                        <div :class="$style.userNum">
                          <span><a-icon type="sd-message" />{{ news.commentNumber }}</span>
                          <span><a-icon type="share-alt" />{{ news.recommendNumber }}</span>
                          <span><a-icon type="sd-eye" />{{ news.readNumber }}</span>
                        </div>
                      </div>
                      <div :class="$style.infos">
                        <p v-if="news.type === 0" :class="$style.edition"
                          ><i>版本</i>：<span>{{ news.versionNum }}</span></p
                        >
                        <p :class="$style.type"
                          ><i>分类</i>：<span>{{
                            categoryrArr.map((item) => item.categoryName).join(' 、')
                          }}</span></p
                        >
                        <p :class="$style.labels"
                          ><i>标签</i>：<span>{{
                            labelArr.map((item) => item.name).join(' 、')
                          }}</span></p
                        >
                        <p v-if="news.type === 0" :class="$style.field"
                          >业务领域：<span>{{
                            businessAreaArr.map((item) => item.name).join(' 、')
                          }}</span></p
                        >
                        <p
                          v-if="news.onlinePreview === '1' && news.type === 0"
                          :class="$style.abstract"
                          ><i>摘要</i>：<span>{{ news.abstractMessage }}</span></p
                        >
                      </div>
                    </div>
                    <a-skeleton v-if="!isAlertShow" active />
                    <div
                      v-else-if="news.onlinePreview === '1' && news.type === 0"
                      :class="$style.articleInfo"
                    >
                      <p :class="$style.title">链接文档</p>
                      <a-divider />
                      <div v-if="attachments.length > 0" :class="$style.wordlist">
                        <p
                          v-for="(item, index) in attachments"
                          :key="index"
                          :class="[
                            $style.downloda,
                            currentIndex === index ? $style.actived : '',
                            index === 0 && !clickChange ? $style.defalutColor : '',
                          ]"
                          @click="chooseAttach(item, index)"
                          >{{ item.name }}

                          <a
                            v-if="news.authDownload === '1'"
                            :download="item.name"
                            :href="
                              `api/flow-mobile/v1/task-form-process/download-attachments/${item.code}`
                                | sdResource
                            "
                            @click="attachmentRecord(item.name, item.code)"
                            ><a-icon type="vertical-align-bottom"/></a
                        ></p>
                      </div>
                      <a-empty v-else />
                    </div>
                  </div>
                </a-col> -->
              </a-row>
            </div>
          </div>
        </div>
      </a-card>
    </a-layout-content>
  </a-layout>
</template>

<script>
import moment from 'moment'
import loginService from '@/login/login-service'
import { Modal, Message } from 'ant-design-vue'
import errorUtil from '@/common/services/error-util'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'

import crossWindowWatcher from '@/common/services/cross-window-watcher'
import FlowService from '@/webflow/flow-service'
import KmKnowledageService from '@product/iam/audit/auditsource/km/km-knowledage-service'
import components from './_import-components/iam-audit-home-view-import'
import { Base65 } from './base65'
const columnsVisit = [
  {
    title: '首次访问时间',
    dataIndex: 'firstSeen',
    scopedSlots: { customRender: 'firstSeen' },
  },
  {
    title: '最近访问时间',
    dataIndex: 'lastSeen',
    scopedSlots: { customRender: 'lastSeen' },
  },
  {
    title: '访问人',
    dataIndex: 'creatorName',
  },
  {
    title: '访问次数',
    dataIndex: 'visitCount',
  },
]
export default {
  name: 'IamAuditHomeView',
  metaInfo: {
    title: '详情查看',
  },
  components: {
    ...components,
  },
  data() {
    return {
      docReadNumber: '', // 阅读次数
      columnsVisit,
      pagination1: {
        onChange: (page) => {},
        pageSize: 10,
      },
      pagination2: {
        onChange: (page) => {},
        pageSize: 10,
      },
      show: false, // 控制显示收藏弹框
      isEdit: false, // 控制显示勘误弹框
      fwId: Number(this.$route.query.id),
      creatorName: '', // 作者
      creationTime: null, // 创建时间
      recommendNum: null, // 推荐次数
      versionNum: null, // 版本号
      categoryName: '', // 分类
      label: '', // 标签
      businessArea: '', // 业务领域
      abstractMessage: '', // 摘要
      badgeCount: 0,
      favoritiesShow: false,
      isRecommend: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      // 推荐
      recommendForm: {
        resource: '',
        desc: '',
      },
      rules: {
        resource: [
          { required: true, message: 'Please select activity resource', trigger: 'change' },
        ],
        desc: [{ required: true, message: 'Please input activity form', trigger: 'blur' }],
      },
      isClick: '',
      loading: false,
      columns: [
        {
          title: '姓名',
          dataIndex: 'name',
        },
        {
          sorter: true,
          dataIndex: 'account',
          title: 'ID',
        },
        {
          title: '状态',
          dataIndex: 'status',
        },
      ],
      attachments: [],
      coverAttachments: [],
      comments: [],
      submitting: false,
      commentValue: '',
      moment,
      still: 1000,
      confirmLoading: false,
      // 版本
      editionModal: false,
      editionForm: {
        edition: '',
      },
      editionrules: {
        edition: [{ required: true, message: '版本号不能为空！', trigger: 'change' }],
      },
      // 获取所有点评入参
      commentParams: {
        columns:
          'commentContent,businessId,creatorName,creationTime,creatorId,praiseNumber,creatorAccount',
        expressions: [
          {
            dataType: 'str',
            name: 'commentContent',
            op: 'like',
            stringValue: '%%',
          },
          {
            dataType: 'str',
            name: 'businessId',
            op: 'eq',
            stringValue: this.$route.query.id,
          },
        ],
        formId: 'kmComment',
        maxResults: 3,
        orderBy: 'creationTime asc',
        startPosition: 0,
      },
      // 发表点评 入参
      publishData: {
        eventId: 'save',
        inputs: [
          {
            name: 'commentContent',
            value: '',
          },
          {
            name: 'businessId',
            value: this.$route.query.id,
          },
        ],
        pageFlowId: 'string',
        pagePath: '/audit/km/comp/comment/kmComment',
      },
      showLoadingMore: true,
      pagination: {
        onChange: (page, pageSize) => this.changePage(page, pageSize),
        hideOnSinglePage: true,
        current: 1,
        pageSize: 3,
        total: 0,
        showTotal: (total) => {
          return `总共${total}条`
        },
      },
      loadingMore: false,
      lastPage: '',
      moreData: false,
      allCommentNum: null,
      news: {},
      isAlertShow: false,
      currentUser: '',
      // 推荐记录入参
      recommendrecord: {
        maxResults: -1,
        startPosition: 0,
        orderBy: 'id asc',
        expressions: [
          {
            dataType: 'str',
            name: 'knowledgeId',
            op: 'eq',
            stringValue: this.$route.query.id,
          },
        ],
      },
      // 访问记录入参
      visitedrecord: {
        maxResults: -1,
        startPosition: 0,
        orderBy: 'id asc',
        expressions: [
          {
            dataType: 'str',
            name: 'beanId',
            op: 'eq',
            stringValue: this.$route.query.id,
          },
        ],
      },
      recommendRecordData: [],
      visitRecordData: [],
      flag: null,
      clickChange: false,
      currentIndex: '',
      changeCode: '',
      changeName: '',
      active: false,
      choosedViewCategory: [],
      clickNum: 0,
      categoryrArr: [],
      businessAreaArr: [],
      labelArr: [],
      spin: true,
      infotype: this.$route.query.type,
    }
  },
  created() {
    this.currentUser = getUserInfo().account
    // 获取所有评论
    this.queryComment(this.commentParams)
    // 获取知识点赞数
    this.queryKnowledgeComment()
    const obj = {}
    obj.categoryId = this.$route.query.typeId
    obj.categoryName = this.$route.query.typeName
    this.choosedViewCategory.push(obj)
    this.callback('2')
  },
  mounted() {
    // 判断是否有权限借阅
    this.queryKnowledgeCheck()
  },
  methods: {
    gotoReaderList() {
      // 处理点击事件
      const param = {}
      param.formId = this.news.formId
      param.beanId = this.$route.query.id
      param.title = this.news.title
      window.open('#/iam-audit-reader-list?params=' + encodeURIComponent(JSON.stringify(param)))
    },
    refreshData() {
      // 获取推荐，访问记录
      this.queryRecommendOrVisitRecord(this.recommendrecord, '2')
      // 获取详情
      this.queryKnowledgeDetails()
    },
    // 下载记录
    attachmentRecord(attachmentName, attachmentCode) {
      const params = {
        knowledgeId: this.$route.query.id,
        knowledgeName: this.$route.query.title,
        categoryId: JSON.parse(this.news.category)[0].categoryId,
        categoryName: JSON.parse(this.news.category)[0].categoryName,
        attachmentGroupId: this.news.applyAttachment,
        attachmentName: attachmentName,
        attachmentCode: attachmentCode,
      }
      KmKnowledageService.getAttachmentRecord(params).then((res) => {})
    },
    previewAttachment(attachment) {
      const domain = `${location.origin}${location.pathname}`
      const url = `${domain}api/framework/v1/task-form-process/download-attachments/${
        attachment.code
      }?access_token=${loginService.getTokens().access_token}&fullfilename=${attachment.name}`
      console.log(url)
      console.log(encodeURIComponent(Base65.encode(url)))

      const targetUrl = `http://super-search.szsj.spic/weread/onlinePreview?url=${encodeURIComponent(
        Base65.encode(url)
      )}`
      window.open(targetUrl, '_blank')
    },
    showModal() {
      this.isRecommend = false
    },
    chooseAttach(item, index) {
      this.clickChange = true
      this.changeCode = item.code
      this.changeName = item.name
      this.currentIndex = index
    },
    queryRecommendOrVisitRecord(record, key) {
      if (key === '3') {
        // 访问记录
        record.columns = 'creationTime,creatorName,createDeptName,firstSeen,lastSeen,visitCount'
        record.formId = 'kmPreview'
        KmKnowledageService.getKnowledgeComment(record).then((res) => {
          this.spin = false
          if (res.data.data.length > 0) {
            this.visitRecordData = res.data.data
            record.columns = ''
            record.formId = ''
          } else {
            this.visitRecordData = []
          }
        })
      }
    },

    // 是否有借阅权限
    queryKnowledgeCheck() {
      const params = {
        id: this.$route.query.id,
      }
      KmKnowledageService.getKnowledgeCheck(params)
        .then((res) => {
          if (res.data.success) {
            // 获取详情
            this.queryKnowledgeDetails()
          }
        })
        .catch((err) => {
          const msg = errorUtil.getMessage(err)
          if (
            msg === '该知识未发布无法预览，待发布后进行详情查看！' ||
            msg === '查无数据，请核实入参！'
          ) {
            Message.error(msg)
            setTimeout(() => {
              window.close()
            }, 1000)
          } else {
            // 借阅提醒
            this.showRemind()
          }
        })
    },
    // 获取知识详情
    queryKnowledgeDetails() {
      // 通知公告
      if ((this.infotype === 'tzgg') | (this.infotype === 'xwdt') | (this.infotype === 'gxjb')) {
        axios({
          url: `api/flow-mobile/v1/task-form-process/done-pages/${this.$route.query.id}`,
          method: 'get',
        }).then((res) => {
          const info = res.data.processFormData.processFormPropertyValues
          this.isAlertShow = true
          this.news = {
            onlinePreview: '0',
            type: 1,
            creationTime: info.find((item) => {
              return item.name === 'creationTime'
            }).value,
            title: info.find((item) => {
              return item.name === 'title'
            }).value,
            creatorName: info.find((item) => {
              return item.name === 'creatorName'
            }).value,
            belongUnit: info.find((item) => {
              return item.name === 'createDeptName'
            }).value,
            content: info.find((item) => {
              return item.name === 'inforDescription'
            }).value,
            formId: res.data.processFormData.formId,
          }
          // 获取文档附件
          this.getAttachmentCode(
            JSON.parse(
              info.find((item) => {
                return item.name === 'attachment'
              }).value
            ).value
          )
          // 获取和增加阅读次数
          this.setReadNums(res.data.processFormData.formId)
        })
      } else if (this.infotype === 'laws') {
        // 法律法规
        axios({
          url: `api/xcoa-mobile/v1/page/wp/core/law/iamLaw?id=${this.$route.query.id}`,
          method: 'get',
        }).then((res) => {
          const info = res.data.pageFormData.pageFieldInfos
          this.isAlertShow = true
          this.news = {
            onlinePreview: '0',
            type: 1,
            creationTime: info.find((item) => {
              return item.name === 'mainteTime'
            }).value,
            title: info.find((item) => {
              return item.name === 'docTitle'
            }).value,
            creatorName: info.find((item) => {
              return item.name === 'maintePerson'
            }).value,
            belongUnit: info.find((item) => {
              return item.name === 'publishUnit'
            }).value,
            content: info.find((item) => {
              return item.name === 'content'
            }).value,
          }
          // 获取文档附件
          this.getAttachmentCode(
            JSON.parse(
              info.find((item) => {
                return item.name === 'attachment'
              }).value
            ).value
          )
          // 获取和增加阅读次数
          this.setReadNums(res.data.pageFormData.formId)
        })
      } else if (this.infotype === 'nbzd') {
        // 内部制度
        axios({
          url: `api/xcoa-mobile/v1/page/wp/audit/auditsource/institution/iamInstitution?id=${this.$route.query.id}`,
          method: 'get',
        }).then((res) => {
          const info = res.data.pageFormData.pageFieldInfos
          this.isAlertShow = true
          this.news = {
            onlinePreview: '0',
            type: 1,
            creationTime: info.find((item) => {
              return item.name === 'mainteTime'
            }).value,
            title: info.find((item) => {
              return item.name === 'docTitle'
            }).value,
            creatorName: info.find((item) => {
              return item.name === 'maintePerson'
            }).value,
            belongUnit: info.find((item) => {
              return item.name === 'publishUnit'
            }).value,
            content: info.find((item) => {
              return item.name === 'content'
            }).value,
          }
          // 获取文档附件
          this.getAttachmentCode(
            JSON.parse(
              info.find((item) => {
                return item.name === 'attachment'
              }).value
            ).value
          )
          // 获取和增加阅读次数
          this.setReadNums(res.data.pageFormData.formId)
        })
      } else {
        KmKnowledageService.getKnowledgeDetails({ id: this.$route.query.id })
          .then((res) => {
            if (res.status === 200) {
              this.isAlertShow = true

              this.news = res.data
              this.flag = this.news.praiseed
              this.labelArr = this.news.label?.split('、')
              // 获取文档附件
              this.getAttachmentCode(res.data.applyAttachment)
            }
          })
          .catch((err) => {
            Modal.error({
              title: '数据异常!',
              content: err.response?.data?.message?.split(':')[1] || '获取详情失败！',
              onOk() {
                // window.close()
              },
            })
          })
      }
    },
    // 获取阅读次数及增加阅读次数
    setReadNums(formId) {
      // 增加阅读次数
      axios({
        url: `api/xcoa-mobile/v1/portal/addIamPortalReadNumberEntity?formId=${formId}&beanId=${this.$route.query.id}`,
      })
      // 获取阅读次数
      axios({
        url: `api/xcoa-mobile/v1/portal/getIamPortalReadNumberEntity?formId=${formId}&beanId=${this.$route.query.id}`,
      }).then((res) => {
        // 把本次也计算上
        this.docReadNumber = res.data + 1
      })
    },
    // 获取附件code
    getAttachmentCode(groupId) {
      axios
        .get(`api/xcoa-mobile/v1/attachment-extend/attachments-info-perm/${groupId}`)
        .then((res) => {
          if (res.data.length > 0) {
            this.attachments = res.data
          } else {
            this.attachments = []
          }
        })
    },
    // 获取所有评论
    queryComment(params) {
      KmKnowledageService.getKnowledgeComment(params).then((res) => {
        if (res.data.totalSize < 4) {
          this.showLoadingMore = false
        }
        this.pagination.total = res.data.totalSize
        this.lastPage = Math.ceil(res.data.totalSize / this.pagination.pageSize)
        if (
          this.comments.length !== 0 &&
          this.moreData === true &&
          this.showLoadingMore !== false
        ) {
          this.comments = this.comments.concat(res.data.data)
          this.loadingMore = false
          this.$nextTick(() => {
            window.dispatchEvent(new Event('resize'))
          })
        } else {
          this.comments = res.data.data
          this.allCommentNum = res.data.totalSize
        }
        if (parseInt(this.pagination.total / 3) === this.clickNum) {
          this.showLoadingMore = false
        }
      })
    },
    // 获取更多评论
    clickMore() {
      this.clickNum++
      if (this.comments.length === this.allCommentNum) {
        this.showLoadingMore = false
      }
      if (this.allCommentNum < 4) {
        this.showLoadingMore = false
      }
      this.loadingMore = true
      this.moreData = true
      this.pagination.current += 1
      this.commentParams.startPosition =
        this.commentParams.maxResults * (this.pagination.current - 1)
      this.$nextTick(function() {
        this.queryComment(this.commentParams)
      })
    },
    // 获取知识点赞数
    queryKnowledgeComment() {
      const params = {
        id: this.$route.query.id,
      }
      KmKnowledageService.getKnowledgePraiseNum(params).then((res) => {
        this.badgeCount = res.data
      })
    },
    // 借阅提醒弹框
    showRemind() {
      const _this = this
      Modal.confirm({
        title: '借阅提醒',
        content: (h) => <div>您没有该文档的阅读权限，是否申请借阅？</div>,
        onOk() {
          _this.$router.replace(
            `/km-flow-guide?code=PROJECT_ZSGL_ZSJY&knowledgeId=${_this.$route.query.id}&title=${_this.$route.query.title}`
          )
        },
        onCancel() {
          window.close()
        },
        class: 'test',
      })
    },
    // 知识点赞
    handleLike(v) {
      const params = {
        id: this.$route.query.id,
      }
      KmKnowledageService.getKnowledgePraise(params).then((res) => {
        if (res.status === 200) {
          if (this.news.praiseed) {
            this.badgeCount = this.badgeCount - 1
            Message.success({ content: '取消点赞' })
            this.flag = false
            this.news.praiseed = false
          } else {
            this.badgeCount = this.badgeCount + 1
            Message.success({ content: '点赞成功' })
            this.flag = true
            this.news.praiseed = true
          }
          this.queryKnowledgeComment()
          // // 获取详情
          // this.queryKnowledgeDetails()
        }
      })
    },
    // 收藏
    handleCollect(v) {
      this.favoritiesShow = true
    },
    // 选择收藏夹save
    handleOkInFavorities(e) {
      this.onFavorities()
    },
    // 新建收藏夹
    createFavorites(e) {
      this.show = !this.show
    },
    getselectKey(key) {
      this.modelSelectedKey = key
    },
    // 收藏按钮点击处理， 目前通用接口没返回，手写的
    onFavorities() {
      const key = Symbol.for()
      Message.loading({ content: '处理中...', key })
      const url = window.location.hash
      const params = {
        eventId: 'save',
        inputs: [
          {
            name: 'title',
            value: this.news.title,
          },
          {
            name: 'topping',
            value: 1, // 0置顶， 1不置顶，默认不置顶
          },
          {
            name: 'url',
            value: url.split('#')[1],
          },
          {
            name: 'formId',
            value: this.news.formId,
          },
          {
            name: 'beanType',
            value: String(this.news.beanId),
          },
          {
            name: 'folderId',
            value: this.modelSelectedKey,
          },
          {
            name: 'businessTypeName',
            value: this.news.businessTypeName,
          },
          {
            name: 'businessTypeId',
            value: this.news.businessTypeId,
          },
        ],
        pageFlowId: 'string',
        pagePath: 'comp/bookmark/kmBookmarkContent',
      }
      FlowService.saveFavorities(params).then(
        () => {
          Message.success({ content: '收藏成功', key })
          this.news.collectioned = true
        },
        (_) => {
          Message.error({ content: '收藏失败', key })
        }
      )
      this.favoritiesShow = false
    },
    // 取消收藏
    onCancelFavorities() {
      const key = Symbol.for()
      Message.loading({ content: '处理中...', key })
      const params = {
        formId: this.news.formId,
        beanType: this.news.beanId,
      }
      FlowService.cancelFavorities(params).then(
        () => {
          Message.success({ content: '取消收藏成功', key })
          this.news.collectioned = false
        },
        (_) => {
          Message.error({ content: '取消收藏失败', key })
        }
      )
    },
    // 推荐
    handleRecommend(v) {
      this.isClick = v
      this.isRecommend = true
    },

    recomentChange(values) {},
    // 点评
    goAnchor(v) {
      this.isClick = v
      this.$refs.textarea.focus()
      document.getElementById('divId').scrollIntoView()
    },
    // 生成链接
    goLink(v) {
      this.isClick = v
      this.copyToClip(window.location.href)
    },
    copyToClip(content, message) {
      var aux = document.createElement('input')
      aux.setAttribute('value', content)
      document.body.appendChild(aux)
      aux.select()
      document.execCommand('copy')
      document.body.removeChild(aux)
      if (message == null) {
        Message.success('链接已生成！')
      } else {
        Message.warning('链接生成出错！')
      }
    },
    // 勘误
    goEdit(v) {
      this.isEdit = !this.isEdit
    },

    // 新版本
    goEdition(v) {
      this.isClick = v
      this.editionModal = true
    },
    handleEditionModalOk() {
      this.$refs.editionRuleForm.validate((valid) => {
        if (valid) {
          const advancedFields = this.news.applyPerson.map((item) => item.name).join(',')
          const attFields = []
          attFields.push(this.news.applyAttachment)
          attFields.push(this.news.coverAttachment)
          const inputs = [
            {
              name: 'flowId',
              value: this.news.flowId,
            },
            {
              name: 'formId',
              value: this.news.formId,
            },
            {
              name: 'beanId',
              value: String(this.news.beanId),
            },
            {
              name: 'advancedFields',
              value: advancedFields,
            },
            {
              name: 'attFields',
              value: 'applyAttachment,coverAttachment',
            },
            {
              name: 'pagePath',
              value: '/knowledge/contribution/kmKnowledge',
            },
          ]
          // 复制附件
          KmKnowledageService.copyAttachment({ inputs: inputs }).then((res) => {
            window.open(
              `#/sd-webflow/pages/draft/${res.data.instId}?versionNum=${this.editionForm.edition}&relationId=${this.news.relationId}`,
              '_blank'
            )
            this.editionForm.edition = ''
          })
          this.editionModal = false
        } else {
          return false
        }
      })
    },
    handleEditionModalCancel() {
      this.editionModal = false
    },
    change(values) {},
    // tab切换
    callback(key) {
      if (key === '2') {
        // 获取推荐，访问记录
        this.queryRecommendOrVisitRecord(this.recommendrecord, key)
      } else if (key === '3') {
        // 获取推荐，访问记录
        this.queryRecommendOrVisitRecord(this.visitedrecord, key)
      }
    },
    // 发表评论
    handleSubmit() {
      if (!this.commentValue) {
        return
      }
      this.submitting = true
      this.publishData.inputs[0].value = this.commentValue
      KmKnowledageService.getComment(this.publishData).then((res) => {
        if (res.status === 200) {
          this.submitting = false
          this.still = 1000
          Message.success({ content: '评论成功！', duration: 1 })
          if (!this.showLoadingMore) {
            // 初始化为0
            this.commentParams.startPosition = this.startNum
            // 结束位置+1
            this.commentParams.maxResults = this.pagination.total + 1
            this.$nextTick(function() {
              this.queryComment(this.commentParams)
            })
          } else {
            this.$nextTick(function() {
              this.queryComment(this.commentParams)
            })
          }
          this.commentValue = ''
        }
      })
    },
    handleChange() {
      const txtVal = this.commentValue.length
      this.still = 1000 - txtVal
    },
    // 评论点赞
    like(item) {
      KmKnowledageService.getPraise({ id: item.id })
        .then((res) => {
          this.moreData = false
          if (res.data.accountOperation === 0) {
            Message.success('取消点赞成功', 2)
          } else {
            Message.success('点赞成功', 2)
          }
          if (!this.showLoadingMore) {
            // 初始化为0
            this.commentParams.startPosition = this.startNum
            // 结束位置为
            this.commentParams.maxResults = this.pagination.total + 1
            this.$nextTick(function() {
              this.queryComment(this.commentParams)
            })
          } else {
            this.$nextTick(function() {
              this.queryComment(this.commentParams)
            })
          }
        })
        .catch(() => {
          this.submitting = false
        })
    },
    treeSelected() {},
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.path, flag)
      window.close()
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
$header-lh: 50px;
$comment-bg: #e4e4e4;
$font-size-middle: 14px;
$link-icon-size: 22px;
$bgcolor: #f7f7f7;

.layout {
  height: 100%;
  .layout-content {
    min-height: calc(100% - 64px);
  }
  .bgcolor {
    height: 100%;
    background: $bgcolor;
    :global(.ant-card-body) {
      background-color: $bgcolor;
    }
  }
  .header {
    width: 100%;
    height: 50px;
    padding: 0 20px;
    line-height: $header-lh;
    color: $heading-color-dark;
    background-color: $primary-color;
  }
  .news-main {
    max-width: 1300px;
    margin: 0 auto;
  }
  .recoment-radio {
    margin-left: 140px;
  }
  .know-ledage {
    padding: 20px 0;
    overflow: hidden;
    .kl-operation {
      width: 100%;
      padding-top: 20px;
      margin-bottom: 20px;
      text-align: left;
      .drage {
        sup {
          top: -8px;
          span {
            p {
              color: $heading-color-dark;
            }
          }
        }
      }
      .is-active {
        color: $primary-color;
        i {
          color: $primary-color;
        }
      }
      > span {
        margin-right: 20px;
      }
      span {
        color: $text-color;
        i {
          padding-right: 5px;
        }
        &:hover {
          color: $primary-color;
          cursor: pointer;
        }
      }
      .down-btn {
        float: right;
        padding: 6px 20px;
        color: $white;
        background: $primary-color;
        border-radius: $border-radius-base;
      }
    }
    .kl-article {
      margin-top: 10px;
      .left-content {
        h3 {
          font-size: $heading-3-size;
          text-align: center;
        }
        .infos {
          padding-bottom: 10px;
          text-align: center;
          :global(.ant-tag) {
            background: white;
          }
          span {
            padding-right: 15px;
            font-size: $font-size-middle;
            i {
              font-style: normal;
              color: $highlight-color;
            }
          }
        }
        .content {
          min-height: 250px;
          padding-top: 40px;
          margin-bottom: 40px;
          p {
            font-size: $font-size-base;
            line-height: $line-height-base;
            text-indent: 60px;
          }
        }
        .files {
          margin: 0 0 10px;
          overflow: hidden;
          .files-name {
            float: left;
          }
          .files-btn {
            float: right;
            button {
              margin-right: 20px;
            }
          }
        }
        .artice-text {
          padding: 40px 40px 10px;
          background: #fff;
        }
        .comment {
          padding: 20px;
          margin-top: 20px;
          background: #fff;
          .pl-content {
            .comment-text {
              margin-bottom: 10px;
            }
            .comment-score {
              .score {
                float: left;
              }
              .publish {
                float: right;
                .text-num {
                  padding-right: 40px;
                  font-size: $font-size-middle;
                  color: $modal-mask-bg;
                  em {
                    padding: 0 2px;
                    font-style: normal;
                  }
                }
              }
            }
          }
          .comment-list {
            margin-top: -20px;
          }
        }
      }
      .right-content {
        margin: 0 0 0 40px;
        .article-info {
          padding: 20px;
          margin-bottom: 20px;
          background: #fff;
          p.title {
            font-size: $font-size-lg;
            font-weight: bold;
          }
          .user-info {
            padding-top: 10px;
            p {
              margin-bottom: 10px;
            }
            .user-img {
              padding-bottom: 10px;

              .username {
                margin-top: 8px;
                margin-bottom: 0;
                font-size: $btn-font-size-lg;
                font-weight: bold;
              }
              .userinfo {
                width: 65px;
                height: 65px;
                border-radius: 50%;
              }
            }
            .user-num {
              padding: 10px 0;
              span {
                padding-right: 40px;
                font-weight: bold;
                color: $black;
                i {
                  padding-right: 10px;
                }
              }
            }
          }
          .infos {
            p {
              margin-bottom: 5px;
              font-size: $btn-font-size-sm;

              i {
                width: 4em; /* 这个值是看最长能显示几个文字，如x，则为x em */
                margin-right: -2em; /* 同上 */
                font-style: normal;
                text-align: center;
                letter-spacing: 2em; /* 如果需要y个字两端对齐，则为(x-y)/(y-1),这里是（4-2）/(2-1)=2em */
              }
            }
          }
          .wordlist {
            .downloda {
              display: inline-block;
              width: 100%;
              padding: 0 10px;
              line-height: $btn-height-lg;
              color: $btn-default-color;
              cursor: pointer;

              i {
                padding-left: 10px;
              }
            }
            .actived {
              background: rgba(173, 212, 247, 0.78);
            }
            .defalut-color {
              background: rgba(173, 212, 247, 0.78);
            }
          }
        }
      }
      .moredata {
        margin-top: 20px;
        text-align: center;
        cursor: pointer;
      }
      .no-comment {
        text-align: center;
      }
    }
    .wpsread {
      height: 800px;
    }

    .example {
      text-align: center;
    }
  }
  .handle-btn {
    padding: 0 $link-icon-size / 2;
    span {
      padding: 0 $link-icon-size / 2;
      margin-right: 0;
      margin-left: 10px;
      cursor: pointer;
      a {
        cursor: pointer;
      }
    }
  }
  .list-item {
    display: flex;

    div {
      &:first-child {
        min-width: 150px;
      }
      &:nth-child(2) {
        margin-left: 50px;
      }
      &:nth-child(3) {
        margin-left: 50px;
      }
    }
  }
  .ulheight {
    :global(.ant-list-items) {
      max-height: 500px;
      overflow-y: scroll;
    }
  }
  :global(.ant-divider) {
    margin: 0;
  }
}
</style>
