 <!--leixiaoyan 知识库新增、编辑-->
<template>
  <div class="knowledgeFrom">
    <dialog-edit :visible.sync="dialogVisible"
                 :autoSave="false"
                 :autoClose="false"
                 :editModel="editModel"
                 :api="api"
                 :form="submitForm"
                 width="1200px"
                 :title="titleData()"
                 :saveLabel="$t('common.submit')"
                 :footerBtnShow="false">
    <div class="titleLine">
      {{titleData()}}
      <span class="line"></span></div>
    <el-form ref="submitForm" :disabled="viewMode" :rules="rules" :model="submitForm">
      <dym-form :componentList="componentList"
                :formValue.sync="submitForm"
                @selectChanged="selectChanged"></dym-form>
    </el-form>
      <template slot="footer">
        <auth-button v-if="!viewMode" :label="$t('feedbackMaterialIndex.check')" type="primary" size="medium" @click="fCnki"></auth-button>
        <auth-button v-if="!viewMode" :label="$t('common.save')" type="primary" size="medium" @click="onSave"></auth-button>
        <auth-button :label="$t('feedbackMaterialIndex.temporaryStorage')"
                     type="primary"
                     size="medium"
                     @click="fTemporaryStorage"
                     v-if="(editModel === 'C' || (editModel === 'E' && voltooideStatus === '1')) && !viewMode"></auth-button>
        <auth-button :label="$t('common.close')" size="medium" @click="fClose"></auth-button>
      </template>
    </dialog-edit>
    <!-- 查重 -->
    <cnki :cnkiData="cnkiData"></cnki>
  </div>
</template>

