<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 v-if="[2].indexOf(isOperate) == -1" id="step2">
            <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; margin-left: 10px;" v-if="[2].indexOf(isOperate) == -1">
            <el-button size="small" :type="viewSelectedBtn === 'visual' ? 'primary' : ''" @click="onChange2('visual')">可视化</el-button>
            <el-button :type="viewSelectedBtn === 'Table' ? 'primary' : ''" @click="onChange2('Table')" size="small">列表</el-button>
            <el-button :type="viewSelectedBtn === 'Card' ? 'primary' : ''" @click="onChange2('Card')" size="small">卡片</el-button>
          </el-button-group>
          <!-- <el-button type="primary" size="small" style="margin: 0 10px;" @click="handleCommand('1')">添加事件</el-button> -->
          <el-dropdown id="step4" trigger="click" split-button type="primary" size="small" @command="handleCommand($event)">
            <span @click="handleCommand('1')">添加事件</span>
            <el-dropdown-menu slot="dropdown" class="text-align_center">
              <el-dropdown-item command="3">显示栏位管理</el-dropdown-item>
              <!-- <el-dropdown-item command="2">批量添加事件</el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-header>
      <el-main id="patent-list-container" class="main" v-loading="loading">
        <div class="height_100">
          <component
            v-if="showView"
            ref="questionViewList"
            :is="viewSelected"
            v-bind="$attrs" 
            v-on="$listeners" 
            :isOperate="isOperate"
            :queryParams="queryParams"
            :tableData="tableData"
            :column="columnList"
            :commonData="commonData"
            @on-sort="handleSort"
            @option="handleOption"
            :groupBy='groupingValue'
            :groupingOption="groupingOption"
            :searchOption="searchOption"
            :sign="true"
            :scenarioName="scenarioName"
            @toFlowPath="toFlowPath"
            :handleMessage="handleMessage"
          ></component>
        </div>
      </el-main>
      <el-footer class="pagination" v-if="viewSelectedBtn != 'visual'">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page.sync="queryParams.current"
          :page-size.sync="queryParams.size"
          @current-change="handleCurrentChange"
          @size-change="getList()"
          :total="total"
        >
        </el-pagination>
      </el-footer>
    </el-container>

    <addEvent ref="addEvent"  @isSuccess="handleSuccess"></addEvent>
    <fields ref="field" type="event" @getFieldList="getFieldList"></fields>
  </div>
</template>

