<template>
  <div class="fbox1">
    <div class="fl">
      <div class="el-form-border">
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="文件分类" prop="docCategoryId">
                <treeselect v-model="form.docCategoryId" :options="docCategory" :show-count="true"
                            :disabled="detailBoolean"
                            placeholder="请选择文件分类"/>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="文档编号" prop="docCode">
                <template v-if="detailBoolean">{{form.docCode}}</template>
                <template v-else>
                  <el-input v-model="form.docCode" placeholder="请输入文档编号" maxlength="50" show-word-limit/>
                </template>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="文档名称" prop="docName">
                <template v-if="detailBoolean">{{form.docCode}}</template>
                <template v-else>
                  <el-input v-model="form.docName" placeholder="请输入文档名称" maxlength="200" show-word-limit/>
                </template>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="文档类别" prop="docType" style="width: 100%">
                <el-select v-model="form.docType" placeholder="请选择文档来源" style="width: 100% !important;"
                :disabled="detailBoolean">
                  <el-option style="width: 100%"
                    v-for="dict in dict.type.doc_class"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="文档来源" prop="docSource">
                <el-select v-model="form.docSource" placeholder="请选择文档来源" style="width: 100%" :disabled="detailBoolean">
                  <el-option
                    v-for="dict in dict.type.doc_source"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
    <!--            <el-input v-model="form.docSource" placeholder="请输入文档来源" maxlength="50" show-word-limit/>-->
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="relatedTool">
              <el-form-item label="关联工具" prop="toolId">
                <el-select
                  v-model="toolDataInfo"
                  ref="selectHeadTool"
                  multiple
                  value-key="toolId"
                  filterable
                  remote
                  placeholder="请选择关联工具"
                  :disabled="detailBoolean"
                  @focus="toolSelect">
                  <el-option
                    v-for="item in toolDataInfo"
                    :key="item.toolId"
                    :label="item.toolName"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>

            </el-col>
            <el-col :span="24">
              <el-form-item label="负责人" prop="docPrincipals">
                <template v-if="detailBoolean">{{form.docPrincipals}}</template>
                <template v-else>
                  <el-input v-model="form.docPrincipals" placeholder="请输入负责人" maxlength="50" show-word-limit/>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="归属单位" prop="docRespDept">
                <treeselect v-model="form.docRespDept" :options="deptOptions" :show-count="true"
                            :disabled="detailBoolean" placeholder="请输入归属单位"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="文件" required>
                <uploadVue
                  :display="editStatus"
                  :uploadUrl="uploadFileUrl"
                  :type="['.txt','.doc','.docx','.pdf','.mp4','.zip','.rar','.7z','.png','.jpg','.jpeg']"
                  :acceptType="acceptType"
                  :limit="1"
                  :dataFile="dataFile"
                  :isDetail="detailBoolean"
                  ref="uploadFile"
                  @handleSuccess="handleUploadSuccess"
                  @handleError="handleUploadError"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <template v-if="detailBoolean">{{form.remark}}</template>
                <template v-else>
                  <el-input v-model="form.remark" type="textarea" :rows="3" maxlength="500" show-word-limit></el-input>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form><!--el-form-->
      </div>
    </div><!--fl 左侧页签-->

    <div class="fr" v-if="detailBoolean">
      <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>
    <tool-selector ref="toolSelect" @selectHandle="selectHandle"></tool-selector>

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

