<template>
  <div class="app-container" v-loading="state.loading">
    <el-card class="search-container" v-if="!props.hideSearch">
      <el-form :inline="true" v-auth="props.apiName + state.searchBtnOptions['search'].auth">
        <el-form-item 
          v-for="(item,index) in props.searchOptions"
          :key="index"
          :label="item.label">
          <!-- 文本 -->
          <el-input 
            v-if="item.type == 'input'"
            v-model="props.searchFilter[item.prop]" 
            :placeholder="item.label" 
            :clearable="!item.noClear"
          />
          <!-- 数字 -->
          <el-input-number 
            v-if="item.type == 'number'"
            v-model="props.searchFilter[item.prop]" 
            :min="item.min" 
            :max="item.max" 
          />
          <!-- 时间区域 -->
          <el-date-picker
            v-if="item.type == 'datetimerange'"
            v-model="props.searchFilter[item.prop]"
            type="datetimerange"
            start-placeholder="起始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
          <!-- 选择框 -->
          <el-select
            v-if="item.type == 'select'"
            v-model="props.searchFilter[item.prop]"
            :filterable="!item.noSearch"
            placeholder="请选择"
            style="width: 240px"
            :clearable="!item.noClear"
          >
            <el-option
              v-for="(op,op_index) in item.options"
              :key="op_index"
              :label="op.label"
              :value="op.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            v-for="(btn,btn_key) in props.searchButtons"
            :key="btn_key"
            :icon="state.searchBtnOptions[btn].icon"
            v-auth="state.searchBtnOptions[btn].sAuth || props.apiName + state.searchBtnOptions[btn].auth"
            :type="state.searchBtnOptions[btn].type"
            @click="searchBtnHandle(btn)"
          >{{state.searchBtnOptions[btn].label}}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="paged-table-container">
      <elTable 
        :columnWidth="props.columnWidth"
        :columnHeaderAlign="props.columnHeaderAlign"
        :columnAlign="props.columnAlign"
        :tableData="state.tableData"
        :tableColumns="getTableColumns()"
        @sortChange="sortChange"
        :leftOperation="props.leftOperation"
        @leftOperationHadel="leftOperationHadel"
      ></elTable>

      <elPager
        style="margin-top: 15px;float:right"
        :pager="state.pager"
        @pageSizeChange="pageSizeChange"
        @pageCurrentChange="pageCurrentChange"
      ></elPager>
    </el-card>

    <!-- 导入弹窗 -->
    <importPop 
      ref="importPopRef" 
      :apiName="props.apiName"
      @success="importSuccess"
    />
  </div>
</template>
  
