<template>
  <div class="workspace height_100">
      <!-- <div class="query-top" v-if="[2].indexOf(isOperate) == -1">
        <el-collapse>
          <el-collapse-item title="图表预览" name="1">
            <div class="chart-box">
              <total-chart ref="totalChart" />
            </div>
          </el-collapse-item>
        </el-collapse>
      </div> -->
      <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;margin-right:10px">
              <div id="step2"  v-if="[2].indexOf(isOperate) == -1">
                <span>分组查询：</span>
                <el-select v-model="group" clearable size="small"
                  @change="onChange" style="width:200px">
                  <el-option v-for="item in groupingOption" :key="item.value" :label="item.name" :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <el-button-group class="margin-left_10" id="step3"  v-if="[2].indexOf(isOperate) == -1">
                <el-button :type="queryShowType === '2' ? 'primary' : ''" @click="onChange2('2')"
                  size="small">可视化</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 id="step4" trigger="click" split-button type="primary" size="small">
                <span @click="handleAdd" v-disabled="false">新增专利数据库</span>
                <el-dropdown-menu slot="dropdown" class="text-align_center">
                  <el-dropdown-item @click.native="handleExport"  v-if="[2].indexOf(isOperate) == -1">导出列表</el-dropdown-item>
                  <el-dropdown-item @click.native="handleImport" v-if="[2].indexOf(isOperate) == -1">导入数据包</el-dropdown-item>
                  <el-dropdown-item @click.native="handleField">显示栏位管理</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </el-header>
          <el-main class="workspace-main height_100">
            <div v-loading="loading" class="height_100">
              <component v-if="showView" :is="viewType" v-bind="$attrs" v-on="$listeners" :isOperate="isOperate"
                :tableData="dataList" :groupBy="group" :groupingOption="groupingOption" :searchOption="searchOption" :scenario="commonData" :matter="matter"
                :queryParams="queryParams" :column="fieldList" @option="handleOption" @on-sort="handleSort" :handleMessage="handleMessage"></component>
            </div>
          </el-main>
          <el-footer class="pagination" v-if="[2].indexOf(isOperate) == -1 && this.queryShowType != '2'">
            <el-pagination backgroundx layout="total,sizes, prev, pager, next, jumper" :current-page.sync="queryParams.current"
              :page-size.sync="queryParams.size" @current-change="handleCurrentChange" :total="total">
            </el-pagination>
          </el-footer>
        </el-container>
      </div>

    <project-form-drawer @submit="getMessage" :common-data="commonData" ref="projectFormDrawer" />
    <field ref="field" type="patentProject" @getFieldList="getFieldList"></field>
    <!-- 项目分享 -->
    <patentShare ref="patentShare"></patentShare>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import TotalChart from "./components/TotalChart";
import Table from "./components/view/table.vue";
import Card from "./components/view/card.vue";
import mergeTable from "./components/view/MergeTable.vue";

import ProjectFormDrawer from './components/drawer/form.vue'
import field from '@/views/components/dialog/fields.vue';
import patentShare from '@/views/components/drawer/Share.vue';

