<template>
  <div class="app-container" v-loading="state.loading">
    <el-card class="search-container" v-if="!props.hideSearch">
      <el-form :inline="true">
        <el-form-item 
          v-auth="props.apiName + state.searchBtnOptions['search'].auth"
          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"
        :rightOperation="getRightOperation()"
        @rightOperationHadel="rightOperationHadel"
        :multipleTable="props.multipleTable"
        @tableSelectionHandle="tableSelectionHandle"
      ></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"
    />

    <!-- 编辑弹窗 -->
    <apiEditPop 
      ref="apiEditPopRef" 
      :apiName="props.apiName"
      @submitEditForm="submitEditForm"
      :formRules="props.apiEditFormRules"
    />
  </div>
</template>
  
<script setup>
  defineOptions({ name: 'tablePage' })
  import store from '@/stores'
  import apiTableColumns from '@/utils/common/apiTableColumns'
  import { reactive, ref, onMounted,computed } from 'vue'
  import { 
    getCommonPaged,
    getCommonDeatailPaged,
    postCommonExport,
    putCommonUpdate,
    getCommonCustominvoke 
  } 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 apiEditPop from '@/components/apiEditPop/index.vue'
  import { formatDate } from '@/utils/formatTime'
  import apiServeNames from '@/utils/common/apiServeNames'

  import { useRoute } from 'vue-router'
  const route = useRoute()
  const userStore = store.userStore()
  const userInfo = userStore.state

  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'},
      custominvoke:{icon:'Position',auth:':custominvoke',label:'手动传出',type:'primary'},
    },
    tableData:[],
    // table排序处理
    sortFilter:{
      sortBy:undefined,
      isAscending:undefined
    },
    pager:{
      page: 1,
      pageSize: 10,
      total: 1,
    },
    tableSelectList:[]
  })

  const props = defineProps({
    // api名称
    apiName: {
      type: String,
      default: null
    },
    // api类型 detailApi：走getdetail接口，不传或者pageApi：走getdatapaged接口
    apiType: {
      type: String,
      default: null
    },
    // 隐藏表头搜索
    hideSearch:{
      type: Boolean,
      default: false
    },
    // 多选
    multipleTable:{
      type: Boolean,
      default: false
    },
    // 左侧操作列
    leftOperation:{
      type: Object,
      default: null
    },
    // 右侧操作列
    rightOperation:{
      type: [Object,String],
      default: null
    },
    // 右侧操作列，特殊自定义格式下，包含api操作
    showApiRightOperation:{
      type: Object,
      default: null
    },
    // table表头
    tableColumns: {
      type: Object,
      default: null
    },
    // 查询配置
    searchOptions: {
      type: Object,
      default: []
    },
    // 查询按钮
    searchButtons: {
      type: Object,
      default: ['search','export']
    },
    // table查询数据filter
    searchFilter: {
      type: Object,
      default: {}
    },
    // 表头宽度
    columnWidth:{
      type: Number,
      default: 120
    },
    // 表头对齐
    columnHeaderAlign:{
      type: String,
      default: 'center'
    },
    // 表内容对齐
    columnAlign:{
      type: String,
      default: 'center'
    },
    // 表单规则
    apiEditFormRules:{
      type: Object,
      default: null
    }
  })
  
  // 获取表头
  function getTableColumns(){
    return props.tableColumns || apiTableColumns[props.apiName]
  }

  const emits = defineEmits([
    'leftOperationHadel',
    'rightOperationHadel',
    'tableSelectionHandle'
  ])

  // table多选
  function tableSelectionHandle (val){
    state.tableSelectList = val
    emits('tableSelectionHandle',val)
  }

  // 左侧操作列
  function leftOperationHadel(btn,scope) {
    emits('leftOperationHadel',btn,scope)
  }

  // 获取右侧操作列
  function getRightOperation() {
    // 自定义右侧列，且不需要默认api通用操作
    if(typeof props.rightOperation == 'object' && !props.showApiRightOperation){
      return props.rightOperation
    }
    // 无自定义操作，或者有自定义且需要默认api操作
    else if(
      (typeof props.rightOperation == 'object' && props.showApiRightOperation)
      || typeof props.rightOperation == 'string'
    ){
      // 格式化默认api按钮合集
      let _apiArr = props.showApiRightOperation || props.rightOperation.split(',')
      let _config = {
        apiUpdate:{label:'编辑',type:'warning'},
      }
      let _btns = []
      if(_apiArr && _apiArr.length > 0){
        _apiArr.forEach(item => {
          _btns.push({label:_config[item].label,name:item,link:true,type:_config[item].type,auth:props.apiName+':'+item})
        });
      }
      // 如果有自定义按钮，合并默认api按钮
      if(typeof props.rightOperation == 'object'){
        _btns = [..._btns,...props.rightOperation]
      }
      return _btns
    }
  }

  // 右侧操作列操作
  const apiEditPopRef = ref()
  function rightOperationHadel(btn,scope) {
    // 通用编辑
    if(btn.name == 'apiUpdate'){
      let _tableColums = getTableColumns()
      let _list = _tableColums.filter(item => !item.noEdit)
      apiEditPopRef.value.open(_list,scope.row)
    }
    emits('rightOperationHadel',btn,scope)
  }

  // 编辑表单提交   todo:putCommonUpdate接口有问题
  const submitEditForm = async (formData,formConfig) => {
    apiEditPopRef.value.validate((valid) => {
      if(valid){
        // 修改人信息处理
        if(
            (formData.hasOwnProperty('updateByUser') && formData.hasOwnProperty('updateTime'))
            || (formData.hasOwnProperty('updateUser') && formData.hasOwnProperty('updateTime'))
        ){
          if(formData.hasOwnProperty('updateByUser')){formData.updateByUser = userInfo.realName}
          if(formData.hasOwnProperty('updateUser')){formData.updateUser = userInfo.realName}
          if(formData.hasOwnProperty('updateTime')){formData.updateTime = formatDate(new Date(), "YYYY-mm-dd HH:MM:SS")}
        }else{
          // 特殊不处理页面
          let _notChange=['taskconifgure']
          if(_notChange.indexOf(props.apiName) < 0){
            formData.remark= `修改信息：${userInfo.realName} ${formatDate(new Date(), "YYYY-mm-dd HH:MM:SS")}`
          }
        }
        apiEditPopRef.value.changeLoading(true)
        putCommonUpdate(props.apiName,formData)
        .then(res=>{
          apiEditPopRef.value.close()
          ElMessage.success('操作成功！')      
          getTableData(1);
        })
        .finally(()=>{apiEditPopRef.value.changeLoading(false)})
      }
    })
  }

  // 格式化页面传参
  function getPageParams(){
    let _filters = []
    if(props.hideSearch){
      _filters = props.searchFilter
    }else{
      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','filter','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) {
    if(props.apiType == 'detailApi'){
      state.loading = true
      if(!page)page = state.pager.page
      if(page)state.pager.page = page
      getCommonDeatailPaged(props.apiName,getPageParams())
        .then((resp) => {
          state.tableData = resp.data.data
          state.pager.total = resp.data.totalCount
        })
        .finally(() => (state.loading = false))
    }else{
      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))
    }
    // 手动传出（直接调接口）
    else if (btn == 'custominvoke'){
      ElMessageBox.confirm('是否确定手动传出？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        state.loading = true
        let _data = {
          taskName:apiServeNames[props.apiName].taskName,
          client:'Chery'
        }
        getCommonCustominvoke(props.apiName,_data)
        .then((res) => {
          ElMessage.success('操作成功！')    
          getTableData(1)//同步数据查询
        })
        .finally(() => (state.loading = false))
      })
    }
    // todo:手动传出（多选）
    else if (btn == 'custominvokeMany'){
      console.log(state.tableSelectList)
      if(state.tableSelectList && state.tableSelectList.length > 0 ){
        ElMessageBox.confirm('是否确定手动传出？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // state.loading = true
          // deleteMenu({ ids:[id] }).then(() => {
            
          // })
          // .finally(() => (state.loading = false))
        })
      }else{
        ElMessage.warning('未选中任何数据')        
      }
    }
  }

  // 排序
  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(pageSize){
    state.pager.pageSize = pageSize
    getTableData(1)
  }

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

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