<script>
import Table from './view/table.vue'
import Card from './view/card.vue'
import visual from '@/views/visual/components/sceneSVG.vue';
import flowPath from '@/views/visual/title/index.vue'
import mergeTable from './view/mergeTable.vue';
import addEvent from './dialog/addEvent.vue';
import fields from '@/views/components/dialog/fields.vue';
export default {
  components: {
    Table,
    Card,
    visual,
    flowPath,
    mergeTable,
    addEvent,
    fields
  },
  props: {
    eventName:'',
    scenarioId:null,
    isOperate:''
  },
  data() {
    return {
      //检索字段
      searchFiled: [],
      //检索条件
      searchOption: {
        scenarioNames:this.scenarioId || (localStorage.scenarioName?[Number(localStorage.scenarioName)]:''),
        name:this.eventName || localStorage.searchContent
      },
      //分组的值
      groupingValue: '',
      //分组
      groupingOption: [],
      // 当前显示的视图
      viewSelected: 'Table',
      // 三种视图底色
      viewSelectedBtn:'Table',
      //加载中
      loading: false,
      //事件的数据集合
      tableData: [],
      //分页信息
      queryParams: {
        current: 1,
        size: 10
      },
      //总条数
      total: 0,
      //排序
      sort: [
        {
          "orderBy": "createTime",
          "orderType": 1
        }
      ],
      //显示栏位
      columnList: null,
      //分组数据
      commonData: [],
      //显示视图
      showView: false,
      //操作回馈
      handleMessage:'',
      //应用场景名称
      scenarioName:''
    };
  },
  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
    }
  },
  created() { },
  async mounted() {
    this.columnList = await this.$commonJS.getCustomField('event')
    //获取table栏位及分组字段
    await this.getColumn()
    this.getList()
  },
  methods: {
    //打开应用场景处理流程界面
    toFlowPath(title){
      this.scenarioName = title
      this.viewSelected = 'flowPath'
    },
    //显示栏位管理
    getFieldList(data){
      this.columnList = data
    },
    // 子组件新增事件成功
    handleSuccess(val) {
      this.handleMessage = val
      this.queryParams.current = 1
      this.isGrouping()
      this.clearMessage()
    },
    //清空信息
    clearMessage(){
      this.$emit('submit',true)
      this.$nextTick(()=>{
        this.handleMessage = ''
      })
    },
    //显示视图?
    showViews() {
      this.showView = false
      this.$nextTick(() => {
        this.showView = true
      })
    },
    //获取table栏位及分组字段、检索字段
    async getColumn() {
      let params = ['event']
      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
              }
            })
          }
        }
      })
      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()
    },
  
    // 分页
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.isGrouping()
    },

    //查询事件数据
    getList() {
      let params = {
        ...this.queryParams,//分页信息
        searchQuery:this.$commonJS.objectToString(this.searchOption || {}),//检索条件
        orderDTOList: this.sort,//排序
      }
      this.$api.queryEvent(params).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.data
          if (!this.groupingValue) {
            this.total=res.data.total
          }
        }
      }).catch(err => {
        this.tableData = []
        this.total=0
      })
    },

    //切换分组值
    changeGrouping(val) {
      if (val!='') {
        this.viewSelected='mergeTable'
      } else {
        this.viewSelected='Table'
      }
      this.queryParams.current = 1
      this.groupingValue=val
      this.isGrouping()
    },
    // 调用分组查询的方法
    getGrouping() {
      console.log(this.sort)
      let params = {
        ...this.queryParams,//分页信息
        searchQuery:this.$commonJS.objectToString(this.searchOption || {}),//检索条件
        orderDTOList:[
          {
            orderBy:this.groupingValue,
            orderType:this.sort[0].orderType
          }
        ],//排序
        groupBy:this.groupingValue,//分组信息
      }
      this.$api.groupEvent(params).then(res => {
        if (res.code == 200) {
          this.commonData=res.data.data.values
          this.total=res.data.total
        }
      }).catch(err => {
        this.commonData = []
        this.total=0
      })
    },

    //切换视图
    onChange2(type) {
      this.viewSelected = type
      this.viewSelectedBtn = type
      this.groupingValue=''
      this.queryParams.current=1
      this.getList()
    },

    //新增事件的选项(1是添加单个事件，2是批量添加)
    handleCommand(e) {
      switch(e){
        case '1'://添加单个事件
          var form = {
            scenarioId : this.scenarioId
          }
          this.$refs.addEvent.open(form, e)
          break;
        case '3'://显示栏位管理
          this.$refs.field.open(this.columnList)
          break;
      }
    },

    //获取排序字段// 子组件table排序
    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()
      }
    },
    // 区分是否为分组
    isGrouping() {
      if (this.groupingValue != '') {//分组
        this.getGrouping()
      } else {//不分组
        this.getList()
      }
    },
    //表格操作列(option为操作类型，row为当前行数据，type为报告类型，单件事件弹窗为1)
    handleOption({ option, row, type,isLast }) {
      switch (option) {
        case '0'://新增专利数据库
          break;
        case 'addReport'://新增报告
          break;
        case '10'://删除
          this.eventDelete(row,isLast)
          break;
        case 'cancel'://取消关联
          break;
        case 'edit'://编辑事件，打开单件事件弹窗,1代表单个事件弹窗
          this.$refs.addEvent.open(row, 1)
          break;
      }
    },
    // 删除事件
    eventDelete(row,isLast) {
      this.eventDeletes([row.id],isLast)
    },
    // 批量删除事件
    eventDeletes(ids,isLast) {
      this.$confirm('此操作将删除该事件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.deleteEvent(ids).then(res => {
          if (res.code == 200) {
            if(isLast){
              this.isGrouping()
            } else {
              this.getList()
            }
            this.handleMessage = '删除成功'
            this.clearMessage()
            this.$message.success('删除成功!');
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
  },
};
</script>
<style lang="scss" scoped></style>