<script setup>
  defineOptions({ name: 'tablePage' })
  import apiTableColumns from '@/utils/common/apiTableColumns'
  import { reactive, ref, onMounted } from 'vue'
  import { getCommonPaged,postCommonExport } from '@/api/common/index'
  import { ElMessageBox, ElMessage,ElTable, ElTableColumn } from 'element-plus'
  import elTable from '@/components/elTable/index.vue'
  import elPager from '@/components/elPager/index.vue'
  import { getPageParamsForFilter } from '@/utils/common/index'
  import { downloadByData } from '@/utils/download'
  import importPop from '@/components/importPop/index.vue'

  import { useRoute } from 'vue-router'
  const route = useRoute()
  
  const state = reactive({
    loading:false,
    searchBtnOptions:{
      search:{icon:'Search',auth:':page',label:'查询',type:null},
      import:{icon:'BottomRight',auth:':import',label:'导入',type:'warning'},
      export:{icon:'TopRight',auth:':export',label:'导出',type:'success'},
    },
    tableData:[],
    // table排序处理
    sortFilter:{
      sortBy:undefined,
      isAscending:undefined
    },
    pager:{
      page: 1,
      pageSize: 10,
      total: 1,
    }
  })

  const props = defineProps({
    // api名称
    apiName: {
      type: String,
      default: null
    },
    // 隐藏表头搜索
    hideSearch:{
      type: Boolean,
      default: false
    },
    // 左侧操作列
    leftOperation:{
      type: Object,
      default: null
    },
    // table表头
    tableColumns: {
      type: Object,
      default: null
    },
    // 查询配置
    searchOptions: {
      type: Object,
      default: []
    },
    // 查询按钮
    searchButtons: {
      type: Object,
      default: ['search','import','export']
    },
    // table查询数据filter
    searchFilter: {
      type: Object,
      default: {}
    },
    // 表头宽度
    columnWidth:{
      type: Number,
      default: 120
    },
    // 表头对齐
    columnHeaderAlign:{
      type: String,
      default: 'center'
    },
    // 表内容对齐
    columnAlign:{
      type: String,
      default: 'center'
    },
  })
  
  // 获取表头
  function getTableColumns(){
    return props.tableColumns || apiTableColumns[props.apiName]
  }

  const emits = defineEmits(['leftOperationHadel'])
  // 左侧操作列
  function leftOperationHadel(btn,scope) {
    emits('leftOperationHadel',btn,scope)
  }

  // 格式化页面传参
  function getPageParams(){
    let _filters = []
    for(let i in props.searchFilter){
      let _item = props.searchOptions.filter(item=>item.prop == i)
      let _type = (_item && _item.length > 0) ? _item[0].type : null
      if(props.searchFilter[i] || props.searchFilter[i] == 0){
        // 时间区域格式
        if(_type == 'datetimerange'){
          _filters.push(
            {
              logic: "And",
              column: i,
              action: '>=',
              value: props.searchFilter[i][0]
            }
          )
          _filters.push(
            {
              logic: "And",
              column: i,
              action: '<=',
              value: props.searchFilter[i][1]
            }
          )
        }else{
          let _action = 'like'
          let _EqualTypes = ['tagFilter','number','select']//等于情况的类型
          if(_EqualTypes.indexOf(_type) >= 0){
            _action =  '=='
          }
          _filters.push(
            {
              logic: "And",
              column: i,
              action: _action,
              value: props.searchFilter[i]
            }
          )
        }
      }
    }
    let _pageParams = getPageParamsForFilter({
      pageNumber:state.pager.page,
      pageSize:state.pager.pageSize,
      sortBy:state.sortFilter.sortBy,
      isAscending:state.sortFilter.isAscending,
      condition:{
        filters:_filters
      }
    })
    return _pageParams
  }

  // 获取页面数据
  function getTableData(page) {
    state.loading = true
    if(!page)page = state.pager.page
    if(page)state.pager.page = page
    getCommonPaged(props.apiName,getPageParams())
      .then((resp) => {
        state.tableData = resp.data.data
        state.pager.total = resp.data.totalCount
      })
      .finally(() => (state.loading = false))
  }

  const importPopRef = ref()
  // 按钮功能
  function searchBtnHandle(btn){
    console.log(btn)
    // 查询
    if(btn == 'search'){
      getTableData()
    }
    // 导入
    else if (btn == 'import'){
      importPopRef.value.open()
    }
    // 导出
    else if (btn == 'export'){
      state.loading = true
      getTableData()//同步数据查询
      postCommonExport(props.apiName,getPageParams())
        .then((res) => {
          downloadByData(res.data,route.meta.title+'.xlsx')
        })
        .finally(() => (state.loading = false))
    }
  }

  // 排序
  function sortChange(data) {
    const { prop, order } = data;
    if (!prop || !order) {
      state.sortFilter.sortBy = undefined;
      state.sortFilter.isAscending = undefined;
      getTableData(1);
      return;
    }
    state.sortFilter.sortBy = prop;
    state.sortFilter.isAscending = (order == "ascending");
    getTableData(1);
  }
  
  // 导入成功之后todo
  function importSuccess(response,importDate){
    getTableData()
  }
  
  // size-change
  function pageSizeChange(page){
    getTableData(page)
  }

  // current-change
  function pageCurrentChange(page){
    getTableData(page)
  }

  onMounted(() => {
    getTableData()
  })
  </script>