<script>
  import { addDocument, updateDocument, getDocument } from "@/api/document/document";
  import axios from 'axios';
  import { getToken } from '@/utils/auth'
  import { deptTreeSelect } from "@/api/system/user";
  import { documentTree } from "@/api/documentCategory/documentCategory.js";
  import Treeselect from "@riophae/vue-treeselect";
  import uploadProgress from "./uploadProgress";
  import uploadVue from '@/components/FileUpload/optimizeUpload.vue'
  import ToolSelector from '@/components/tool-selector/index.vue'
  import { listDiscussions, addDiscussions } from "@/api/tool/discussions.js";
  import { listReplies, addReplies} from "@/api/tool/replies.js";

  export default {
    name: 'editDocument',
    components: { Treeselect, uploadProgress, uploadVue, ToolSelector},
    dicts:['doc_class','doc_source'],
    props: {
      tooId: {
        type: String,
        default: "",
        required: false
      },
      relatedTool: {
        type: Boolean,
        default: true,
      },
    },
    data(){
      return{
        templateSelection: '',
        drawer1: false,
        checkList: [],
        tableData2: [
          {
            prop1: 'GDL-987',
            prop2: 'GDL工具',
            prop3: '检测型 ',
            prop4: '研发部门',
            prop5: '韩健'
          },
          {
            prop1: 'GDL-988',
            prop2: 'GDL工具',
            prop3: '检测型 ',
            prop4: '研发部门',
            prop5: '韩健'
          }
        ],
        // 表单参数
        form: {
          docId: undefined,
          docCategoryId: undefined,
          docCode: '',
          docName: '',
          docType: '',
          docPrincipals: '',
          docRespDept: undefined,
          docSource: '',
          toolId: '',
          remark: undefined
        },
        fileList: [],
        progress: 0,
        // 表单校验
        rules: {
          docCategoryId: [
            { required: true, message: "文档分类不能为空", trigger: "blur" }
          ],
          docCode: [
            { required: true, message: "文档编号不能为空", trigger: "blur" }
          ],
          docName: [
            { required: true, message: "文档名称不能为空", trigger: "blur" }
          ],
          docType: [
            { required: true, message: "类别不能为空", trigger: "blur" }
          ],
          docSource: [
            { required: true, message: "文档来源不能为空", trigger: "blur" }
          ]
        },
        docCategory:[],
        deptOptions:[],
        uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
        fileData: null,
        acceptType: ".txt,.doc,.docx,.pdf,.mp4,.zip,.rar,.7z,.png,.jpg,.jpeg",
        editStatus: true,
        toolDataInfo: [],
        dataFile: [],
        //详情
        detailBoolean: false,

        discussionContent: null, // 评论内容
        repliesContent: null, // 回复内容
        // 评论列表
        discussionsList: [],
        // 回复列表
        repliesList: [],
        showReplyForm: [],
        replyContent: [],
        detailLoading: false,
      }
    },
    created(){
      this.getDeptTree();
      this.getDocumentTree();
    },
    mounted(){
     /* this.$nextTick(() => {
        document.querySelector('.el-upload__input').webkitdirectory = true
      })*/
    },
    methods:{
      chooseToolConfirm(){
        this.$set(this.form, "toolId", this.templateSelection)
        this.drawer1 = false;
      },
      singleElection(row) {
        this.templateSelection = row.prop1
        this.checkList = this.tableData2.filter((item) => item.prop1 === row.prop1)
        console.log(`该行的编号为${row.prop1}`)
      },
      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;
      },
      /** 提交按钮 */
      submitForm: function() {
        let fileName = []
        //编辑时走该逻辑
        if(this.form.docId && (this.fileList == null || this.fileList.length <= 0 )){
          fileName = this.$refs.uploadFile.fileList[0]
          this.fileList = this.$refs.uploadFile.fileList
        }else{
          fileName = this.fileList[0]
          this.fileList = this.fileList
        }
        //判断是否有文件再上传
        if (this.fileList.length == 0) {
          return this.$message.warning('请选取文件后再上传')
        }
        /*this.fileList.map(file =>{
          this.form.docName = file.name
        })*/
        if(fileName){
          this.$set(this.form,"docUrl", fileName.filePath)
          this.$set(this.form,"docStatus", "ysc")
          this.$set(this.form,"attachment", fileName)
        }
        if(this.toolDataInfo && this.toolDataInfo.length > 0){
          this.$set(this.form,"toolId", this.toolDataInfo[0].toolId)
        }

        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.docId) {
              updateDocument(this.form).then(res => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.$emit("submit");
              });
            } else {
              addDocument(this.form).then(res => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                // this.confirmSubmit(response.data);
                this.$emit("submit");
              });
            }
          }
        });
      },
      /** 提交按钮 */
      assembleSubmit: function() {
        let self = this
        let fileName = []
        //编辑时走该逻辑
        if(this.form.docId && (this.fileList == null || this.fileList.length <= 0 )){
          fileName = this.$refs.uploadFile.fileList[0]
          this.fileList = this.$refs.uploadFile.fileList
        }else{
          fileName = this.fileList[0]
        }
        //判断是否有文件再上传
        if (this.fileList.length == 0) {
          return this.$message.warning('请选取文件后再上传')
        }
        /*this.fileList.map(file =>{
          this.form.docName = file.name
        })*/
        if(fileName){
          this.$set(this.form,"docUrl", fileName.filePath)
          this.$set(this.form,"docStatus", "ysc")
          this.$set(this.form,"attachment", fileName)
        }
        if(this.toolDataInfo && this.toolDataInfo.length > 0){
          this.$set(this.form,"toolId", this.toolDataInfo[0].toolId)
        }

        this.$refs["form"].validate(valid => {
          if (valid) {
            self.$emit("docSubmitData",self.form)
          }
        });
      },
      /** 查询部门下拉树结构 */
      getDeptTree() {
        deptTreeSelect().then(response => {
          this.deptOptions = response.data;
        });
      },
      /** 查询树形下拉树结构 */
      getDocumentTree() {
        documentTree().then(response => {
          this.docCategory = response.data;
        });
      },
      /** 转换部门数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children
        };
      },
      // flag 为true表示新增
      getData(data, flag, index) {
      },
      getError(message) {
        this.$message.error(message);
      },
      handleUploadSuccess(res) {
        this.fileList = []
        this.fileList.push(res)
        // 处理上传成功后的逻辑
      },
      handleUploadError(error) {
        // 处理上传失败后的逻辑
      },
      toolSelect(){
        this.$refs.selectHeadTool.blur();
        this.$nextTick(()=>{
          this.$refs.toolSelect.init(null,null,false)
        })
      },
      selectHandle(source,index,data){
        this.toolDataInfo = []
        let toolInfo = {toolId:data.toolId,toolCode:data.toolCode,toolName:data.toolName}
        this.toolDataInfo.push(toolInfo)
      },
      /**初始化 **/
      resetForm() {
        this.$refs.form.resetFields();
        this.toolDataInfo = []
        this.fileList = []
        this.detailBoolean = false
        this.$nextTick(()=>{
          this.$refs.uploadFile.clearFile();
        })
      },
      editInit(docId, type){
        let self = this
        if(type == "detail"){
          this.detailBoolean = true
        }
        self.$refs.form.resetFields();
        self.toolDataInfo = []
        self.$nextTick(()=>{
          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.getDiscussionsList()
          });
        })
      },
      /** 评论 **/
      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.getDiscussionsList()
          }).catch(err =>{
            this.discussionContent = null
            console.error("handleDiscussions==err==", err)
            self.$modal.msgError("发布失败");
          });
        })
      },
      getDiscussionsList() {
        let self = this
        listDiscussions({businessId:this.form.docId}).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', '')
            }
          });
        });
      },
      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.getDiscussionsList()
          }).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.getDiscussionsList()
          }).catch(err =>{
            console.error("handleDiscussions==err==", err)
            self.$modal.msgError("发布失败");
          });
        })

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

<style scoped>

</style>
