<template>
  <div class="repositoey-item">
    <el-tabs v-model="activeName"  @tab-click="handleTabs">
      <el-tab-pane name="1" v-if="showPane">
        <span slot="label">
          <el-radio v-model="radio" label="1" >{{$t('knowledgeBaseIndex.selectknowledgeBase')}}</el-radio>
        </span>
        <div style="display:flex; width:100%;align-items: center;padding:0 10px;" v-if="pageType !== 'V'">
          <div style="font-size:14px; color:#666;padding-left:10px;flex-shrink: 0;"> {{$t('knowledgeBaseIndex.keyWord')}}</div>
          <yf-es-search class="yfesSearch-item"
                        style="flex:1; align-items: center"
                        ref="yfEsSearchItem"
                        @callbackFunc="updata"
                        v-bind="yfEsSearchData"
                        :btnAttrs="btnAttrs"
                        :shouldBefore="true"
                        :beforeLoad="beforeLoad"></yf-es-search>
          <el-button type="primary"
                     size="medium"
                     @click="isAddShow()">
            <span class="icon iconfont">&#xe6e1;</span> {{$t('knowledgeBaseIndex.advancedSearch')}}</el-button>
          <el-button size="medium"
                     @click="resetSearch">
            <span class="icon iconfont">&#xe63d;</span> {{$t('common.reset')}}</el-button>
        </div>
        <div style="padding:10px;">
          <el-table v-loading="vLoading"
                    :element-loading-text="$t('knowledgeBaseIndex.underHeavyLoad')"
                    element-loading-spinner="el-icon-loading"
                    element-loading-background="rgba(255, 255, 255, 1)"
                    header-cell-class-name="common-table-header"
                    :data="tableFormData"
                    border
                    max-height="347"
                    class="reposit-table"
                    style="width: 100%">
            <el-table-column width="50">
              <!-- 单选标签 -->
              <template slot-scope="scope">
                  <el-radio class="radio" v-model="radioCheck" :label="scope.row.keyId" style="padding-left:7px;" @change="handleTable(scope.row)">&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column prop="fileType" align="center" show-overflow-tooltip :formatter="filterFileType"  :label="$t('knowledgeBaseIndex.fileType')"></el-table-column>
            <el-table-column prop="fileName" show-overflow-tooltip :label="$t('knowledgeBaseIndex.fileName')"></el-table-column>
            <el-table-column prop="problemType" show-overflow-tooltip :label="$t('knowledgeBaseIndex.problemType')"></el-table-column>
            <el-table-column prop="problemPoint" show-overflow-tooltip :label="$t('knowledgeBaseIndex.problemPoint')"></el-table-column>
            <el-table-column prop="solution" show-overflow-tooltip :label="$t('knowledgeBaseIndex.solution')"></el-table-column>
            <el-table-column prop="applicableProjectName" show-overflow-tooltip :label="$t('knowledgeBaseIndex.production')"></el-table-column>
            <el-table-column fixed="right" :label="$t('common.operate')" width="100" align="center" v-if="showBtn">
              <template slot-scope="scope">
                <auth-button size="small"
                             class="iconCircle marginLeft"
                             icon="iconfont iconlvli"
                             :title="$t('knowledgeBaseIndex.feedback')"
                             @click="showEdit(scope.row.keyId, 'P')"></auth-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="text-align: right;margin-top:10px;" v-if="typeSearch === 'P'">
            <!-- 暂存数据页码 -->
            <el-pagination @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="yfEsSearchData.pageConfig.pageIndex"
                           :page-sizes="[10, 20, 30, 40]"
                           :page-size="yfEsSearchData.pageConfig.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="yfEsSearchData.pageConfig.totalCount"></el-pagination>
          </div>
          <div style="text-align: right;margin-top:10px;" v-else>
            <!-- 高级搜索数据页码 -->
            <el-pagination @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="pageConfig.pageIndex"
                           :page-sizes="[10, 20, 30, 40]"
                           :page-size="pageConfig.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="pageConfig.totalCount"></el-pagination>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="2" v-if="showPanePz">
        <span slot="label">
          <el-radio v-model="radio" label="2">
            {{$t('knowledgeBaseIndex.customAnalysisContent')}}</el-radio> </span>
        <el-row>
        <el-form ref="submitForm" :model="submitForm" :rules="rules">
          <el-col :span="8">
            <el-form-item :label="$t('knowledgeBaseIndex.fileType')"
                          prop='fileType'
                          label-width="100px">
              <SelectDictionary name='fileType'
                                :disabled="currentDisabled"
                                v-model="submitForm.fileType"
                                dictTypeCode="HG_FILE_TYPE"></SelectDictionary>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('knowledgeBaseIndex.fileName')"
                          prop='fileName'
                          label-width="100px">
              <SelectFileName class="selectFile-item"
                              :disabled="currentDisabled"
                              :multiple="true"
                              name='fileName'
                              v-model="submitForm.fileName"
                              @selectChanged="selectChanged"></SelectFileName>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('knowledgeBaseIndex.problemType')"
                          prop='problemType'
                          label-width="100px">
              <el-autocomplete :maxlength="500"
                               :disabled="currentDisabled"
                               v-model="submitForm.problemType"
                               :fetch-suggestions="problemTypeAsync"
                               :placeholder="$t('knowledgeBaseIndex.inputContent')"></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('knowledgeBaseIndex.problemPoint')"
                          prop='problemPoint'
                          label-width="100px">
              <el-autocomplete :maxlength="500"
                               :disabled="currentDisabled"
                               v-model="submitForm.problemPoint"
                               :fetch-suggestions="problemPointAsync"
                               :placeholder="$t('knowledgeBaseIndex.inputContent')"></el-autocomplete>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item :label="$t('knowledgeBaseIndex.production')" prop='production' label-width="100px">
              <SelectApplicableProject
                class="selectFile-item"
                :disabled="currentDisabled"
                :multiple="true"
                name='production'
                v-model="submitForm.production"
                @selectChanged="selectChangedPdt"
              ></SelectApplicableProject>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item :label="$t('knowledgeBaseIndex.solution')" prop='solution' label-width="100px">
              <el-input :disabled="currentDisabled"
                        class="textareaRepository"
                        v-model="submitForm.solution"
                        :placeholder="$t('common.pleaseInput')"
                        :maxlength="500"
                        type="textarea"
                        style="width:100%;height:80px"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      </el-tab-pane>
  </el-tabs>
  <!-- 高级检索 -->
  <advanced-search ref="advancedForm"
                   :clickPosition='clickPosition'
                   @advSearchData='advSearchData'
                   :visible.sync="dialogFormVisible"
                   :disabled="currentDisabled"
                   :parameter="pageConfig"></advanced-search>
  <!-- 反馈意见 -->
  <create-feedback v-if="dialogFeedbackVisible"
                   :visible.sync="dialogFeedbackVisible"
                   :feedbackKeyId="feedbackKeyId"></create-feedback>
  </div>
