<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.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 JSON.parse(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">
          <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="180" v-if="detailData.downloadStatus">
              <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" @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 左侧页签-->
    <div class="fr">
      <div class="tboper">
        <div class="tit">评论</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">{{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">{{getFirstChar(repItem.nickName)}}</span></div>
                  <div class="ltext">
                    <div class="nt"><span class="name">{{repItem.nickName}}</span><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)">发布</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>

    <!-- 上传 -->
    <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 AddDoc from './AddDoc'
  import editDocument from "../document/editDocument";
  import { Base64 } from 'js-base64';
  import iFrame from "@/components/iFrame/index"
  import { addCount } from "@/api/tool/downloadCount";
  import { listAttachment } from "@/api/attachment/attachment";

  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: {},
        required: false
      }
    },
    data(){
      return{
        detailActiveName: 'first',
        attachmentList: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          toolId: ''
        },
        previewUrl: '',
        viewDialogTitle: "",
        viewDialogOpen: false,
        title: '新增文档',
        open: false,
        loadingDownload: false,
        discussionContent: null, // 评论内容
        repliesContent: null, // 回复内容
        // 评论列表
        discussionsList: [],
        // 回复列表
        repliesList: [],
        showReplyForm: [],
        replyContent: [],
        detailLoading: false,
        //详细数据
        detailData:{},
        attFileType: "zip,rar,7z",
      }
    },
    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.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.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 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
      },
      /** 获取详情信息 **/
      getDetail(){
        let self = this
        self.detailLoading = true
        getTool(self.toolDetail.toolId).then((res) => {
          self.detailData = res.data
          /*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;
      },
    }
  }
</script>

<style scoped>

</style>
