<template>
  <div class="height_100">
    <el-container>
      <el-header>
        <div>
          <mySearch style="width: 500px" :SearchFields="searchFiled" @search="search" :searchValue="searchOption">
          </mySearch>
        </div>
        <div style="display: flex">
          <div v-if="[2].indexOf(isOperate) == -1">
            <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 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 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"
            :handleMessage="handleMessage"
          ></component>
        </div>
      </el-main>
      <el-footer class="pagination">
        <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 mergeTable from './view/mergeTable.vue';
import addEvent from './dialog/addEvent.vue';
import fields from '@/views/components/dialog/fields.vue';
export default {
  components: {
    Table,
    Card,
    mergeTable,
    addEvent,
    fields
  },
  props: {
    eventName:'',
    applicationScenario:null,
    isOperate:''
  },
  data() {
    return {
      //检索字段
      searchFiled: [],
      //检索条件
      searchOption: {
        // name: this.eventName,
        // applicationScenario: this.applicationScenario
      },
      //分组的值
      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:'',
    };
  },
  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: {
    //显示栏位管理
    getFieldList(data){
      this.columnList = data
    },
    // 子组件新增事件成功
    handleSuccess(val) {
      this.handleMessage = val
      this.queryParams.current = 1
      this.searchOption.searchQuery=''
      // this.getList()
      this.isGrouping()
      this.clearMessage()
    },
    //清空信息
    clearMessage(){
      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) {
          // 显示栏位
          // this.columnList = res.data[0].conditionDTOList.filter(item => {
          //   return item.name != 'Id' && item.ifShow == true
          // })
          // 分组字段
          let conditionDTOList= JSON.parse(JSON.stringify(res.data[0].conditionDTOList))
          // this.groupingOption = conditionDTOList.filter(item => {
          //   return item.ifGroup == true
          // })
          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.searchQuery=params
      // this.searchOption.searchQuery=this.$commonJS.objectToString(params)
      // 调用查询接口
      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.searchQuery || {}),//检索条件
        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() {
      let params = {
        ...this.queryParams,//分页信息
        // ...this.searchOption,//检索信息
        orderDTOList:this.sort,//排序
        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'://添加单个事件
          this.$refs.addEvent.open(null, e)
          break;
        case '3'://显示栏位管理
          this.$refs.field.open(this.columnList)
          break;
      }
    },

    //获取排序字段// 子组件table排序
    handleSort({ column, prop, order, str }) {
      this.sort=[]//如需要多个字段排序，则不需要清空
      if (order == 'null') {
        return;
      }
      var orderType = {
        ascending: 0,
        descending:1
      }
      var params = this.sort.find(item => {
        return item.orderBy == prop
      })
      if (params) {
        params.orderType = orderType[order]
      } else {
        params = {}
        params.orderBy = prop
        params.orderType = orderType[order]
        this.sort.push(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.$confirm('此操作将删除该事件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用接口
        let params = [ row.id ]
        this.$api.deleteEvent(params).then(res => {
          if (res.code == 200) {
            this.getList()
            if(isLast){
              this.isGrouping()
            }
            this.handleMessage = '删除成功'
            this.clearMessage()
            this.$message.success('删除成功!');
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
  },
};
</script>
<style lang="scss" scoped></style>