<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"  v-if="$permission('/pcs/report/add')">
              <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">
                <!-- 遍历按钮 -->
                <el-dropdown-item
                  v-for="item in dictMessage.REPORT_TYPE.filter(item => !['6'].includes(item.dictChildValue))"
                  :key="item.dictChildLabel" @click.native="handleAnalyse(item.dictChildValue)"
                  v-if="$permission('/pcs/report/add/' + item.permission)">{{ item.dictChildLabel }}</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"
          @getRow="checkDetails" @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>
  </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';
export default {
  components: {
    Table,
    Card,
    visual,
    CreateReport,
    mergeTable,
    fields,
  },
  props: {
    isOperate: '',
    matterId:{},
    scenarioId:{}
  },
  data() {
    return {
      //视图类型
      viewTypes: [
        {
          name: '可视化',
          component: 'visual'
        },
        {
          name: '列表',
          component: 'Table'
        },
        {
          name: '卡片',
          component: 'Card'
        },
      ],
      //当前视图类型
      viewType: 'Table',
      //检索字段
      searchFiled: [],

      //检索条件
      searchOption: {
        name: localStorage.searchContent,
        scenarioNames:this.scenarioId,
        matterNames:this.matterId
      },
      //分组的值
      groupingValue: '',
      //分组
      groupingOption: [],
      //分页信息
      queryParams: {
        current: 1,
        size: 10,
      },
      //总数
      total: 0,
      //分页数量
      pageSize: [10, "全部"],
      //排序字段
      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.dictChildValue)) {
            item.permission = 'invalid'
          } else if (item.dictChildValue == 3) {
            item.permission = 'FTO'
          } else if (item.dictChildValue == 4) {
            item.permission = 'tort'
          } else if (item.dictChildValue == 5) {
            item.permission = 'avoidDesign'
          } else if (item.dictChildValue == 7) {
            item.permission = 'reInvalid'
          }
        })
      }
      if (a.REPORT_TYPE) {
        // 报告类型
        this.searchFiled[1].options = a.REPORT_TYPE.map(item => {
          return {
            value: item.dictChildValue,
            label: item.dictChildLabel
          }
        })
        // 报告状态
        this.searchFiled[2].options = a.REPORT_STATE.map(item => {
          return {
            value: item.dictChildValue,
            label: item.dictChildLabel
          }
        })
      }

      return a
    },
    state() {
      var a = this.$store.state.dictMessage.dictMessage.REPORT_STATE
      var b = {}
      if (a) {
        a.forEach(item => {
          b[item.dictChildValue] = item.dictChildLabel
        });
        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.showView = false
      this.$nextTick(() => {
        this.showView = true
      })
    },
    // 处理检索字段为array类型的问题
    handleSearchArray(obj) {
      switch (obj.label) {
        case '报告类型':
          let dict = this.dictMessage.REPORT_TYPE.filter(item => !['6'].includes(item.dictChildValue))
          obj.options = dict.map(item => {
            return {
              label: item.dictChildLabel,
              value: item.dictChildValue,
            }
          })
          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 = params
      // 调用查询接口
      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: this.sort,//排序
        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,
        scenarioList: []
      }
      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.handleFields(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)
          var routerReport3 = this.$router.resolve({
            path: "/tortIndex",
            query: {
              id: row.id,
              patentNo: row.signPatentNo,
              personId: row.personId,
              type: 8
            }
          })
          window.open(routerReport3.href, '_blank');
          break
        case '9'://回避设计
          this.handleDetails(row)
          break;
        case '10'://添加对比文件
          this.addPatentList(row)
          break
        case '11'://完成报告
          this.completeReport(row)
          break
        case '12'://追踪报告
          this.trackReport(row)
          break
        case '13'://添加无效理由和证据
          this.toInvalidIndex(row)
          break;
        case '14'://导入无效证据
          this.toInvalidResponset(row)
          break;
        case 'e'://编辑
          this.handleEdit(row)
          break
      }
    },
    // 删除
    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)
    },

    //查看详情（修改）
    checkDetails(row) {
      row.dictMessage = this.dictMessage
      row.showMenu = true
      this.$s.setSession('row', row)
      this.$s.setSession('params', row)
      switch (row.type) {
        case 0://无效分析
        case 1://稳定性分析
        case 2://第三方意见
          var router = this.$router.resolve({
            name: 'rDetails',
          })
          window.open(router.href, '_blank');
          break;
        case 3://FTO

        case 4://侵权
          var router = this.$router.resolve({
            name: 'FTOrDetails',
          })
          window.open(router.href, '_blank');
          break;
        case 5://回避
          var router = this.$router.resolve({
            name: 'avoidAside',
          })
          window.open(router.href, '_blank');
          break;
        case 6://图表
          break;
        case 7://无效应对
          var router = this.$router.resolve({
            name: 'InvalidResponse',
          })
          window.open(router.href, '_blank');
          break;
      }
    },

    //接收可视化的参数
    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.$nextTick(() => {
        this.handleMessage = ''
      })
    },
  },
};
</script>
<style lang="scss" scoped></style>