<template>
  <div class="patentMiningIndex">
    <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 id="step3" class="margin-left_10" v-if="[2].indexOf(isOperate) == -1">
            <el-button :type="viewTypeBtn === 'commonTable' ? 'primary' : ''" @click="onChange2('commonTable')"
              size="small">列表</el-button>
            <el-button :type="viewTypeBtn === 'commonCard' ? 'primary' : ''" @click="onChange2('commonCard')"
              size="small">卡片</el-button>
          </el-button-group>
          <el-dropdown id="step4" trigger="click" split-button type="primary" size="small" @command="handleCommand($event)">
            <span @click="handleAdd">创建项目</span>
            <el-dropdown-menu slot="dropdown" class="text-align_center">
              <el-dropdown-item command="0">显示栏位管理</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-header>
      <el-main>
        <component v-if="showView" :is="viewType" v-bind="$attrs" v-on="$listeners" :isOperate="isOperate" :tableData="dataList"
          :column="columnList" :groupingOption="groupingOption" :groupBy="group" :queryParams="queryParams" @option="handleOption" @on-sort="handleSort"
          :commandData="commandData" :searchOption="searchOption" :handleMessage="handleMessage">
        </component>
      </el-main>
      <el-footer class="pagination">
        <div>
          <el-pagination background layout="total, prev, pager, next, jumper" :current-page.sync="queryParams.current"
            :page-size.sync="queryParams.size" @current-change="handleCurrentChange" :total="total">
          </el-pagination>
        </div>
      </el-footer>
    </el-container>
    <addAndEditProject ref="addAndEditProject" @isSuccess="isSuccess"></addAndEditProject>
    <fields ref="field" type="patentDigProject" @getFieldList="getFieldList"></fields>
  </div>
</template>
  
<script>
import commonTable from './view/commonTable.vue';
import commonCard from './view/card.vue';
import addAndEditProject from './dialog/addAndEditProject.vue';
import fields from '@/views/components/dialog/fields.vue';
import mergeTable from '../components/view/MergeTable.vue'
export default {
  components: {
    commonTable,
    addAndEditProject,
    fields,
    mergeTable,
    commonCard,
  },
  props: {
    isOperate: '',
    matterId:{},
    scenarioId:{},
    eventName:'',
    eventId:''
  },
  data() {
    return {
      //当前组件名称
      viewType: 'commonTable',
      // 当前按钮的底色
      viewTypeBtn:'commonTable',
      //专利挖掘项目table数据集合
      dataList: [],
      // 专利挖掘分组项目数据数组
      commandData:[],
      //分页
      queryParams: {
        size: 10,
        current: 1,
      },
      //当前分组的值
      group: '',
      // 分组字段数组
      groupingOption: [],
      //排序
      sort: [{ "orderBy": "createTime", "orderType": 1 }],
      //总数
      total: 0,
      //检索字段
      searchFiled: [
        {
          label: '项目名称',
          value: 'name',
          type: 1,
          placeholder: '请输入项目名称'
        },
        {
          label: '创建人',
          value: 'createPerson',
          type: 1,
          placeholder: '请输入创建人名称'
        },
      ],
      //检索条件
      searchOption: {
        scenarioNames:this.scenarioId,
        matterNames:this.matterId,
        name:localStorage.searchContent,
        eventNames:this.eventName
      },
      // table栏位信息
      columnList: [],
      //显示视图
      showView: false,
      // 子组件添加/更新项目返回的值
      handleMessage:'',
    };
  },
  watch: {},
  computed: {
    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('patentDigProject')
    //获取检索、分组字段
    await this.getColumn()
    // 获取table数据
    this.getList()
    this.showViews()
  },
  methods: {
    //显示视图?
    showViews() {
      this.showView = false
      this.$nextTick(() => {
        this.showView = true
      })
    },
    //显示栏位管理
    getFieldList(data) {
      this.columnList = data
    },
    // 获取检索及分组栏位
    async getColumn() {
      let params = ['patentDigProject']
      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',
          })
           //为应用场景添加选项
           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()
    },
    // 新增、编辑成功信息
    isSuccess(val) {
      this.handleMessage = val
      this.queryParams.current = 1
      this.isGrouping()
      this.clearMessage()
    },
    clearMessage() {
      this.$emit('submit',true)
      this.$nextTick(() => {
        this.handleMessage = ''
      })
    },
    //获取检索组件传过来的数据
    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()
    },
    //排序
    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();
    },
    //获取专利挖掘项目数据列表
    getList() {
      let params = {
        ...this.queryParams,//分页信息
        searchQuery: this.$commonJS.objectToString(this.searchOption || {}),//检索条件
        orderDTOList: this.sort,//排序
      }
      this.$api.queryPatentDigProject(params).then(res => {
        if (res.code == 200) {
          this.dataList = res.data.data
          this.total = res.data.total
        }
      }).catch(error => {
        this.dataList = []
        this.total = 0
        this.$message.error(error.message)
      })
    },
    // 获取分组数据
    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.groupPatentDigProject(params).then(response => {
        this.commandData = response.data.data.values
        this.total = response.data.total
        this.loading = false
      }).catch(error => {
        this.commandData = []
        this.total = 0
        this.loading = false
      })
    },
    //创建项目按钮，添加其他企业专利数据库
    handleAdd() {
      var form = {
        matterIds:this.matterId || [],
        scenarioIds:this.scenarioId || [],
        eventName:this.eventName,
        eventId:this.eventId
      }
      this.$refs.addAndEditProject.open()
    },
    // 创建项目按钮下拉菜单内容
    handleCommand(ev) {
      switch (ev) {
        case '0'://显示栏位管理
          this.$refs.field.open(this.columnList)
          break;

        default:
          break;
      }
    },
    //切换到分组
    onChange(val) {
      if (val != '') {
        this.viewType = 'mergeTable'
      } else {
        this.viewType = 'commonTable'
      }
      this.group = val
      this.queryParams.current = 1
      this.queryParams.size = 10
      this.isGrouping()//区分是否分组，调用不同请求数据
    },
    // 区分是否为分组
    isGrouping() {
      if (this.group != '') {//分组
        this.getGrouping()
      } else {//不分组
        this.getList()
      }
    },
    //切换视图
    onChange2(val) {
      this.viewType = val
      this.viewTypeBtn=val
      this.group=''
      this.queryParams.current = 1
      this.getList()
    },
    //操作列
    handleOption({ option, row ,isLast}) {
      switch (option) {
        case '0'://设置定时任务
          // this.$refs.addAndEditDB.open(row, true)
          break;
        case '1'://删除
          this.projectDelete(row,isLast)
          break;
        case 'e'://编辑
          this.$refs.addAndEditProject.open(row)
          break;
      }
    },
    // 删除项目
    projectDelete(row,isLast) {
      this.projectDeletes([row.id],isLast)
    },
    // 删除项目
    projectDeletes(ids, isLast) {
      this.$confirm('此操作将删除该项目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.deletePatentDigProject(ids).then(res => {
          if (res.code == 200) {
            this.handleMessage = '删除成功'
            if(isLast){
              this.isGrouping()
            }else{
              this.getList()
            }
            this.clearMessage()
            this.$message.success('删除成功!');
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.patentMiningIndex {
  height: 100%;
}
</style>