<template>
  <div style="background:white;min-width:1400px">
      <el-container>
        <el-header>
            <div>
              <mySearch style="width:500px" :SearchFields="searchFiled" @search="search" :searchValue="searchOption"></mySearch>  
            </div>
            <div style="display:flex;">
                <el-button-group style="display:flex;justify-content:flex-start">
                  <el-button size="small" :type="queryShowType === '2' ? 'primary' : ''"  @click="onChange2('2')" >可视化</el-button>
                  <el-button :type="queryShowType === '0' ? 'primary' : ''" @click="onChange2('0')" size="small">列表 </el-button>
                  <el-button :type="queryShowType === '1' ? 'primary' : ''" @click="onChange2('1')" size="small">卡片</el-button>
                </el-button-group>
                <el-dropdown size="small" style="margin-right:20px" 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>
            </div>
        </el-header>
        <el-main id="patent-list-container" class="main" v-loading="loading" >
          <div v-if="queryShowType == 2">
            <Report-Visual ref="reportVisual" @params="getParams"></Report-Visual>
          </div>
          <div v-else>
            <component :is="viewType" :data="dataList" @checkVisual="checkVisual" :state="state" :group="queryParams.group" :params="queryParams"  @option="handleOption" @sort="handleSort" @getRow="getRow"></component>
          </div>
        </el-main>
        <el-footer class="workspace-content-patent-page" v-if="queryShowType != 2">
          <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"
            @size-change="handleSizeChange"
            :total="total">
          </el-pagination>
        </el-footer>
      </el-container>
    <!-- 弹窗创建报告 -->
    <CreateReport ref="ReportForm" @getList="isGetList"></CreateReport>
    <el-dialog width="1100px" title="设置" :visible.sync="setVisible" :before-close="close">
        <Project-Field :reportId="reportId"></Project-Field>
  </el-dialog>
  <el-dialog width="1000px" title="选择模板" :visible.sync="reportTemplate" :before-close="close1" >
    <div  v-loading="loadingTemplate"
  element-loading-text="报告导出中"
  element-loading-spinner="el-icon-loading"
 >
      <Report-Template :reportType="reportType" @getReportTemplateId="getReportTemplateId"></Report-Template>
        <div slot="footer" class="dialog-footer" style="display: flex;justify-content: flex-end;">
          <el-button @click="close1">取 消</el-button>
          <el-button type="primary" @click="submitExport" :loading="btnLoading">确 定</el-button>
        </div>
    </div>
        
  </el-dialog>
  <el-drawer
    class="custom-drawer-form"
    title="分享"
    size="800px"
    :visible.sync="drawer"
    direction="rtl"
    :before-close="closeDrawer"
    destroy-on-close
    append-to-body
  >
    <shareReport :reportId="reportId"></shareReport>
  </el-drawer>

  <!-- 添加核心结论 -->
  <el-dialog width="800px" title="添加核心结论" :visible.sync="conclusionVisible" :efore-close="closeConclusion">
    <Cron-Conclusion ref="cronConclusion" :reportId="reportId" @dialog="getDialog"></Cron-Conclusion>
  </el-dialog>

  <project-file-drawer  ref="projectFileDrawer" />


  <visualDialog ref="visualDialog"></visualDialog>
  </div>
</template>

<script>
import ReportTabel from './components/Tabel';
import ReportCard from './components/Card'
import CreateReport from './components/CreateReport.vue'
import ProjectField from '@/views/layout/components/field.vue';
import ReportTemplate from './components/ReportTemplate.vue';
import ProjectFileDrawer from "./components/File.vue";
import { downLoad2 } from "@/utils";

import shareReport from './components/share/shareReport.vue';
import ReportVisual from './components/visual/reportVisual.vue';

import CronConclusion from './components/cronConclusion.vue';

import InvalidIndex from "@/views/report/InvalidResponse/components/InvalidIndex.vue"

import visualDialog from '@/views/home/components/visualDialog.vue'
import { openVisual } from "@/views/home/components/mixins";