<script>
import BaseEdit from '@/pages/baseEditPage'
import { DialogEdit, DataTable, SelectDictionary, authButton, dymForm } from 'newepoch-components'
import knowledgeBaseApi from '@/api/assetaudit/knowledgeBaseApi'
import SelectApplicableProject from '@/components/element/assetaudit/SelectApplicableProject'
import SelectFileName from '@/components/element/assetaudit/SelectFileNameZsk'
import ProblemTypeInput from '@/components/element/assetaudit/ProblemTypeInput'
import ProblemPointInput from '@/components/element/assetaudit/ProblemPointInput'
import * as format from '@/filters/index'
import mixin from '@/pages/mixin'
import cnki from '@/components/element/assetaudit/cnki'
export default {
  extends: new BaseEdit(),
  mixins: [mixin],
  name: 'knowledgeBasePop',
  components: {
    DialogEdit,
    DataTable,
    SelectApplicableProject,
    SelectDictionary,
    authButton,
    SelectFileName,
    ProblemTypeInput,
    ProblemPointInput,
    dymForm,
    cnki
  },
  props: {
    viewMode: { // 新增查看模式，为true禁止修改，为false可以修改
      type: Boolean,
      default: false
    },
    autoSave: {
      type: [Boolean],
      default: false
    },
    options: {
      type: [Array],
      default () {
        return []
      }
    },
    keyId: {
      type: [String],
      default () {
        return ''
      }
    },
    editModel: {
      type: [String],
      default () {
        return 'E'
      }
    }
  },
  data () {
    return {
      appendToBody: false,
      toolMenuFlag: true,
      loadCount: 0,
      menuFlag: false,
      operateBtnLayout: '',
      loadingFlag: false, // 加载动画控件
      queryParas: {},
      fileName: '', // 文件名称
      applicableProjectName: '', // 适用产品名
      applicableProjectDTO: [], // 适用产品key-value
      submitData: {},
      oldForm: {},
      componentList: [
        {
          // 文件类型
          label: this.$t('knowledgeBaseIndex.fileType'),
          disabled: false,
          value: 'fileType',
          prop: 'fileType',
          placeholder: this.$t('common.pleaseSelect'),
          labelWidth: '100px',
          cols: [8, 8, 8],
          componentName: SelectDictionary,
          dictTypeCode: 'HG_FILE_TYPE'
        },
        {
          // 文件名称
          label: this.$t('knowledgeBaseIndex.fileName'),
          disabled: false,
          multiple: true,
          filterable: true,
          value: 'fileName',
          prop: 'fileName',
          name: 'fileName',
          placeholder: this.$t('common.pleaseSelect'),
          labelWidth: '100px',
          cols: [8, 8, 8],
          componentName: SelectFileName,
          attrs: { // 注意使用的组件要设置 :multiplelimit="multiplelimit"
            multiplelimit: 10
          }
        },
        {
          // 问题类型
          label: this.$t('knowledgeBaseIndex.problemType'),
          disabled: false,
          value: 'problemType',
          prop: 'problemType',
          placeholder: this.$t('common.pleaseInput'),
          labelWidth: '100px',
          maxlength: 12, // 根据磨刀50/4
          cols: [8, 8, 8],
          componentName: ProblemTypeInput
        },
        {
          // 问题点
          label: this.$t('knowledgeBaseIndex.problemPoint'),
          disabled: false,
          value: 'problemPoint',
          prop: 'problemPoint',
          placeholder: this.$t('common.pleaseInput'),
          maxlength: 25, // 根据磨刀100/4
          labelWidth: '100px',
          cols: [8, 8, 8],
          componentName: ProblemPointInput
        },
        {
          // 适用产品
          label: this.$t('knowledgeBaseIndex.production'),
          disabled: false,
          multiple: true,
          value: 'applicableProject',
          prop: 'applicableProject',
          placeholder: this.$t('common.pleaseSelect'),
          labelWidth: '100px',
          name: 'applicableProject',
          cols: [8, 8, 8],
          componentName: SelectApplicableProject
        },
        {
          // 解决方式
          label: this.$t('knowledgeBaseIndex.solution'),
          disabled: false,
          value: 'solution',
          prop: 'solution',
          placeholder: this.$t('common.pleaseInput'),
          maxlength: 500,
          labelWidth: '100px',
          cols: [24, 24, 24],
          componentName: 'el-input',
          rows: 5,
          type: 'textarea'
        }
      ],
      submitForm: { fileType: '', fileName: [], problemType: '', problemPoint: '', applicableProject: [], solution: '' },
      rules: {
        fileType: [
          { required: true, message: this.$t('common.pleaseSelect') + this.$t('feedbackMaterialIndex.fileType'), trigger: ['blue', 'change'] }
        ],
        fileName: [
          { required: true, message: this.$t('common.pleaseSelect') + this.$t('feedbackMaterialIndex.fileName'), trigger: ['blue', 'change'] }
        ],
        problemType: [
          { required: true, message: this.$t('common.pleaseInput') + this.$t('feedbackMaterialIndex.problemType'), trigger: ['blue', 'change'] }
        ],
        problemPoint: [
          { required: true, message: this.$t('common.pleaseInput') + this.$t('feedbackMaterialIndex.problemPoint'), trigger: ['blue', 'change'] }
        ],
        applicableProject: [
          { required: true, message: this.$t('common.pleaseSelect') + this.$t('feedbackMaterialIndex.applicableProject'), trigger: ['blue', 'change'] }
        ],
        solution: [
          { required: true, message: this.$t('common.pleaseInput') + this.$t('feedbackMaterialIndex.solution'), trigger: ['blue', 'change'] }
        ]
      },
      cnkiData: {
        dialogVisible: false,
        fromData: {}, // 表单数据
        showSave: false
      },
      voltooideStatus: '',
      correlationStatus: ''
    }
  },
  mounted () {
    this.loadData()
    this.handleFilter()
    // this.formValidation()
  },
  computed: {
    api () {
      return knowledgeBaseApi.knowledgeBase
    },
    apiOperate () {
      return knowledgeBaseApi.knowledgeBaseList
    }
  },
  methods: {
    // 清除表单验证
    formValidation () {
      // setTimeout(() => {
      this.$nextTick(() => {
        this.$refs.submitForm.clearValidate()
      })
      // }, 5000)
    },
    // 判断title值
    titleData () {
      if (this.editModel === 'E' && this.viewMode) {
        return this.$t('knowledgeBaseIndex.knowledgeBaseView')
      } else if (this.editModel === 'E' && !this.viewMode) {
        return this.$t('knowledgeBaseIndex.knowledgeBaseEdit')
      } else if (this.editModel === 'C') {
        return this.$t('knowledgeBaseIndex.knowledgeBaseAdd')
      }
    },
    // 表单选择 存值
    selectChanged (data) {
      // 拼接适用产品
      if (data.applicableProjectInfo) {
        this.applicableProjectDTO = data.applicableProjectInfo.map(item => {
          return { 'applicableProject': item.projectName, 'applicableProjectId': item.keyId }
        })
        this.applicableProjectName = data.applicableProjectInfo.map(item => item.projectName).join(',')
      }
      // 拼接选择文件名称
      if (data.fileNameInfo) {
        this.fileName = data.fileNameInfo.map(item => item.fileName).join(',')
      }
    },
    // 获取文件类型字符串
    getFileDict (type) {
      return type === '01'
        ? this.$t('knowledgeBaseIndex.oneFile')
        : this.$t('knowledgeBaseIndex.moreFile')
    },
    // 详情
    loadData () {
      if (this.editModel === 'E') {
        this.api.get(this.keyId).then(res => {
          let data = res.data
          // 是否显示重置按钮
          this.voltooideStatus = data.voltooideStatus
          this.fileName = data.fileName
          // 是否被关联
          this.correlationStatus = data.correlationStatus
          this.applicableProjectName = data.applicableProject
          this.oldForm.knowledgeMgrXmExtPostDTO = data.knowledgeMgrXmExtDTO.map(item => {
            return { 'applicableProject': item.applicableProject, 'applicableProjectId': item.applicableProjectId }
          })
          Object.assign(this.oldForm, data)
          // 编辑赋值
          this.submitForm = {
            fileType: data.fileType,
            fileName: data.fileId ? data.fileId.split(',') : '',
            problemType: data.problemType,
            problemPoint: data.problemPoint,
            solution: data.solution,
            applicableProject: data.knowledgeMgrXmExtDTO.map(item => item.applicableProjectId === '0' ? '' : item.applicableProjectId)
          }
          this.formValidation() // 清空表单验证，防止进入表单验证以后显示红色
        })
      }
    },
    // 新增表单信息
    saveData () {
      this.submitData = {
        // applicableProject: this.applicableProjectName,
        fileId: this.submitForm.fileName ? this.submitForm.fileName.join(',') : '',
        fileName: this.fileName,
        fileType: this.submitForm.fileType,
        knowledgeMgrXmExtPostDTO: this.applicableProjectDTO.length > 0 ? this.applicableProjectDTO : [],
        problemType: this.submitForm.problemType.trim(),
        problemPoint: this.submitForm.problemPoint.trim(),
        solution: this.submitForm.solution.trim(),
        fileDic: this.getFileDict(this.submitForm.fileType)
      }
      return this.submitData
    },
    // 编辑时新旧值比较
    oldEquals (oldValue, newValue) {
      let oldApplicableProjectId = oldValue.knowledgeMgrXmExtPostDTO.map(item => item.applicableProjectId === '0' ? '' : item.applicableProjectId).sort().toString()
      let newApplicableProjectId = newValue.knowledgeMgrXmExtPostDTO.map(item => item.applicableProjectId === '0' ? '' : item.applicableProjectId).sort().toString()
      let oldFileName = oldValue.fileName
      let newFileName = newValue.fileName
      if (oldValue.fileId === newValue.fileId && oldApplicableProjectId === newApplicableProjectId && oldFileName === newFileName &&
          oldValue.fileType === newValue.fileType &&
          oldValue.problemPoint === newValue.problemPoint &&
          oldValue.problemType === newValue.problemType &&
          oldValue.solution === newValue.solution) {
        return false
      } else {
        return true
      }
    },
    // 新增 保存  函数
    fCreate () {
      if (this.submitForm.fileType === '01' && this.submitForm.fileName.length > 1) {
        this.warning(this.$t('knowledgeBaseIndex.oneSelect'))
        return
      }
      if (this.submitForm.fileType === '02' && this.submitForm.fileName.length < 2) {
        this.warning(this.$t('knowledgeBaseIndex.moreSelect'))
        return
      }
      this.$LoadingShow()
      knowledgeBaseApi.knowledgeBaseCreate.create(this.saveData()).then(res => {
        this.$LoadingClose()
        if (res && res.success && res.data) {
          this.$emit('operateBtnClick', true)
          this.$refs.submitForm.clearValidate()
          this.$refs.submitForm.resetFields()
          this.dialogVisible = false
          this.success(this.$t('documentSealingConfig.addseccessinfo'))
        } else if (!res.data) {
          this.warning(this.$t('knowledgeBaseIndex.existenceData'))
        } else {
          this.error(this.$t('documentSealingConfig.addfialinfo'))
        }
      })
    },
    // 编辑 保存 函数
    fEdit (voltooideStatus) {
      let saveObj = this.saveData()
      if (this.submitForm.fileType === '01' && this.submitForm.fileName.length > 1) {
        this.warning(this.$t('knowledgeBaseIndex.oneSelect'))
        return
      }
      if (this.submitForm.fileType === '02' && this.submitForm.fileName.length < 2) {
        this.warning(this.$t('knowledgeBaseIndex.moreSelect'))
        return
      }
      saveObj.voltooideStatus = voltooideStatus
      // 修改的 时候 适用产品值未变传null
      let oldApplicableProject = this.oldForm.knowledgeMgrXmExtPostDTO.map(item => item.applicableProjectId === '0' ? '' : item.applicableProjectId).sort().toString()
      let newApplicableProject = saveObj.knowledgeMgrXmExtPostDTO.map(item => item.applicableProjectId === '0' ? '' : item.applicableProjectId).sort().toString()
      if (oldApplicableProject === newApplicableProject) {
        saveObj.knowledgeMgrXmExtPostDTO = null
      }
      if (saveObj.knowledgeMgrXmExtPostDTO && saveObj.knowledgeMgrXmExtPostDTO.length === 0 && !this.temporary) { // 当saveObj.knowledgeMgrXmExtPostDTO为空数组，修改为null，并且不是暂存状态
        saveObj.knowledgeMgrXmExtPostDTO = null
      }
      this.$LoadingShow()
      this.api.update(this.keyId, saveObj).then(res => {
        this.$LoadingClose()
        if (res && res.success && res.data) {
          this.$emit('operateBtnClick', true)
          this.$refs.submitForm.clearValidate()
          this.$refs.submitForm.resetFields()
          this.dialogVisible = false
          voltooideStatus === '0'
            ? this.success(this.$t('ladingNoticeManage.ModifyFaile'))
            : this.success(this.$t('knowledgeBaseIndex.temporarySuccess'))
        } else {
          voltooideStatus === '0'
            ? this.error(this.$t('paymentConfirmationManage.editError'))
            : this.error(this.$t('knowledgeBaseIndex.temporaryError'))
        }
      })
    },
    // 保存函数
    onSave () {
      let flag = false
      this.$refs.submitForm.validate((valid) => { flag = valid })

      if (this.editModel === 'E' && this.correlationStatus === '1' && !this.oldEquals(this.oldForm, this.saveData())) {
        this.warning(this.$t('knowledgeBaseIndex.noChange'))
        return
      }

      if (this.editModel === 'C' && flag) {
        this.fCreate()
      } else if (this.editModel === 'E' && flag) {
        this.fEdit('0')
      }
    },
    // 暂存 btn ------------
    fTemporaryStorage () {
      this.temporary = true // 存入暂存值标签
      // let flag = false
      let flag = true // 暂存不验证表单
      // this.$refs.submitForm.validate((valid) => { flag = valid }) // 表单验证
      let tempData = this.saveData() // 判断是否一个数据都没有
      if (!tempData.fileType && !tempData.fileId && !tempData.problemType && !tempData.problemPoint && tempData.knowledgeMgrXmExtPostDTO.length === 0 && !tempData.solution) {
        this.warning(this.$t('knowledgeBaseIndex.emptyPrompt'))
        return
      }

      if (this.editModel === 'E' && this.correlationStatus === '1' && !this.oldEquals(this.oldForm, this.saveData())) {
        this.warning(this.$t('knowledgeBaseIndex.noChange'))
        return
      }

      if (this.editModel === 'C' && flag) {
        this.fTemporarySave()
      } else if (this.editModel === 'E' && flag) {
        this.fEdit('1')
      }
    },
    // 暂存发请求
    fTemporarySave () {
      if (this.submitForm.fileType === '01' && this.submitForm.fileName.length > 1) {
        this.warning(this.$t('knowledgeBaseIndex.oneSelect'))
        return
      }
      if (this.submitForm.fileType === '02' && this.submitForm.fileName.length < 2) {
        this.warning(this.$t('knowledgeBaseIndex.moreSelect'))
        return
      }
      this.$LoadingShow()
      this.apiOperate.save(this.saveData()).then(res => {
        this.$LoadingClose()
        if (res && res.success && res.data) {
          this.$emit('operateBtnClick', true)
          this.submitForm = {}
          this.dialogVisible = false
          this.success(this.$t('knowledgeBaseIndex.temporarySuccess'))
        } else if (!res.data) {
          this.warning(this.$t('knowledgeBaseIndex.existenceData'))
        } else {
          this.error(this.$t('knowledgeBaseIndex.temporaryError'))
        }
      })
    },
    // 查重btn
    fCnki () {
      if (this.submitForm.fileType === '01' && this.submitForm.fileName.length > 1) {
        this.warning(this.$t('knowledgeBaseIndex.oneSelect'))
        return
      }
      if (this.submitForm.fileType === '02' && this.submitForm.fileName.length < 2) {
        this.warning(this.$t('knowledgeBaseIndex.moreSelect'))
        return
      }
      this.$LoadingShow()
      this.$refs['submitForm'].validate((valid) => {
        this.$LoadingClose()
        if (valid) {
          this.cnkiData.fromData = {
            fileTypeStr: format.formatDict(this.submitForm.fileType, 'HG_FILE_TYPE'),
            fileId: this.submitForm.fileName.join(','),
            fileNameStr: this.fileName,
            showSave: false
          }
          Object.assign(this.cnkiData.fromData, this.submitForm)
          this.cnkiData.dialogVisible = true
        }
      })
    },
    // 关闭弹窗
    fClose () {
      this.$refs.submitForm.clearValidate()
      this.$refs.submitForm.resetFields()
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.knowledgeFrom{
  >>> .el-tag.el-tag--info{
    max-width: 180px;
  }
}
</style>
