<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="24"> <el-form-item label="文件分类">{{form.docCategoryName}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="文档编号">{{form.docCode}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="文档名称">{{form.docName}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="文档类别"><dict-tag :options="dict.type.doc_class" :value="form.docType"/></el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="文档来源"><dict-tag :options="dict.type.doc_source" :value="form.docSource"/></el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="负责人">{{form.docPrincipalsName}}</el-form-item> </el-col>
                <el-col :span="12"> <el-form-item label="归属单位">{{form.docRespDeptName}}</el-form-item> </el-col>
                <el-col :span="24"> <el-form-item label="备注">{{form.remark}}</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="序号" width="60" type="index" align="center"></el-table-column>
            <el-table-column label="附件名称" prop="fileName" :show-overflow-tooltip="true" />
<!--            <el-table-column label="操作" align="center" width="180" v-if="!detailBoolean">
              <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="isShowOperation(scope.row)"
                           @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">评论</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>


  </div><!--el-form-border 表单-->
</template>

<script>
  import { addDocument, updateDocument, getDocument } from "@/api/document/document";
  import { deptTreeSelect } from "@/api/system/user";
  import { documentTree } from "@/api/documentCategory/documentCategory.js";
  import { listDiscussions, addDiscussions } from "@/api/tool/discussions.js";
  import { listReplies, addReplies} from "@/api/tool/replies.js";
  import { listAttachment } from "@/api/attachment/attachment";
  import { addCount } from "@/api/tool/downloadCount";

  export default {
    name: 'editDocument',
    components: {},
    dicts:['doc_class','doc_source'],
    props: {
      tooId: {
        type: String,
        default: "",
        required: false
      },
      relatedTool: {
        type: Boolean,
        default: true,
      },
      //是否展示下载
      isDownload: {
        type: Boolean,
        default() {
          return true
        },
        required: false
      },
      //是否展示评论
      isComment: {
        type: Boolean,
        default() {
          return true
        },
        required: false
      },
    },
    data(){
      return{
        detailActiveName: 'first',
        templateSelection: '',
        drawer1: false,
        checkList: [],
        // 表单参数
        form: {
          docId: undefined,
          docCategoryId: undefined,
          docCode: '',
          docName: '',
          docType: '',
          docPrincipals: null,
          docPrincipalsName: null,
          docRespDept: this.$store.getters.userInfo.deptId,
          docSource: '',
          toolId: '',
          remark: undefined,
          docCategoryName: undefined,
        },
        fileList: [],
        progress: 0,
        // 表单校验
        rules: {
        },
        docCategory:[],
        deptOptions:[],
        uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
        fileData: null,
        editStatus: true,
        toolDataInfo: [],
        dataFile: [],
        //详情
        detailBoolean: false,

        discussionContent: null, // 评论内容
        repliesContent: null, // 回复内容
        // 评论列表
        discussionsList: [],
        // 回复列表
        repliesList: [],
        showReplyForm: [],
        replyContent: [],
        detailLoading: false,
        attachmentList: [],
        attFileType: "zip,rar,7z",
        isPreviewDisable: false,
        loadingDownload: false,
        userInfo: this.$store.getters.userInfo,
        toolPrincipalsChoose: false,
        docQueryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        total: 0,
      }
    },
    computed: {
    },
    created(){
      // this.getDeptTree();
      this.getDocumentTree();
    },
    mounted(){
    },
    methods:{
      chooseToolConfirm(){
        this.$set(this.form, "toolId", this.templateSelection)
        this.drawer1 = false;
      },
      getCurrentRow(row){
        // 获取选中数据   row表示选中这一行的数据，可以从里面提取所需要的值
      },
      showOpenHandle(){
        this.reset();
        this.title = "上传文档";
      },
      // 表单重置
      reset() {
        this.form = {
          docName: '',
          docType: '',
          docPrincipals: '',
          docRespDept: '',
          docSource: '',
          toolId: ''
        };
        this.fileList = []
        this.resetForm("form");
      },
      // 取消按钮
      cancel() {
        this.drawer1 = false;
        this.reset();
      },
      generateUniqueID() {
        // 使用时间戳来生成唯一ID
        const timestamp = new Date().getTime();
        // 在ID前面添加一个前缀，以防止与其他ID冲突
        const uniqueID = 'file_' + timestamp;
        return uniqueID;
      },
      /** 查询部门下拉树结构 */
      getDeptTree() {
        deptTreeSelect().then(response => {
          this.deptOptions = response.data;
        });
      },
      /** 查询树形下拉树结构 */
      getDocumentTree() {
        documentTree().then(res => {
          this.docCategory = res.data;
        });
      },
      /**初始化 **/
      resetForm() {
        let self = this
        self.form.docPrincipalsName = null
        this.$refs.form.resetFields();
        this.toolDataInfo = []
        this.fileList = []
        this.attachmentList = []
        this.detailBoolean = false
        this.setAllRequiredTrue(true)
        this.$nextTick(()=>{
          if(self.$refs.uploadFile){
            self.$refs.uploadFile.clearFile();
          }
        })
      },
      editInit(docId, type){
        let self = this
        if(type == "detail"){
          this.detailBoolean = true
          self.setAllRequiredTrue(false)
        }
        self.$refs.form.resetFields();
        self.toolDataInfo = []
        self.$nextTick(()=>{
          if(self.$refs.uploadFile){
            self.$refs.uploadFile.clearFile();
          }

          getDocument(docId).then(res => {
            self.form = res.data
            self.toolDataInfo = []
            let toolInfo = {toolId:self.form.toolId,toolName:self.form.toolName}
            self.toolDataInfo.push(toolInfo)

            self.dataFile = []
           /*  let fileData = res.data.attachment
            self.$set(fileData, "name", fileData.fileOldName)
            self.$set(fileData, "size", fileData.fileSize)
            self.dataFile.push(fileData) */

            self.getAttachmentList()

            setTimeout(() => {
              self.$set(self.form, "docCategoryName" , self.findLabelById(self.docCategory, self.form.docCategoryId) )
            }, 300);

          });
        })
      },
      /** 评论 **/
      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.form.docId,
          content: this.discussionContent,
          type: "doc",
        }
        self.$modal.confirm('是否确认发布？').then(()=> {
          addDiscussions(data).then(res => {
            this.discussionContent = null
            self.$message({
              message: '发布成功',//提示的信息
              type:'success',　　//类型是成功
              duration:1200,　　//显示时间, 毫秒。设为 0 则不会自动关闭，建议1200
            });
            self.getAttachmentList()
          }).catch(err =>{
            this.discussionContent = null
            console.error("handleDiscussions==err==", err)
            self.$modal.msgError("发布失败");
          });
        })
      },
      getAttachmentList() {
        let self = this
        this.$set(this.queryParams,'del',"0")
        this.$set(this.queryParams,'businessId',this.form.docId)
        listAttachment(this.queryParams).then(res => {
          self.attachmentList = res.rows;
          self.total = res.total;
          self.loading = false;
        });

      },
      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, '');
      },
      /** 第二级 **/
      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.getAttachmentList()
          }).catch(err =>{
            console.error("submitReplySon==err==", err)
            self.$modal.msgError("发布失败");
          });
        })

        // 清空回复内容并隐藏表单
        this.$set(parentItem.replyContentSon, repIndex, '');
        this.$set(parentItem.showReplyFormSon, repIndex, false);
      },
      /** 回复 **/
      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.getAttachmentList()
          }).catch(err =>{
            console.error("handleDiscussions==err==", err)
            self.$modal.msgError("发布失败");
          });
        })

        // 清空回复内容并隐藏表单
        this.replyContent[index] = '';
        this.showReplyForm[index] = 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;
      },
      handlePreview(row){
        this.isPreviewDisable = true
        this.$nextTick(() => {
          this.$refs.previewForm.frontModulePreview(row)
        })
      },
      /** 关闭预览 **/
      previewClose(){
        this.isPreviewDisable = false
      },
      /**
       * 处理下载
       * **/
      handleDownload(row){
        let self = this
        self.loadingDownload = true
        this.$download.resource(row.fileUrl);

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

        setTimeout(()=>{
          self.loadingDownload = false
        },1000)
      },
      handleDelete(row){
        const index = this.attachmentList.findIndex(item => item.fileNewName == row.fileNewName);
        if (index !== -1) {
          // 从 attachmentList 中删除数据
          this.attachmentList.splice(index, 1);
          // 处理当前页面可能没有数据的情况，跳到上一页
          if (this.paginatedData.length === 0 && this.currentPage > 1) {
            this.currentPage--;
          }
        }
        // this.attachmentList.splice(row,1)
      },
      handleBeforeClose() {
        this.viewDialogOpen = false
      },
      handleUploadSuccess(res) {
        this.attachmentList.push(res)
        // 处理上传成功后的逻辑
      },
      handleUploadError(error) {
        // 处理上传失败后的逻辑
      },
      isShowOperation(row){
        let self = this
        if(row.businessId == null || row.businessId == undefined || row.businessId == ''){
          return false
        }
        return true
      },
      submitPeople(peopleList){
        this.$set(this.form,'docPrincipals',peopleList[0]['userId'])
        this.$set(this.form,'docPrincipalsName',peopleList[0]['nickName'])
        this.toolPrincipalsChoose = false;
      },
      setAllRequiredTrue(value) {
        Object.keys(this.rules).forEach(key => {
          this.rules[key].forEach(rule => {
            rule.required = value;
          });
        });
      },
      handlePageChange(newPage) {
        this.currentPage = newPage;
      },
      // 递归查找方法
      findLabelById(treeData, id) {
        for (let i = 0; i < treeData.length; i++) {
          let item = treeData[i];
          if (item.id == id) {
            return item.label;
          }
          if (item.children && item.children.length) {
            const label = this.findLabelById(item.children, id);
            if (label) {
              return label;
            }
          }
        }
        return null;
      }

    }
  }
</script>

<style scoped>

</style>