export default {
mixins:[openVisual],
components: {
  ReportTabel,
  ReportCard,
  CreateReport,
  ProjectField,
  ReportTemplate,
  ProjectFileDrawer,
  shareReport,
  ReportVisual,
  CronConclusion,
  InvalidIndex,
  visualDialog,
},
data() {
  return {
    conclusionVisible:false,
    drawer:false,
    btnLoading:false,
    reportTemplate:false,
    setVisible:false,
    dataList: [],
    queryShowType: '0',
    viewType: 'ReportTabel',
    searchFiled:[
      {
        label:'报告名称',
        value:'name',
        type:1,
        placeholder:'请输入报告名称'
      },
      {
        label:'报告类型',
        value:'types',
        type:3,
        placeholder:'请选择报告类型',
        // options:this.dictMessage.REPORT_TYPE||[]
      },
      {
        label:'报告状态',
        value:'statuses',
        type:3,
        placeholder:'请选择报告状态',
        // options:this.dictMessage.REPORT_STATE||[]
      },
      {
        label:'核心结论',
        value:'cronIds',
        type:3,
        placeholder:'请选择核心结论',
        options:[]
      },
    ],
    searchOption:{
      name:localStorage.searchContent
    },
    queryParams: {
      cronIds:[],
      types:[],
      statuses:[],
      group: [],
      size: 10,
      current: 1,
      signPatentNo:"",
      
    },
    reportAsDicItem:{
      "0":"INVALID_ASSESS",
      "1":"THIRD_ASSESS",
      "2":"STABILITY_ASSESS",
      "3":"FTO_ASSESS",
      "4":"TORT_ASSESS",
      "5":"AVOID_ASSESS",
    },
    ConclusionList:[],
    pageSize:[10,"全部"],
    total: 0,
    loading: false,
    showDialog: false,
    loadingTemplate: false,
    reportId: "",
    reportType:'',
    reportTemplateId:''
  }
},
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 []
    
  }
},
watch:{
},
mounted() {
  this.getList()
  this.getConclusion()//获取核心结论
},
methods: {
  //获取检索条件
  search(val){
    var params = {}
    if(val.length>0){
      val.forEach(item => {
        if(item.type == 3){
          params[item.value] = item.searchValue.map(item1=>{
            return item1.value
          }) 
        }else{
          params[item.value] = item.searchValue.label
        }
      });
    }
    this.searchOption = params
    this.queryParams.current = 1
    this.getList()
  },
  //获取核心结论
  getConclusion(){
    this.$api.getConclusion([]).then(response=>{
      if(response.code == 200){
        this.ConclusionList = response.data
        this.searchFiled.find(item=>{
          return item.value == 'cronIds'
        }).options = this.ConclusionList.map(item=>{
          return {
            value:item.cType,
            label:item.cTypeName
          }
        })
      }
    })
    
  },
  handleSizeChange(val) {
    // this.queryParams.size = null
    // this.queryParams.current = null
    this.getList()
      // console.log(`每页 ${val} 条`);
    },
  getReportTemplateId(val){
    this.reportTemplateId = val
  },
  close1(){
    this.reportType = ''
    this.reportTemplateId = ''
    this.reportTemplate = false
  },
  submitExport(){
    if (this.reportTemplateId) {
      this.loadingTemplate=true
      var a = {
        reportId : this.reportId,
        templeId :this.reportTemplateId
      }
      this.$api.exportReport(a).then(response => {
        if (response.code == 200) {
          this.$message.success('导出成功')
          downLoad2(response.data)
          this.reportType = ''
          this.reportTemplateId = ''
          this.reportTemplate = false
          this.loadingTemplate=false
        } else{
          this.$message.error('导出失败,请重试')
          this.loadingTemplate=false
        }
      }).catch(error => {
        this.$message.error('导出失败,请重试')
          this.loadingTemplate=false
      })
    }else{
      this.$alert('请选择报告模板', '提示', {
        confirmButtonText: '确定',
        callback: action => {
          
        }
      });
    }
    
  },
  //关闭弹窗
  close(){
    this.setVisible = false
  },
  //获取选中行参数
  getRow(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' ,
          // query: {
          //   row:JSON.stringify(row)
          //   // reportId:row.id,
          //   // signPatentNo:row.signPatentNo,
          //   }
        })
        window.open(router.href, '_blank');
        break;
      case 3:
       
      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;
    }
    


  },
  // 创建报告：无效分析等点击事件
  handleAnalyse(id) {
    var form = {
      type:id,
    }
    this.$refs.ReportForm.open(form)
  },
  handleOption({ option, row }) {
    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.$confirm('此操作将永久删除该报告, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.handleDelete(row)
           
          }).catch(() => {
            this.$message.info("已取消删除")         
          });
        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)
      // associateReportName:this.row.volumeNumber?this.row.volumeNumber:this.row.name,
      //         associateReportId:this.reportId
          break
      case '13'://添加无效理由和证据
        this.toInvalidIndex(row)
          break;
      case '14'://导入无效证据
        this.toInvalidResponset(row)
          break;
      case 'e':
        this.handleEdit(row)
        break
    }
  },
  // 导入无效证据
  toInvalidResponset(row) {
    this.$router.push({
      path: '/evidenceAndRequestIndex',
      query: {
        patentNo: row.signPatentNo,
        reportId: row.id,
      }
    })
  },
  toInvalidIndex(row) {
    this.$router.push({
      path: '/invalidIdexRouter',
      query: {
        patentNo: row.signPatentNo,
        reportId: row.id,
        reportType: row.reportType || row.type,
      }
    })
  },
  //追踪报告
  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,'conclusionIds',[])
    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)
  },
  //关闭分享抽屉
  closeDrawer(){
    this.drawer  = false
  },
  //分享
  share(row){
    this.reportId  = row.id
    this.drawer = true
  },
   //获取弹窗状态
   getDialog(val){
      this.closeConclusion()
      if(val){
         var a = {
          reportId:val,
          status:3
        }
        this.$api.UpdateStatus(a).then(response=>{
          if(response.code == 200){
            this.$message.success('该报告已完成')
            this.getList()
          }
        })
      }
       
    },
    //关闭弹窗
    closeConclusion(){
      this.conclusionVisible = false
    },
  //完成报告
  completeReport(row){
    this.conclusionVisible = true
    this.$nextTick(()=>{
      this.$refs.cronConclusion.open(row)
    })
    return false
    this.$confirm('确定将该报告置为完成?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var a = {
          reportId:row.id,
          status:3
        }
        this.$api.UpdateStatus(a).then(response=>{
          if(response.code == 200){
            this.$message.success('该报告已完成')
            this.getList()
          }
        })
      }).catch(() => {
               
      });
    
  },
  addPatentList(row){
    this.$s.setSession('reportMessage1',row)
    var router = this.$router.resolve({
          path: '/addPatentList' ,
          query: {
            id: row.id,
            name: row.name,
            status:row.status
          }
        })
    window.open(router.href, '_blank');
  },
  handleFile(row){
    this.$refs.projectFileDrawer.open(row.id,1)
  },

  handleImportPatent(row) {
    this.$router.push({
      path: '/import',
      query: {
        id: row.id
      }
    })
  },
  exportReport(row){
    this.reportId = row.id
    this.reportType = row.type
    this.reportTemplate = true
  },
  handleDetails(val){
    this.$s.setSession('reportMessage1',val)
    switch(val.type){
      case 0:
      case 1:
      case 2:
        var routerReport = this.$router.resolve({
          path: "/InvalidIndex",
          query: {
            id: val.id,
            patentNo:val.signPatentNo,
            splitType:val.splitType,
            splitBy: val.splitBy,
            personId:val.personId,
          }
        })
        window.open(routerReport.href, '_blank');//open方法中添加_blank属性打开新窗口页面
        break;
      case 3:
        var routerReport2 = this.$router.resolve({
            path: "/FTOIndex",
            query: {
              id: val.id,
              patentNo:val.signPatentNo,
              personId:val.personId,
            }
          })
          window.open(routerReport2.href, '_blank');//open方法中添加_blank属性打开新窗口页面
          break;
      case 4:
      var routerReport3 = this.$router.resolve({
            path: "/tortIndex",
            query: {
              id: val.id,
              patentNo:val.signPatentNo,
              personId:val.personId,
              type:5
            }
          })
          window.open(routerReport3.href, '_blank');//open方法中添加_blank属性打开新窗口页面
          break;
      case 5:
      var routerReport4 = this.$router.resolve({
            path: "/avoid",
            query: {
              id: val.id,
              patentNo: val.signPatentNo,
              splitType:val.splitType,
              splitBy: val.splitBy,
              personId:val.personId,
            }
          })
          window.open(routerReport4.href, '_blank');//open方法中添加_blank属性打开新窗口页面
          break;
      case 6:

    }
   
    
    
  },
  handleDelete(row) {
    this.$api.deleReport({ id: row.id }).then(res => {
      if(res.code == 200){
        this.$message.success("删除报告成功")
        this.getList()
      }
    }).catch(error=>{
      this.$message.error("删除报告失败")
    })
  },
  handleFields(row) {
    this.reportId=row.id
    this.setVisible = true
    //  this.$api.listPatentField().then(res=>{})
  },
  handleTask(row) {
    // console.log(row);
    let a=this.$router.resolve({
      path: "/SelectedPatent",
      query: {
        reportId: row.id,
        personId:row.personId,
      }
    })
    this.$s.setSession('row',row)
    window.open(a.href,"_blank")
  },
  handleEdit(row) {
    if(row.type == 7){
      this.$api.reReportDetail({reportId:row.id}).then(response=>{
        if(response.code == 200){
          // this.$set(this,'form',response.data)
          this.$refs.ReportForm.open(response.data)
        }
      })
    }else{
        this.$refs.ReportForm.open(row)
    }
    
  },
  handleSort(sort) {
    // console.log(sort)
    this.queryParams.orderBy = sort.prop
    this.queryParams.orderDesc = sort.order
    // this.queryParams.sort = { ...sort }
    this.getList()
  },
  handleCurrentChange(val) {
    this.queryParams.current = val;
    this.getList();
  },
  onChange() {
    this.queryParams.current = 1
    this.getList()
    this.handleChangeView()
  },
  getList2(){
    this.queryParams.current = 1
    this.getList()
    if(this.queryShowType == 2){
      this.$nextTick(()=>{
        this.reportVisual()
      })
    }
    
  },
  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.queryShowType = '0'
    this.handleChangeView()
    this.getList2()

  },
  reportVisual() {
    this.$api.reportVisual(this.queryParams).then(response=>{
          if(response.code == 200){
            this.$refs.reportVisual.open(response.data)
          }
        })
   },
  onChange2(type) {
    this.queryShowType = type
    if(type == 2){
      
      this.$nextTick(()=>{
        this.reportVisual()
        
      })
      
      return false
    }
    this.queryParams.size = this.queryShowType === '0' ? 10 : 12
    this.onChange()
  },
  handleChangeView() {
    let view = [
      ['ReportTabel', 'ReportCard'],
    ]
    if (this.queryParams.group.length === 0) {
      // console.log(view[0][this.queryShowType],'777777');
      this.viewType = view[0][this.queryShowType]
    } else {
      this.viewType = view[1][this.queryShowType]
      // console.log(this.viewType)
    }
  },
  isGetList(val){
    if(val == true){
      this.getList()
    }
  },
  getList() {
    var params = this.queryParams
    params = {
      ...this.queryParams,
      ...this.searchOption
    }
    // this.pageSize = this.queryShowType === '0' ? [10] : [12]
    this.loading = true
    this.$api.QueryReport(params).then(response=>{
      if(response.code == 200){
        this.pageSize = this.queryShowType === '0' ? [10] : [12]
        this.dataList = response.data
        // if(!this.queryParams.size){
        //   this.queryParams.current = 1
        //   this.queryParams.size = this.total = response.pageColumn.total
        // }
        this.pageSize.push(response.pageColumn.total)
        this.total = response.pageColumn.total
         this.loading = false
      }
    }).catch(error=>{
        this.pageSize = this.queryShowType === '0' ? [10] : [12]
        this.dataList = []
        this.total = 0
        this.loading = false
    })
   
  },
 
},
}
</script>

<style lang="scss" scoped>
.right{
  float: right;
}
</style>