<template>
  <div class="fbox1">
    <div class="fl">
      <el-tabs v-model="detailActiveName">
        <el-tab-pane label="文件信息" name="first">
          <el-table :data="docList" style="width: 100%">
            <el-table-column label="文档名称" prop="docName" :show-overflow-tooltip="true" />
            <el-table-column label="类别" prop="docType" :show-overflow-tooltip="true" width="80" >
              <template slot-scope="scope">
                <dict-tag :options="dict.type.doc_class" :value="scope.row.docType"/>
              </template>
            </el-table-column>
            <el-table-column label="负责人" prop="docPrincipals" :show-overflow-tooltip="true" width="80" />
            <el-table-column label="归属单位" align="center" prop="docRespDeptName" :show-overflow-tooltip="true" width="80" />
            <el-table-column label="来源" prop="docSource" width="100" >
              <template slot-scope="scope">
                <dict-tag :options="dict.type.doc_source" :value="scope.row.docSource"/>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180" v-if="toolDetail.downloadStatus">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handlePriew(scope.row)"
                >预览</el-button>
                <el-button type="text" icon="el-icon-download" @click="handleDownload(scope.row)" v-loading="loadingDownload">下载</el-button>
              </template>
            </el-table-column>
          </el-table><!--el-table-->
        </el-tab-pane><!--el-tab-pane-->
      </el-tabs><!--el-tabs-->
    </div><!--fl 左侧页签-->

    <el-dialog :title="viewDialogTitle" :visible.sync="viewDialogOpen" fullscreen width="500px" append-to-body :before-close="handleBeforeClose">
      <i-frame :src="previewUrl" v-if="viewDialogOpen"/>
    </el-dialog>
  </div><!--fbox1 左右分栏-->
</template>

