<template>
  <div class="fbox1">
    <div class="fl" v-loading="detailLoading">
      <el-tabs v-model="detailActiveName">
        <el-tab-pane label="基本信息" name="first">
          <div class="el-form-border">
            <el-form ref="form" label-width="150px">
              <el-row>
                <el-col :span="12"> <el-form-item label="中文别名">{{detailData.toolName}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="类别"><dict-tag :options="dict.type.tool_type" :value="detailData.toolType"/></el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="来源"><dict-tag :options="dict.type.tool_source" :value="detailData.toolSource"/></el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="负责人">{{detailData.toolPrincipalsName}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="归属单位">{{detailData.toolRespDeptName}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="形态"><dict-tag :options="dict.type.tool_status" :value="detailData.status"/></el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="加密方式">{{detailData.encryptionMode}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="服务时间">{{detailData.serviceTime}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="联系人">{{detailData.contactPerson}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="联系方式">{{detailData.contactPhone}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="用途">{{detailData.toolUse}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="测评机构">{{detailData.testSituation}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="功能简介">{{detailData.functionDesc}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="适用条件">{{detailData.applyCondition}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="操作说明">{{detailData.operateExplain}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="备注">{{detailData.remark}}</el-form-item> </el-col>
                <el-col :span="24">
                  <el-form-item label="关联工具">
                    <span v-if="detailData.association != null && detailData.association != '' && detailData.association != undefined">
                     <el-tag :key="tag.toolId" v-for="tag in detailData.association" type="info" style="margin-right: 5px">{{tag.toolName}}</el-tag>
                    </span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form><!--el-form-->
          </div><!--el-form-border 表单-->
        </el-tab-pane><!--el-tab-pane-->
        <el-tab-pane label="关联附件" name="second" v-loading="previewLoading" element-loading-text="预览转换中，请耐心等待">
          <el-table :data="attachmentList" style="width: 100%">
            <el-table-column label="附件名称" prop="fileName" :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.createDate) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="150px">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  v-if="previewAuth(scope.row)"
                  @click="handlePreview(scope.row)"
                >预览</el-button>
                <el-button type="text" icon="el-icon-download" v-if="detailData.downloadStatus" @click="handleDownload(scope.row)" v-loading="loadingDownload">
                  下载
                </el-button>
              </template>
            </el-table-column>
          </el-table><!--el-table-->
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getAttachmentList"
          />
        </el-tab-pane><!--el-tab-pane-->
      </el-tabs><!--el-tabs-->
    </div><!--fl 左侧页签-->
    <div class="fr" v-if="isComment">
      <div class="tboper">
        <div class="tit">评论（{{ reviewTotal }}）</div>
      </div><!--tboper 标题与操作按钮-->
      <div class="pltextarea">
        <el-input v-model="discussionContent" type="textarea" placeholder="请输入您的意见" :rows="4" maxlength="1000" show-word-limit></el-input>
        <div class="plbtn"><el-button @click="handleDiscussions">发布</el-button></div>
      </div><!--pltextarea-->
      <div class="pllist">
        <template v-if="discussionsList && discussionsList.length > 0">
          <div class="list" v-for="(item,index) in discussionsList" :key="item.id">
            <div class="luser"><span class="xuser" :style="{backgroundColor: extractColorByName(item.nickName)}">{{getFirstChar(item.nickName)}}</span></div>
            <div class="ltext">
              <div class="nt"><span class="name">{{item.nickName}}</span><span class="time">{{ parseTime(item.createTime, '{y}-{m}-{d} {h}:{i}') }}</span></div>
              <div class="te">{{item.content}}</div>
              <div class="hb">
                <a class="btn" @click="toggleReplyForm(index)">
                  <i class="el-icon-chat-line-round"></i>回复
                </a>
              </div>
              <div class="pltextarea" v-if="showReplyForm[index]">
                <el-input type="textarea" v-model="replyContent[index]" placeholder="请输入您的意见" :rows="2" maxlength="1000" show-word-limit></el-input>
                <div class="plbtn">
                  <el-button @click="cancelReply(index)">取消</el-button>
                  <el-divider direction="vertical"></el-divider>
                  <el-button @click="submitReply(index, item)">发布</el-button>
                </div>
              </div>
              <!--第二层级-->
              <template v-if="item.repliesList && item.repliesList.length > 0">
                <div class="list" v-for="(repItem, repIdex) in item.repliesList" :key="repItem.id">
                  <div class="luser">
                    <span class="xuser" :style="{width:'28px',height:'28px',lineHeight:'28px',backgroundColor: extractColorByName(repItem.nickName)}">{{getFirstChar(repItem.nickName)}}</span>
                  </div>
                  <div class="ltext">
                    <div class="nt">
                      <span class="name">{{repItem.nickName}}</span>
                      <template v-if="repItem.repTargetNickName">
                        <span>回复</span>
                        <span class="name">{{ repItem.repTargetNickName }}</span>
                      </template>
                      <span class="time">{{ parseTime(repItem.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                    </div>
                    <div class="te">{{repItem.content}}</div>
                    <div class="hb"><a class="btn" @click="toggleReplyFormSon(index,repIdex)"><i class="el-icon-chat-line-round"></i>回复</a></div>
                    <div class="pltextarea" v-if="item.showReplyFormSon[repIdex]">
                      <el-input type="textarea" v-model="item.replyContentSon[repIdex]" placeholder="请输入您的意见" :rows="2" maxlength="1000" show-word-limit></el-input>
                      <div class="plbtn">
                        <el-button @click="cancelReplySon(index,repIdex)">取消</el-button>
                        <el-divider direction="vertical"></el-divider>
                        <el-button @click="submitReplySon(index, repIdex, item, repItem.id)">发布</el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </template>
      </div>
    </div>
    <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>

    <preview-util v-if="isPreviewDisable" ref="previewForm" @previewClose="previewClose" @previewLoadingClose="previewLoadingClose"></preview-util>


    <!-- 关联工具展示 -->
    <el-dialog title="关联工具" :visible.sync="toolTreeVisible"  width="980px" append-to-body :close-on-press-escape="false" :close-on-click-modal="false"
               :show-close="false" :wrapperClosable="false" v-loading="toolTreeLoading">
      <el-tree :data="toolRelationOptions" :props="defaultProps"></el-tree>
      <!--      <el-table
              :data="relationToolData"
              border
              ref="multipleTable"
              header-align="left"
            >
              <el-table-column label="序号" width="60" type="index" align="center"></el-table-column>
              <el-table-column label="工具编号"  key="toolCode" prop="toolCode"/>
              <el-table-column label="工具名称"  key="toolName" prop="toolName":show-overflow-tooltip="true" />
              <el-table-column label="操作" width="100px" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="selectDelete(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            &lt;!&ndash; 分页组件 &ndash;&gt;
            <el-pagination
              v-show="relationToolTotal > 0"
              :current-page.sync="currentToolPage"
              :page-size.sync="pageToolSize"
              :total="relationToolTotal"
              @current-change="handlePageToolChange"
              layout="total, prev, pager, next"
            />-->
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="toolTreeVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 上传 -->
<!--    <AddDoc :show.sync="open" :toolId="detailData.toolId" @callback="getAttachmentList"/>-->
  </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 { getTool } from "@/api/tool/tool.js";
  import iFrame from "@/components/iFrame/index"
  import { addCount } from "@/api/tool/downloadCount";
  import { listAttachment } from "@/api/attachment/attachment";
  import previewUtil from '@/components/PreviewUtil/previewUtil.vue'
  import { getDataThree } from '@/api/tool/toolRelation'

  export default {
    name: 'toolDetail',
    components: { iFrame, previewUtil },
    dicts:['sys_normal_disable','tool_type','tool_source','tool_status','doc_class','doc_source'],
    props: {
      toolDetail: {
        type: Object,
        default: {},
        required: false
      },
      //是否展示下载
      isDownload: {
        type: Boolean,
        default: true,
        required: false
      },
      //是否展示评论
      isComment: {
        type: Boolean,
        default: true,
        required: false
      },
    },
    data(){
      return{
        detailActiveName: 'first',
        attachmentList: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          toolId: ''
        },
        reviewTotal: 0,
        previewUrl: '',
        viewDialogTitle: "",
        viewDialogOpen: false,
        title: '新增文档',
        open: false,
        loadingDownload: false,
        discussionContent: null, // 评论内容
        repliesContent: null, // 回复内容
        // 评论列表
        discussionsList: [],
        // 回复列表
        repliesList: [],
        showReplyForm: [],
        replyContent: [],
        detailLoading: false,
        //详细数据
        detailData:{},
        attFileType: "zip,rar,7z",
        // json
        dialogVisible:false,
        isJson:false,
        resultContentObj:[],
        // docx
        isDocx:false,
        docxData: null,
        //pdf文件
        isPdf:false,
        pdfFileData: null, // 默认文档类型
        previewLoading:false,
        previewUseFront: "txt,doc,docx,pdf",
        isPreviewDisable: false,
        total: 0,
        //工具树显示
        toolTreeVisible: false,
        toolTreeLoading: false,
        toolDataList: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        //工具关系选择项
        toolRelationOptions: [],

      }
    },
    created(){
      this.getDetail()
      this.getAttachmentList()
      this.getDiscussionsList()
    },
    watch: {
      discussionsList(newList) {
        this.showReplyForm = new Array(newList.length).fill(false);
        this.replyContent = new Array(newList.length).fill('');
      }
    },
    methods:{
      getAttachmentList() {
        this.loading = true;
        this.$set(this.queryParams,'del',"0")
        this.$set(this.queryParams,'businessId',this.toolDetail.toolId)
        listAttachment(this.queryParams).then(response => {
            this.attachmentList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      handleAdd(){
        this.open = true
      },
      editDocumentSubmit(){
        this.open = false
        this.getAttachmentList()
      },
      handlePreview(row){
        this.isPreviewDisable = true
        this.$nextTick(() => {
          this.$refs.previewForm.frontModulePreview(row)
        })
      },
      /** 关闭预览 **/
      previewClose(){
        this.isPreviewDisable = false
      },
      /** 关闭预览遮罩 **/
      previewLoadingClose(){
        this.previewLoading = false
      },
      /** 删除按钮操作 */
      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.fileUrl);

        //保存下载记录
        if(row.businessId){
          let formData = {
            'businessId': row.businessId,
            'businessType': 'tool',
            'attId': row.id,
            'attName': row.fileOldName
          }
          addCount(formData).then(res => {
          });
        }

        setTimeout(()=>{
          self.loadingDownload = false
        },1000)
      },
      getDiscussionsList() {
        let _this = this
        _this.reviewTotal = 0
        listDiscussions({businessId: _this.toolDetail.toolId}).then(res => {
          _this.discussionsList = res.rows
          let reviewTotal = 0
          _this.discussionsList.forEach(item => {
            if(item.repliesList && item.repliesList.length > 0){
              reviewTotal += item.repliesList.length
              _this.$set(item, 'showReplyFormSon', new Array(item.repliesList.length).fill(false))
              _this.$set(item, 'replyContentSon', new Array(item.repliesList.length).fill(''))
            }else{
              _this.$set(item, 'showReplyFormSon', false)
              _this.$set(item, 'replyContentSon', '')
            }
          });
          _this.reviewTotal = _this.discussionsList.length + reviewTotal
        });
      },
      /** 评论 **/
      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("发布失败");
          });
        })
      },
      extractColorByName(name) {
        let temp = [];
        temp.push("#");
        for (let index = 0; index < name.length; index++) {
          temp.push(parseInt(name[index].charCodeAt(0), 10).toString(16));
        }
        return temp.slice(0, 5).join('').slice(0, 4);
      },
      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, repId) {
        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,
          "repId": repId,
          "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()
            // 清空回复内容并隐藏表单
            this.$set(parentItem.replyContentSon, repIndex, '');
            this.$set(parentItem.showReplyFormSon, repIndex, false);
          }).catch(err =>{
            console.error("submitReplySon==err==", err)
            self.$modal.msgError("发布失败");
          });
        })
      },
      handleBeforeClose() {
        this.viewDialogOpen = false
      },
      /** 获取详情信息 **/
      getDetail(){
        let self = this
        self.detailLoading = true
        getTool(self.toolDetail.toolId).then((res) => {
          self.detailData = res.data
          self.detailData.association = JSON.parse(res.data.association)
          /*let formData = res.data;
          formData.type = _this.form.type
          _this.form = formData*/
        }).finally(()=>{
          self.detailLoading = false
        });
      },
      previewAuth(row){
        if(row.fileUrl == null || row.fileUrl == '' || row.fileUrl == undefined){
          return false
        }
        let extension = this.getExtension(row.fileUrl);
        const acceptedExtensions = this.attFileType.toLowerCase().split(',');
        if(acceptedExtensions.includes(extension)){
          return false
        }
        return true
      },
      getExtension(filePath) {
        // 分割字符串，以 '.' 为分隔符
        const parts = filePath.split('.');
        // 取最后一个部分作为后缀名
        const extension = parts.pop();
        return extension;
      },
      /** 获取工具关联树展示 */
      getToolRelationTree() {
        let self = this
        let toolRelation ={
          resourceId: "",
        }
        let toolIds = []
        if(self.detailData.toolId){
          self.$set(toolRelation,"resourceIds",[self.detailData.toolId])
        }else if(self.detailData.association && self.detailData.association.length > 0){
          self.detailData.association.forEach(item=>{
            toolIds.push(item.toolId)
          })
          self.$set(toolRelation,"resourceIds",toolIds)
        }

        self.toolTreeVisible = true;
        self.toolTreeLoading = true;
        getDataThree(toolRelation).then(res => {
          if(self.detailData.toolName){
            let treeArray = []
            let treeData = {
              "id": "20240908001",
              "label": self.detailData.toolName,
              "types": null,
              "children": res.data
            }
            treeArray.push(treeData)
            this.toolRelationOptions = treeArray;
            self.toolTreeLoading = false;
            return
          }
          this.toolRelationOptions = res.data;
          self.toolTreeLoading = false;
        }).catch(err => {
          console.error("err========", err)
          self.toolTreeLoading = false;
        });
      },
    }
  }
</script>

<style scoped>

</style>
