<template>
  <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" placeholder="请选择文件分类"/>
          </el-form-item>
        </el-col>

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

        <el-col :span="24">
          <el-form-item label="文档名称" prop="docName">
            <el-input v-model="form.docName" placeholder="请输入文档名称" maxlength="200" show-word-limit/>
          </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;">
              <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%">
              <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="请选择关联工具"
              @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">
            <el-input v-model="form.docPrincipals" placeholder="请输入负责人" maxlength="50" show-word-limit/>
          </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" 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"
              ref="uploadFile"
              @handleSuccess="handleUploadSuccess"
              @handleError="handleUploadError"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" :rows="3" maxlength="500" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form><!--el-form-->

    <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'

  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: [],
      }
    },
    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.$nextTick(()=>{
          this.$refs.uploadFile.clearFile();
        })
      },
      editInit(docId, type){
        this.$refs.form.resetFields();
        this.toolDataInfo = []
        this.$nextTick(()=>{
          this.$refs.uploadFile.clearFile();

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

            this.dataFile = []
            let fileData = res.data.attachment
            this.$set(fileData, "name", fileData.fileOldName)
            this.$set(fileData, "size", fileData.fileSize)
            this.dataFile.push(fileData)
          });
        })
      }
    }
  }
</script>

<style scoped>

</style>