export default {
  components: {
    TotalChart,
    Table,
    Card,
    ProjectFormDrawer,
    field,
    mergeTable,
    patentShare,
  },
  props: {
    isOperate: '',
    matterId:{},
    scenarioId:{},
    eventName:'',
    eventId:''
  },
  data() {
    return {
      //检索字段
      searchFiled: [],
      //检索条件
      searchOption: {
        scenarioNames:this.scenarioId,
        matterNames:this.matterId,
        name:localStorage.searchContent,
        eventNames:this.eventName
      },
      //专利数据库数据总数
      total: 0,
      //分页信息
      queryParams: {
        size: 10,
        current: 1,
      },
      //排序
      sort: [
        {
          "orderBy": "createTime",
          "orderType": 1
        } 
      ],
      //分组集合
      groupingOption: [],
      //分组
      group: '',
      //展示的视图
      queryShowType: '0',
      //显示的视图组件
      viewType: 'Table',
      //加载
      loading: false,
      //专利数据库数据集合//分组及不分组公用此变量
      dataList: [],
      //栏位集合
      fieldList: [],
      //接受子组件消息
      handleMessage: '',
      //显示视图
      showView: false,
    };
  },
  watch: {},
  computed: {
    ...mapGetters(['userinfo']),
    commonData() {
      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() {
    this.fieldList = await this.$commonJS.getCustomField('patentProject')
    //获取检索字段和分组字段
    await this.getColumn()
    //获取专利数据库列表
    this.getList()
    this.showViews()
  },
  methods: {
    //显示视图?
    showViews() {
      this.showView = false
      this.$nextTick(() => {
        this.showView = true
      })
    },
    //获取自定义栏位
    getFieldList(data) {
      this.fieldList = data
    },
    //获取检索字段和分组字段
    async getColumn() {
      let params = ['patentProject']
      await this.$api.getParamsCommon(params).then(async 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',
          })
          //为应用场景添加选项
          var obj = this.searchFiled.find(item=>{return item.label == '应用场景'})
          if(obj){
            obj.options = this.commonData.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()
    },

    //检索
    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.isGrouping()
    },
    //获取专利数据库列表/卡片数据
    getList() {
      this.queryParams.size = this.queryShowType === '0' ? 10 : 12
      var params = this.queryParams
      params = {
        ...this.queryParams,//分页信息
        searchQuery: this.$commonJS.objectToString(this.searchOption),//检索条件
        orderDTOList: this.sort,//排序
      }
      this.loading = true
      this.$api.queryPatentProject(params).then(response => {
        this.dataList = response.data.data
        this.total = response.data.total
        this.loading = false
      }).catch(error => {
        this.dataList = []
        this.total = 0
        this.loading = false
      })
    },
    // 获取分组数据
    getGrouping() {
      let params = {
        ...this.queryParams,//分页信息
        searchQuery: this.$commonJS.objectToString(this.searchOption),//检索条件
        orderDTOList: [
          {
            orderBy:this.group,
            orderType:this.sort[0].orderType
          }
        ],//排序
        groupBy: this.group,//分组的值
      }
      this.loading = true
      this.$api.groupPatentProject(params).then(response => {
        this.dataList = response.data.data.values
        this.total = response.data.total
        this.loading = false
      }).catch(error => {
        this.dataList = []
        this.total = 0
        this.loading = false
      })
    },
    //排序
    handleSort({ column, prop, order, str }) {
      var params = {
        sort:this.sort,
        column,
        prop,
        order,
      }
      this.sort = this.$commonJS.getSortData(params)//如需要多个字段排序，则不需要清空
      this.queryParams.current = 1
      //1表示展开行2表示基础表格
      if (str == '1') {
        this.getGrouping()
      } else {//table排序
        this.getList()
      }
    },
    //分页
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.isGrouping();
    },
    //切换到分组
    onChange(val) {
      if (val != '') {
        this.viewType = 'mergeTable'
      } else {
        this.viewType = 'Table'
      }
      this.group = val
      this.queryParams.current = 1
      this.queryParams.size = 10
      this.isGrouping()//区分是否分组，调用不同请求数据
    },
    // 区分是否为分组
    isGrouping() {
      if (this.group != '') {//分组
        this.getGrouping()
      } else {//不分组
        this.getList()
      }
    },
    //切换table、卡片视图
    onChange2(type) {
      var viewTypes = {
        '0':'Table',
        '1':'Card',
        '2':'TotalChart'
      }
      this.group = ''
      this.queryShowType = type
      this.viewType = viewTypes[type]
      if(type == 2){
        return false
      }
      this.queryParams.current = 1
      this.getList()
      // this.onChange()
    },
    //新增专利数据库
    handleAdd() {
      this.$refs.projectFormDrawer.open({
        ifUpdate: false,
        updateTime: 'day',
        crons: '',
        status: '0',
        sort: 1,
        matterIds:this.matterId || [],
        scenarioIds:this.scenarioId || [],
        eventName:this.eventName,
        eventId:this.eventId
      }, '新增专利数据库')
    },
    //确认提交专利数据库信息
    getMessage(val) {
      this.handleMessage = val
      this.queryParams.current = 1
      this.isGrouping()
      this.clearMessage()
    },
    clearMessage() {
      this.$emit('submit',true)
      this.$nextTick(() => {
        this.handleMessage = ''
      })
    },
    //导出列表
    handleExport() {
      this.btnLoading = true
      this.$api.exportProjectList().then(response => {
        downLoad(response, getFileName('xlsx'))
        this.btnLoading = false
      }).catch(error => {
        this.btnLoading = false
      })
    },
    //导入数据包
    handleImport() {
      this.$refs.projectImport.open()
    },
    //显示栏位管理
    handleField() {
      this.$refs.field.open(this.fieldList)
    },
    //操作列
    handleOption({ option, row ,isLast}) {
      switch (option) {
        case '0'://Excel导入
          this.patentImport(row,1)
          break
        case '1'://专利号导入
          this.patentImport(row,2)
          break
        case '2'://检索条件导入
          this.patentImport(row,4)
          break
        case '3'://任务清单
          this.taskList(row)
          break
        case '5'://报告管理
          this.reportFile(row)
          break
        case '6'://产品架构
          this.framework(row)
          break
        case '7'://事件
          break
        case '8'://其他附件
          this.otherFiles(row)
          break;
        case '9'://项目分享
          this.$refs.patentShare.open(row.id)
          break;
        case '10'://删除
          this.deletes(row,isLast)
          break
        case 'e'://编辑
          this.handleEdit(row)
          break
      }
    },
    
    otherFiles(row){

    },
    //任务清单
    taskList(row){
      this.$router.push(
        {
          path:'/myTask',
          query:{
            projectId:row.id
          }
        }
      )
    },
    //报告文档
    reportFile(row){
      this.$router.push(
        {
          path:'/reportFiles',
          query:{
            projectId:row.id
          }
        }
      )
    },
    //架构
    framework(row){
      var form = {
        // name:row.name,
        // id:row.id,
        // categoryId:row.categoryId,
        // type:val,
      }
      let router = this.$router.resolve({
        path: '/frameworkIndex',
        query: {
          row: JSON.stringify(form),
          projectId:row.id
        }
      })
      window.open(router.href, '_blank')
    },
    //专利导入
    patentImport(row,type){
      var form = {
        importToId:row.id,
        importToType:0,
        type:type,
        ifUpdate:row.ifUpdate,
        crons:row.crons
      }
      this.$commonJS.toImportParent(form,type)
    },
    //获取删除的id
    deletes(row,isLast) {
      this.deletePatentProject([row.id],isLast)
    },
    //删除专利数据库
    deletePatentProject(ids) {
      this.$confirm('此操作将删除该产品类别, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.deletePatentProject(ids).then(response => {
          if (response.code == 200) {
            this.handleMessage = '删除成功'
            this.$message.success('删除成功!');
            if (!this.group) {
              this.getList()
            }
            this.clearMessage()
          }
        })
      })

    },
    //编辑专利数据库
    handleEdit(row) {
      this.$refs.projectFormDrawer.open(JSON.parse(JSON.stringify(row)), '编辑专利数据库')
    },
    
  },
};
</script>
<style lang="scss" scoped></style>
<style lang="scss">
.workspace {
  .workspace-card {
    min-height: calc(100% - 3px);

    // padding-bottom: 15px;
    .workspace-main {
      padding-top: 10px;
      width: 100%;
    }

    .el-card__body {
      height: 100%;
    }
  }

  .nopadding .el-card__body {
    padding: 0 !important;
  }

  .query-top {
    border-bottom: 1px solid #bbb;
    padding-bottom: 10px;

    .el-collapse {
      border-bottom: 0 !important;
      border-top: 0 !important;

      .el-collapse-item__wrap,
      .el-collapse-item__header {
        border-bottom: 0 !important;
      }

      .el-collapse-item__header {
        padding-left: 15px;
        font-weight: bold;
      }

      .is-active .el-collapse-item__wrap {
        border-top: 1px solid #bbb;
      }
    }

    .chart-box {
      height: 250px;
    }
  }
}
</style>