</template>
<script>
import SelectApplicableProject from '@/components/element/assetaudit/SelectApplicableProject'
import SelectFileName from '@/components/element/assetaudit/SelectFileName'
import { SelectDictionary, yfEsSearch, authButton } from 'newepoch-components'
import knowledgeBaseApi from '@/api/assetaudit/knowledgeBaseApi'
import AdvancedSearch from '@/pages/assetaudit/cKnowledgeBase/advancedSearch'
import CreateFeedback from '@/pages/assetaudit/reviewMaterial/createFeedback'
import * as format from '@/filters/index'
export default {
  components: {
    SelectApplicableProject,
    SelectFileName,
    SelectDictionary,
    yfEsSearch,
    authButton,
    AdvancedSearch,
    CreateFeedback
  },
  props: {
    // 暂存或保存的table数据
    tableData: {
      type: [Array],
      default () {
        return []
        // return [{
        //  fileType: '01',
        //  fileName: ['1', '2'],
        //  problemType: '123',
        //  problemPoint: '123',
        //  solution: '123',
        //  analyseWay: '02'
        // }]

        // return [{
        //   analyseWay: '01',
        //   file_type: '2016-05-02',
        //   file_name: '王小虎',
        //   problem_type: '上海市普陀区金沙江路 1518 弄',
        //   problem_point: '上海市普陀区金沙江路 1518 弄',
        //   solution: '上海市普陀区金沙江路 1518 弄',
        //   applicable_project: '上海市普陀区金沙江路 1518 弄'
        // }]
      }
    },
    // 是否显示操作按钮
    showBtn: {
      type: Boolean,
      default () {
        return true
      }
    },
    // 页面状态 -- E 编辑 V 查看
    pageType: {
      type: String,
      default () {
        return 'E'
      }
    }
  },
  name: '',
  data () {
    return {
      btnAttrs: {
        size: 'medium'
      },
      dialogFormVisible: false,
      dialogFeedbackVisible: false,
      feedbackKeyId: '',
      clickPosition: '',
      loading: null,
      activeName: '1',
      radio: '1',
      fileNameStr: [],
      fileNameCode: [],
      radioCheck: '', // 单选行选中（获取的是keyid）
      vLoading: true,
      tableFormData: [], // 列表数据
      formTableData: null,
      showPane: true,
      showPanePz: true,
      analyse_way: '',
      typeSearch: 'P', // P关键词搜索，G高级搜索
      pageConfig: {
        pageIndex: 1,
        pageSize: 10,
        totalCount: 0
      },
      yfEsSearchData: { // 关键词检索
        // configUrl: 'http://es.cdyfsz.com',
        // module: 'ckb_knowledge_base',
        filterKeys: [{ name: 'field_group', modle: 'must' }],
        sortKeys: '',
        shouldBefore: true,
        pageConfig: {
          pageIndex: 1,
          pageSize: 10,
          totalCount: 0
        },
        autoSearch: false,
        placeholder: this.$i18n.messages[this.$i18n.locale].retrievalIndex.inputKeyWord,
        recommendKey: { name: 'field_group', modle: 'must' },
        defauleKeys: [
          { name: 'voltooide_status', type: 'term', value: '0' },
          { name: 'data_status', type: 'term', value: '01' },
          { name: 'del_status', type: 'term', value: '0' }
        ]
      },
      problemTypeData: [],
      submitForm: { keyId: '', fileType: '', fileName: [], problemType: '', problemPoint: '', solution: '' },
      rules: {
        fileType: [
          { required: true, message: '请选择文件类型', trigger: 'change' }
        ],
        fileName: [
          { required: true, message: '请选择文件名称', trigger: 'change' }
        ],
        problemType: [
          { required: true, message: '请选择问题类型', trigger: 'change' }
        ],
        problemPoint: [
          { required: true, message: '请选择问题点', trigger: 'change' }
        ],
        solution: [
          { required: true, message: '请填写解决方式' }
        ]
      }
    }
  },
  watch: {
    radio (val) {
      this.$emit('radio', this.radio)
    },
    // 监听table
    tableData (val) {
      if (val[0].analyseWay === '01') {
        this.activeName = '1'
        this.radio = '1'
        this.tableFormData = this.tableData
      }
    }
  },
  mounted () {
    this.checkForm()
    this.envSetFun()
  },
  computed: {
    currentDisabled () {
      if (this.pageType === 'V') {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    // 设置关键词环境变量
    envSetFun () {
      // this.yfEsSearchData.configUrl = process.env.VUE_APP_CONFIG_URL
      // this.yfEsSearchData.module = process.env.VUE_APP_KNOWLEDGE_BASE
      this.$set(this.yfEsSearchData, 'configUrl', process.env.VUE_APP_CONFIG_URL)
      this.$set(this.yfEsSearchData, 'module', process.env.VUE_APP_KNOWLEDGE_BASE)
    },
    selectChanged (data1, data2, data3) {
      this.fileNameStr = []
      this.fileNameCode = []
      if (data3.length > 0) {
        data3.forEach(item => {
          if (item) {
            this.fileNameStr.push(item.fileName)
            this.fileNameCode.push(item.fileCode)
          }
        })
      } else {
        this.fileNameStr = []
      }
    },
    // 清空搜索
    resetSearch () {
      this.$refs.yfEsSearchItem.$data.esValue = ''
    },
    // radio关联切换
    handleTabs (val, event) {
      this.radio = val.paneName
      // 清空自定义分析内容数据
      if (val.paneName === '2') {
        this.$refs['submitForm'].resetFields()
      } else {
        this.tableFormData = []
      }
      this.$nextTick(() => {
        if (val.paneName === '1') this.$refs.submitForm.clearValidate()
      })
    },
    // 传入的table值
    checkForm () {
      if (this.tableData.length === 0) {
        this.vLoading = false
        return
      }
      if (this.tableData[0].analyseWay === '01') {
        this.vLoading = false
        this.activeName = '1'
        this.radio = '1'
        if (this.tableData.length !== 0) {
          this.radioCheck = this.tableData[0].keyId
          this.yfEsSearchData.pageConfig.totalCount = 1
        }
        this.tableFormData = this.tableData
      } else if (this.tableData[0].analyseWay === '02') {
        this.vLoading = false
        this.activeName = '2'
        this.radio = '2'
        this.submitForm = this.tableData[0]
      } else {
        this.tableFormData = []
      }
      if (this.pageType === 'V') {
        if (this.tableData[0].analyseWay === '01') {
          this.showPanePz = false
          this.showPane = true
        } else {
          this.showPanePz = true
          this.showPane = false
        }
      }
    },
    // 第一次查询 数据加载
    beforeLoad (load) {
      this.yfEsSearchData.pageConfig.pageIndex = 1
      if (this.tableData.length !== 0 && this.tableData[0].analyseWay === '01') {
        this.radioCheck = this.tableData[0].knowledgeBaseId
      }
      load()
    },
    // 高级检索回调数据
    advSearchData (data) {
      this.vLoading = false
      this.typeSearch = 'G'
      data.data.total = data.data.totalRow
      this.pageConfig.pageIndex = data.data.pageIndex
      if (data.data.pageIndex === 1 && this.tableData.length !== 0 && this.tableData[0].analyseWay === '01') {
        this.radioCheck = this.tableData[0].knowledgeBaseId
      }
      this.cutData(data.data)
    },
    // 关键字查询
    updata (data) {
      // if (this.tableData > 0) {
      //   this.radioCheck = this.tableData[0].knowledgeBaseId
      // }
      this.vLoading = false
      this.typeSearch = 'P'
      this.cutData(data)
    },
    // 赋值函数
    cutData (data) {
      let sortData = data.datas.sort((a, b) => { // 按文件类型和文件名称排序
        if (a.file_type) a.file_type.localeCompare(b.file_type, 'zh')
      })
      sortData.sort((a, b) => {
        if (a.file_name) a.file_name.localeCompare(b.file_name, 'zh')
      })
      if (this.typeSearch === 'P') {
        this.yfEsSearchData.pageConfig.totalCount = data.total // 关键词总数
      } else {
        this.pageConfig.totalCount = data.total // 高级检索总数
      }
      this.tableFormData = []
      if (this.typeSearch === 'P') {
        if (this.tableData.length !== 0 && this.yfEsSearchData.pageConfig.pageIndex === 1 && this.tableData[0].analyseWay === '01') {
          this.tableFormData = sortData
        } else {
          this.tableFormData = sortData
        }
      } else {
        if (this.tableData.length !== 0 && this.pageConfig.pageIndex === 1 && this.tableData[0].analyseWay === '01') {
          this.tableFormData = sortData
        } else {
          this.tableFormData = sortData
        }
      }
    },
    // 每页多少条
    handleSizeChange (val) {
      if (this.typeSearch === 'P') {
        this.yfEsSearchData.pageConfig.pageSize = val
      } else {
        this.pageConfig.pageSize = val
      }
    },
    // 当前第几页
    handleCurrentChange (val) {
      if (val === 1) {
        if (this.tableData.length !== 0) {
          this.radioCheck = this.tableData[0].knowledgeBaseId
        } else {
          this.radioCheck = ''
        }
        this.formTableData = this.tableData[0]
      } else {
        this.radioCheck = ''
        this.formTableData = null
      }
      if (this.typeSearch === 'P') {
        this.yfEsSearchData.pageConfig.pageIndex = val
        this.$refs.yfEsSearchItem.loadData()
        this.vLoading = true
      } else {
        this.pageConfig.pageIndex = val
        this.vLoading = false
        this.clickPosition = 'page'
      }
    },
    // 点击行事件
    handleTable (item) {
      this.clickBut = true
      this.formTableData = item
    },
    problemTypeAsync (queryString, cb) {
      let data = []
      knowledgeBaseApi.knowledgeBaseList.getSelect({ type: '06' }).then((res) => {
        res.data.forEach(item => {
          data.push({ value: item.name })
        })
        var results = queryString ? data.filter(this.createFilter(queryString)) : data
        cb(results)
      })
    },
    createFilter (queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    problemPointAsync (queryString, cb) {
      let data = []
      knowledgeBaseApi.knowledgeBaseList.getSelect({ type: '07' }).then((res) => {
        res.data.forEach(item => {
          data.push({ value: item.name })
        })
        var results = queryString ? data.filter(this.createFilter(queryString)) : data
        cb(results)
      })
    },
    // 提交并返出数据
    submitData () {
      let data = {}
      if (this.activeName === '1') {
        if (this.clickBut) { // 判断是否点击行
          data = this.formTableData
        } else {
          if (this.tableData[0]) {
            data = this.tableData[0]
          } else {
            return
          }
        }
        data.analyseWay = '01'
      } else { // 返回第二个tabs的数据
        this.$refs['submitForm'].validate((valid) => {
          if (valid) {
            data = this.submitForm
            data.fileDic = format.formatDict(data.fileType, 'HG_FILE_TYPE')
            data.analyseWay = '02'
            data.fileNameStr = this.fileNameStr
            data.fileNameCode = this.fileNameCode
          } else {
            data = null
          }
        })
      }
      return data
    },
    // 高级检索显示和隐藏
    isAddShow () {
      this.dialogFormVisible = true
      this.clickPosition = 'btn'
    },
    filterFileType (row) {
      return format.formatDict(row.fileType, 'HG_FILE_TYPE')
    },
    // 反馈
    showEdit (data, editmodel) {
      this.dialogFeedbackVisible = true
      this.feedbackKeyId = data
    }
  }
}
</script>
<style lang="scss" scoped>
.repositoey-item{
  background: #fff;
}
.yfesSearch-item /deep/ .el-input input{
  max-width: 400px !important;
}
.textareaRepository{
 /deep/ textarea{
    height: 80px;
  }
}
.selectFile-item{
 /deep/ .el-select{
    width: 100% !important;
  }
}
 /deep/ .el-table td > .cell {
    text-overflow: ellipsis !important;
}
 /deep/ .el-table__row td:nth-child(1) .cell{
  text-overflow: initial !important;
}
/deep/ .reposit-table th .cell{
  text-align: center;
}
</style>
