<template>
  <div class="height_100">
    <el-container v-if="showView">
      <el-header>
        <div id="step1">
          <mySearch style="width:500px" :SearchFields="searchFiled" @search="search" :searchValue="searchOption">
          </mySearch>
        </div>
        <div style="display:flex;">
          <div id="step2" v-if="[2].indexOf(isOperate) == -1" class="margin-right_10">
            <span>分组查询：</span>
            <el-select v-model="groupingValue" size="small" @change="changeGrouping" clearable style="width: 120px">
              <el-option v-for="item in groupingOption" :key="item.value" :label="item.name" :value="item.value">
              </el-option>
            </el-select>
          </div>
          <el-button-group id="step3" style="display:flex;justify-content:flex-start" v-if="[2].indexOf(isOperate) == -1">
            <el-button v-for="item in viewTypes" :key="item.component" size="small"
              :type="viewType == item.component ? 'primary' : ''" @click="onChange(item.component)">{{ item.name
              }}</el-button>
          </el-button-group>
          <div id="step4" class="margin-left_10">
            <el-dropdown size="small">
              <el-button type="primary" size="small">
                创建报告<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown" style="margin-top:0px"
                v-if="dictMessage.REPORT_TYPE && dictMessage.REPORT_TYPE.length > 0">
                <!-- 遍历按钮 -->
                <el-dropdown-item v-for="item in dictMessage.REPORT_TYPE.filter(item => !['6'].includes(item.value))"
                  :key="item.label" @click.native="handleAnalyse(item.value)">{{ item.label }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button type="primary" class="margin-left_10" size="small" @click="showField">显示栏位管理</el-button>
          </div>

        </div>
      </el-header>
      <el-main id="patent-list-container" class="main" v-loading="loading">
        <component :is="viewType" v-bind="$attrs" v-on="$listeners" :isOperate="isOperate" :tableData="dataList"
          :state="state" :queryParams="queryParams" @option="handleOption" @on-sort="handleSort" :groupBy="groupingValue"
          :groupingOption="groupingOption" :commonData="commonData" :searchOption="searchOption" :column="columnList" @params="getParams"></component>
      </el-main>
      <el-footer class="pagination" v-if="viewType != 'visual'">
        <el-pagination background layout="total,sizes, prev, pager, next, jumper" :current-page.sync="queryParams.current"
          :page-sizes="pageSize" :page-size.sync="queryParams.size" @current-change="handleCurrentChange"
          :handleMessage="handleMessage" @size-change="handleSizeChange" :total="total">
        </el-pagination>
      </el-footer>
    </el-container>
    <CreateReport ref="ReportForm" @getList="isGetList"></CreateReport>
    <fields ref="field" type="reportProject" @getFieldList="getFieldList"></fields>
    <Field-Drawer ref="FieldDrawer"></Field-Drawer>
    <reportFileDrawer ref="reportFileDrawer"></reportFileDrawer>
    <cronConclusion ref="cronConclusion" @save="getList"></cronConclusion>
    <exportReport ref="exportReport"></exportReport>
    <!-- 项目分享 -->
    <patentShare ref="patentShare"></patentShare>
  </div>
</template>

<script>
import Table from './view/table.vue'
import Card from './view/card.vue'
import visual from './view/visual.vue'
import mergeTable from './view/mergeTable.vue'
import CreateReport from './dialog/addAndEditReport.vue'
import fields from '@/views/components/dialog/fields.vue';
import FieldDrawer from '@/views/components/drawer/Field.vue'
import reportFileDrawer from './drawer/reportFileDrawer.vue'
import cronConclusion from './dialog/cronConclusion.vue'
import exportReport from './dialog/exportReport.vue'
import patentShare from '@/views/components/drawer/Share.vue';
export default {
  components: {
    Table,
    Card,
    visual,
    CreateReport,
    mergeTable,
    fields,
    FieldDrawer,
    reportFileDrawer,
    cronConclusion,
    exportReport,
    patentShare,
  },
  props: {
    isOperate: '',
    matterId: {},
    scenarioId: {},
    eventName: '',
    eventId: '',
  },
  data() {
    return {
      //视图类型
      viewTypes: [
        // {
        //   name: '可视化',
        //   component: 'visual'
        // },
        {
          name: '列表',
          component: 'Table'
        },
        {
          name: '卡片',
          component: 'Card'
        },
      ],
      //当前视图类型
      viewType: 'Table',
      //检索字段
      searchFiled: [],

      //检索条件
      searchOption: {
        name: localStorage.searchContent,
        reportType: localStorage.reportType ? [localStorage.reportType] : '',
        scenarioNames: this.scenarioId,
        matterNames: this.matterId,
        eventNames: this.eventName
      },
      //分组的值
      groupingValue: '',
      //分组
      groupingOption: [],
      //分页信息
      queryParams: {
        current: 1,
        size: 10,
      },
      //总数
      total: 0,
      //分页数量
      pageSize: [10, 20],
      //排序字段
      sort: [
        {
          "orderBy": "createTime",
          "orderType": 1
        }
      ],
      //加载
      loading: false,
      //报告数据集合
      dataList: [],
      // 报告分组数据集合
      commonData: [],
      // 栏位信息数组
      columnList: [],
      // 子组件新增、编辑报告成功发送的字符串
      handleMessage: '',
      showView: false,
    };
  },
  watch: {},
  computed: {
    dictMessage() {
      var a = this.$store.state.dictMessage.dictMessage
      if (a.REPORT_TYPE) {
        a.REPORT_TYPE.forEach(item => {
          if (['0', '1', '2'].includes(item.value)) {
            item.permission = 'invalid'
          } else if (item.value == 3) {
            item.permission = 'FTO'
          } else if (item.value == 4) {
            item.permission = 'tort'
          } else if (item.value == 5) {
            item.permission = 'avoidDesign'
          } else if (item.value == 7) {
            item.permission = 'reInvalid'
          }
        })
      }
      if (a.REPORT_TYPE) {
        // 报告类型
        this.searchFiled[1].options = a.REPORT_TYPE.map(item => {
          return {
            value: item.value,
            label: item.label
          }
        })
        // 报告状态
        this.searchFiled[2].options = a.REPORT_STATE.map(item => {
          return {
            value: item.value,
            label: item.label
          }
        })
      }

      return a
    },
    state() {
      var a = this.$store.state.dictMessage.dictMessage.REPORT_STATE
      var b = {}
      if (a) {
        a.forEach(item => {
          b[item.value] = item.label
        });
        return b
      }
      return []

    },
    scene() {
      var a = this.$store.state.dictMessage.scenario.map(item => {
        return {
          label: item.name,
          value: item.id
        }
      })
      var obj = this.searchFiled.find(item => { return item.label == '应用场景' })
      if (obj) {
        obj.options = a
      }
      return this.$store.state.dictMessage.scenario
    },
    matter() {
      var a = this.$store.state.dictMessage.matter.map(item => {
        return {
          label: item.name,
          value: item.id
        }
      })
      var obj = this.searchFiled.find(item => { return item.label == '调查类型' })
      if (obj) {
        obj.options = a
      }
      return this.$store.state.dictMessage.matter || []
    }
  },
  created() { },
  async mounted() {
    // 获取table栏位
    this.columnList = await this.$commonJS.getCustomField('reportProject')
    // 获取搜索/分组
    await this.getColumn()
    //获取报告清单
    this.getList()
    this.showViews()
  },
  methods: {
    //显示视图?
    showViews() {
      this.showView = false
      this.$nextTick(() => {
        this.showView = true
      })
    },
    // 显示栏位管理组件返回数据
    getFieldList(val) {
      this.columnList = val
    },
    // 显示栏位管理
    showField() {
      this.$refs.field.open(this.columnList)
    },
    //获取table栏位及分组字段、检索字段
    async getColumn() {
      let params = ['reportProject']
      await this.$api.getParamsCommon(params).then(res => {
        if (res.code == 200) {
          let conditionDTOList = JSON.parse(JSON.stringify(res.data[0].conditionDTOList))
          // 分组字段
          this.groupingOption = this.$commonJS.getField(conditionDTOList, (u) => u.ifGroup == true, {
            name: 'name',
            value: 'value',
          })
          // 搜索字段
          this.searchFiled = this.$commonJS.getField(conditionDTOList, (u) => u.ifSearch == true, {
            label: 'name',
            value: 'value',
            type: 'type',
          })
          //先获取报告类型，报告状态，相关事件，再为报告类型,报告状态,相关事件添加选项
          let arr = ['报告类型', '报告状态', '核心结论']
          arr.forEach(item => {
            let obj = this.searchFiled.find(item2 => {
              return item2.label == item
            })
            if (obj) {
              this.handleSearchArray(obj)
            }
          })
          //为应用场景添加选项
          var obj = this.searchFiled.find(item => { return item.label == '应用场景' })
          if (obj) {
            obj.options = this.scene.map(item => {
              return {
                label: item.name,
                value: item.id
              }
            })
          }
          var obj = this.searchFiled.find(item => { return item.label == '调查类型' })
          if (obj) {
            obj.options = this.matter.map(item => {
              return {
                label: item.name,
                value: item.id
              }
            })
          }
        }
      })
      this.showViews()
    },
    // 处理检索字段为array类型的问题
    handleSearchArray(obj) {
      switch (obj.label) {
        case '报告类型':
          if (this.dictMessage.REPORT_TYPE && this.dictMessage.REPORT_TYPE.length > 0) {
            let dict = this.dictMessage.REPORT_TYPE.filter(item => !['6'].includes(item.value))
            obj.options = dict.map(item => {
              return {
                label: item.label,
                value: item.value,
              }
            })
          }

          break;
        case '报告状态':
          obj.options = [
            { value: 0, label: '开卷审核' },
            { value: 1, label: '创建中' },
            { value: 2, label: '处理中' },
            { value: 3, label: '完成' },
            { value: 4, label: '取消开卷' },
            { value: 5, label: '补资料中' },
          ]
          break;
        case '核心结论':
          this.$api.queryCrons().then(res => {
            if (res.code == 200) {
              obj.options = res.data.data
            }
          })
          break;

        default:
          break;
      }
    },
    //接收检索条件
    search(val) {
      let params = {}
      val.forEach(item => {
        if (item.type == 3) {
          params[item.value] = item.searchValue.map(itemValue => {
            return itemValue.value
          })
        } else {
          params[item.value] = item.searchValue.label
        }
      })
      // 返回字符串
      this.searchOption = this.$commonJS.ArrayToArray(val)
      // 调用查询接口
      this.queryParams.current = 1
      this.getList()
    },
    //获取报告列表
    getList() {
      let params = {
        ...this.queryParams,//分页信息
        searchQuery: this.$commonJS.objectToString(this.searchOption),//检索条件
        orderDTOList: this.sort,//排序信息
      }
      this.loading = true
      this.$api.queryReportProject(params).then(res => {
        if (res.code == 200) {
          this.dataList = res.data.data
          this.total = res.data.total
          this.loading = false
        }
      }).catch(error => {
        this.dataList = []
        this.total = 0
        this.loading = false
        this.$message.error(error.message)
      })
    },
    // 获取分组数据
    getGrouping() {
      let params = {
        ...this.queryParams,//分页信息
        searchQuery: this.$commonJS.objectToString(this.searchOption),//检索条件
        orderDTOList: [
          {
            orderBy: this.groupingValue,
            orderType: this.sort[0].orderType
          }
        ],//排序
        groupBy: this.groupingValue,//分组信息
      }
      this.$api.groupReportProject(params).then(res => {
        if (res.code == 200) {
          this.commonData = res.data.data.values
          this.total = res.total
        }
      }).catch(error => {
        this.commonData = []
        this.total = 0
        this.$message.error(error.message)
      })
    },
    //排序
    handleSort({ column, prop, order }) {
      //如需要多个字段排序，则不需要清空
      var params = {
        sort: this.sort,
        column,
        prop,
        order,
      }
      this.sort = this.$commonJS.getSortData(params)
      this.queryParams.current = 1
      this.isGrouping()
    },
    //分页
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.isGrouping()
    },
    //切换页大小
    handleSizeChange(val) {
      this.queryParams.size = val
      this.isGrouping()
      // this.getList()
    },
    //切换视图
    onChange(type) {
      this.viewType = type
      if (type == 'visual') {
        this.$nextTick(() => {
          this.reportVisual()
        })
        return false
      }
      this.queryParams.size = this.viewType === 'Table' ? 10 : 12
      this.groupingValue = ''
      this.queryParams.current = 1
      this.getList()
    },
    //展示报告可视化
    reportVisual() {
      this.$api.reportVisual(this.queryParams).then(response => {
        if (response.code == 200) {
          // this.$refs.reportVisual.open(response.data)
        }
      })
    },
    //切换分组值
    changeGrouping(val) {
      if (val != '') {
        this.viewType = 'mergeTable'
      } else {
        this.viewType = 'Table'
      }
      this.queryParams.current = 1
      this.groupingValue = val
      this.isGrouping()
    },
    // 区分是否为分组
    isGrouping() {
      if (this.groupingValue != '') {//分组
        this.getGrouping()
      } else {//不分组
        this.getList()
      }
    },
    //打开创建报告弹窗
    handleAnalyse(id) {
      var form = {
        reportType: id,
        eventId: this.eventId,
        eventName: this.eventName,
        matterId: this.matterId || [],
        scenarioId: this.scenarioId || [],
      }
      this.$refs.ReportForm.open(form)
    },
    //操作列
    handleOption({ option, row, isLast }) {
      this.$s.setSession('params', row)
      switch (option) {
        case '0'://分享
          this.share(row)
          break
        case '1'://导出报告
          this.exportReport(row)
          break
        case '2'://报告文档
          this.handleFile(row)
          break
        case '5'://拆分特征
          this.handleDetails(row)
          break
        case '3'://自定义字段
          this.handleField(row)
          break
        case '4'://任务分配
          this.handleTask(row)
          break
        case '6'://导入专利
          this.handleImportPatent(row)
          break
        case '7'://删除
          this.handleDelete(row, isLast)
          break;
        case '8'://侵权分析技术特征对比
          // this.$s.setSession('reportMessage1', row)
          this.toTortIndex(row)
          break
        case '9'://回避设计
          this.handleDetails(row, '回避设计')
          break;
        case '10'://对比文件
          this.patentList(row)
          break
        case '11'://完成报告
          this.completeReport(row)
          break
        case '12'://追踪报告
          this.trackReport(row)
          break
        case '13'://添加无效理由和证据
          this.toInvalidIndex(row)
          break;
        case '14'://导入无效证据
          this.toInvalidEvidence(row)
          break;
        case '15'://录入产品信息
          this.toInformationEntry(row)
          break;
        case 'e'://编辑
          this.handleEdit(row)
          break
      }
    },
    //分享
    share(row){
      this.$refs.patentShare.open(row.id)
    },
    //导出报告
    exportReport(row){
      this.$refs.exportReport.open(row)
    },
     //追踪报告
   trackReport(row){
      var form = JSON.parse(JSON.stringify(row))
      this.$set(form,'associateReportName',row.volumeNumber?row.volumeNumber:row.name)
      this.$set(form,'associateReportId',row.id)
      this.$set(form,'cronIds',[])
      if(isNaN((row.name).substring((row.name).length-1))){
        form.name = row.name + '-V1'
      }else{
       var a= Number((row.name).substring((row.name).length-1)) + 1
       form.name = (row.name).substring(0,(row.name).length-1) + a
      }
      form.status = 1
      form.id = null
      form.track = true
      this.$refs.ReportForm.open(form)
    },
    //完成报告
    completeReport(row){
      this.$refs.cronConclusion.open(row)
    },
    //无效证据
    toInvalidEvidence(row){
      this.$router.push({
        path:'/evidence',
        query:{
          projectId:row.id,
          reportType:row.reportType,
          signPatentNo:row.signPatentNo,
          patentNo:row.signPatentNo
        }
      })
    },
    // 报告文档
    handleFile(row) {
      this.$refs.reportFileDrawer.open(row.id)
    },
    //自定义栏位管理
    handleField(row) {
      this.$refs.FieldDrawer.open(row.id)
    },
    //跳转到专利列表页面
    patentList(row){
      this.$router.push(
        {
          path:'/reportPatentList',
          query:{
            projectId:row.id
          }
        }
      )
    },
    // 跳转录入产品信息页面
    toInformationEntry(row) {
      var routerReport = this.$router.resolve({
        path: "/informationEntry",
        query: {
          patentNo: row.signPatentNo,
          projectId: row.id,
          reportType: row.reportType
        }
      })
      window.open(routerReport.href, '_blank');
    },

    // 跳转专利与产品关联比对
    toTortIndex(row) {
      var routerReport = this.$router.resolve(
          {
            path: '/patentDetails/' + row.signPatentNo,
            query: {
              projectId: row.id,
              reportType: row.reportType,
              taskType:3
            }
          }
        )


      // var routerReport = this.$router.resolve({
      //   path: "/tortIndex",
      //   query: {
      //     patentNo: row.signPatentNo,
      //     projectId: row.id,
      //     reportType: row.reportType
      //   }
      // })
      window.open(routerReport.href, '_blank');
    },
    // 跳转回避设计或拆分特征
    handleDetails(row, type) {
      if (type == '回避设计') {
        var router = this.$router.resolve({
          path: "/avoid",
          query: {
            patentNo: row.signPatentNo,
            reportId: row.id,
          }
        })
        window.open(router.href, '_blank');
      }
    },
    // 删除
    handleDelete(row, isLast) {
      this.handleDeletes([row.id], isLast)
    },
    // 批量删除报告
    handleDeletes(ids, isLast) {
      this.$confirm('此操作将永久删除该报告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.deleteReportProject(ids).then(res => {
          if (res.code == 200) {
            if (isLast) {
              this.isGrouping()
            } else {
              this.getList()
            }
            this.handleMessage = '删除成功'
            this.clearMessage()
            this.$message.success('删除报告成功')
          }
        }).catch(err => {
          this.$message.error(err.message)
        })

      }).catch(() => {
        this.$message.info("已取消删除")
      });
    },
    //编辑报告
    handleEdit(row) {
      this.$refs.ReportForm.open(row)
    },

    //接收可视化的参数
    getParams(params) {
      if (params.conclusionType == '-1') {
        this.searchOption.statuses = ['0', '1', '2', '4', '5']
        this.searchOption.types = [params.type]
      } else {
        this.searchOption.cronIds = [params.conclusionType]
      }
      var a = JSON.parse(JSON.stringify(this.searchOption))
      this.searchOption = a
      this.viewType = 'Table'
      this.queryParams.current = 1
      this.getList()
    },
    //创建报告子组件返回值
    isGetList(val) {
      this.handleMessage = val
      this.queryParams.current = 1
      this.isGrouping()
      this.clearMessage()
    },
    //清空信息
    clearMessage() {
      this.$emit('submit', true)
      this.$nextTick(() => {
        this.handleMessage = ''
      })
    },
  },
};
</script>
<style lang="scss" scoped></style>