<script>
  import { listDocument, getDocument, delDocument, addDocument, updateDocument } from "@/api/document/document";
  import { listDiscussions, addDiscussions } from "@/api/tool/discussions.js";
  import { listReplies, addReplies} from "@/api/tool/replies.js";

  import { addCount } from "@/api/tool/downloadCount";
  import AddDoc from './AddDoc'
  import editDocument from "../document/editDocument";
  import { Base64 } from 'js-base64';
  import iFrame from "@/components/iFrame/index"

  export default {
    name: 'toolDetail',
    components: { editDocument, AddDoc, iFrame },
    dicts:['sys_normal_disable','tool_type','tool_source','tool_status','doc_class','doc_source'],
    props: {
      toolDetail: {
        type: Object,
        default: {},
      }
    },
    data(){
      return{
        detailActiveName: 'first',
        docList: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          toolId: ''
        },
        previewUrl: '',
        viewDialogTitle: "",
        viewDialogOpen: false,
        title: '新增文档',
        open: false,
        loadingDownload: false,
        discussionContent: null, // 评论内容
        repliesContent: null, // 回复内容
        // 评论列表
        discussionsList: [],
        // 回复列表
        repliesList: [],
        showReplyForm: [],
        replyContent: [],
      }
    },
    created(){
      this.getDocList()
      this.getDiscussionsList()
    },
    watch: {
      discussionsList(newList) {
        this.showReplyForm = new Array(newList.length).fill(false);
        this.replyContent = new Array(newList.length).fill('');
      }
    },
    methods:{
      getDocList() {
        this.loading = true;
        this.queryParams.toolId = this.toolDetail.toolId
        listDocument(this.queryParams).then(response => {
            this.docList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      handleAdd(){
        this.open = true
      },
      editDocumentSubmit(){
        this.open = false
        this.getDocList()
      },
      handlePriew(row){
        this.previewUrl = process.env.VUE_APP_TOOL_TECH_FILE_VIEW_API + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(process.env.VUE_APP_BASE_API + row.docUrl));
        this.viewDialogTitle = '文档在线预览'
        this.viewDialogOpen = true;
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const docIds = row.docId || this.ids;
        this.$modal.confirm('是否确认删除？').then(function() {
          return delDocument(docIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /**
       * 处理下载
       * **/
      handleDownload(row){
        let self = this
        self.loadingDownload = true
        this.$download.resource(row.docUrl);

        //保存下载记录
        if(this.toolDetail.toolId){
          let formData = {
            toolId: this.toolDetail.toolId
          }
          addCount(formData).then(res => {
          });
        }

        setTimeout(()=>{
          self.loadingDownload = false
        },1000)
      },
      getDiscussionsList() {
        let self = this
        listDiscussions({businessId:this.toolDetail.toolId}).then(res => {
          self.discussionsList = res.rows
          self.discussionsList.forEach(item => {
            if(item.repliesList && item.repliesList.length > 0){
              self.$set(item, 'showReplyFormSon', new Array(item.repliesList.length).fill(false))
              self.$set(item, 'replyContentSon', new Array(item.repliesList.length).fill(''))
            }else{
              self.$set(item, 'showReplyFormSon', false)
              self.$set(item, 'replyContentSon', '')
            }
          });
        });
      },
      /** 评论 **/
      handleDiscussions(){
        let self = this
        if (this.discussionContent == '' || this.discussionContent == null || this.discussionContent == undefined) {
          self.$message({
            message: '内容不能为空',//提示的信息
            type:'warning',　　//类型是成功
            duration:1200,　　//显示时间, 毫秒。设为 0 则不会自动关闭，建议1200
          });
          return;
        }
        let data = {
          businessId: this.toolDetail.toolId,
          content: this.discussionContent,
          type: "tool",
        }
        self.$modal.confirm('是否确认发布？').then(()=> {
          addDiscussions(data).then(res => {
            this.discussionContent = null
            self.$message({
              message: '发布成功',//提示的信息
              type:'success',　　//类型是成功
              duration:1200,　　//显示时间, 毫秒。设为 0 则不会自动关闭，建议1200
            });
            self.getDiscussionsList()
          }).catch(err =>{
            this.discussionContent = null
            console.error("handleDiscussions==err==", err)
            self.$modal.msgError("发布失败");
          });
        })
      },
      getFirstChar(value) {
        if(!value){return ''}
        return value.charAt(0);
      },
      toggleReplyForm(index) {
        this.$set(this.showReplyForm, index, !this.showReplyForm[index]);
      },
      cancelReply(index) {
        this.$set(this.showReplyForm, index, false);
        this.$set(this.replyContent, index, '');
      },
      /** 回复 **/
      submitReply(index, item) {
        let self = this
        const content = this.replyContent[index];
        if (content == '' || content == null || content == undefined) {
          self.$message({
            message: '回复内容不能为空',//提示的信息
            type:'warning',　　//类型是成功
            duration:1200,　　//显示时间, 毫秒。设为 0 则不会自动关闭，建议1200
          });
          return;
        }
        let data = {
          "discussionId": item.id,
          "content": content,
        }

        self.$modal.confirm('是否确认发布？').then(()=> {
          addReplies(data).then(res => {
            self.$message({
              message: '发布成功',//提示的信息
              type:'success',　　//类型是成功
              duration:1200,　　//显示时间, 毫秒。设为 0 则不会自动关闭，建议1200
            });
            self.cancelReply(index)
            self.getDiscussionsList()
          }).catch(err =>{
            console.error("handleDiscussions==err==", err)
            self.$modal.msgError("发布失败");
          });
        })

        // 清空回复内容并隐藏表单
        this.replyContent[index] = '';
        this.showReplyForm[index] = false;
      },



      /** 第二级 **/
      toggleReplyFormSon(parentIndex, repIndex) {
        const parentItem = this.discussionsList[parentIndex];
        this.$set(parentItem.showReplyFormSon, repIndex, !parentItem.showReplyFormSon[repIndex]);
        // this.$set(this.showReplyFormSon, index, !this.showReplyFormSon[index]);
      },
      /** 第二级，取消回复 **/
      cancelReplySon(parentIndex, repIndex) {
        const parentItem = this.discussionsList[parentIndex];
        this.$set(parentItem.showReplyFormSon, repIndex, false);
        this.$set(parentItem.replyContentSon, repIndex, '');
      },
      /** 第二级回复 **/
      submitReplySon(parentIndex, repIndex, repItem) {
        let self = this
        const parentItem = this.discussionsList[parentIndex];
        const content = parentItem.replyContentSon[repIndex];
        if (content.trim() == '' || content == null || content == undefined) {
          self.$message({
            message: '回复内容不能为空',//提示的信息
            type:'warning',　　//类型是成功
            duration:1200,　　//显示时间, 毫秒。设为 0 则不会自动关闭，建议1200
          });
          return;
        }
        let data = {
          "discussionId": repItem.id,
          "content": content,
        }

        self.$modal.confirm('是否确认发布？').then(()=> {
          addReplies(data).then(res => {
            self.$message({
              message: '发布成功',//提示的信息
              type:'success',　　//类型是成功
              duration:1200,　　//显示时间, 毫秒。设为 0 则不会自动关闭，建议1200
            });
            self.cancelReplySon(parentIndex, repIndex)
            self.getDiscussionsList()
          }).catch(err =>{
            console.error("submitReplySon==err==", err)
            self.$modal.msgError("发布失败");
          });
        })

        // 清空回复内容并隐藏表单
        this.$set(parentItem.replyContentSon, repIndex, '');
        this.$set(parentItem.showReplyFormSon, repIndex, false);
      },
      handleBeforeClose() {
        this.viewDialogOpen = false
      }
    }
  }
</script>

<style scoped>

</style>
