<template>
  <!--  <a-spin size="small" :spinning="spinning">-->
  <!--  不用props.也可以-->
  <a-layout style="height: 100%" :class="'lt-common-table-remote-'+state.tableClass">
    <a-layout-content style="height: 100%" >
      <Card
          style="padding: 0px; height: 100%"
          :body-style="{
            padding: '0px',

            height:'100%'
          }"
      >
        <lt-a-table
            v-if="state.isShowTable"
            style="height: 100%"
            ref="ltTableRemoteRef"
            size="small"
            bordered
            :columns="showCols"
            :url="state.url"
            :columnFilter="columnFilter"
            :remoteQueryMode="state.remoteQueryMode"
            :dataName="state.dataName"
            :showIndex="state.showIndex"
            :is-auto-editable="state.isAutoEdit"
            :rowSelection="localShowSelection"
            :showEditInDialog="state.showEditInDialog"
            :ellipsis="state.ellipsis"
            :searchBox="state.searchBox"
            :row-key="state.rowKey"
            :queryParams="state.queryParams"
            :pagination="state.pagination"
            :showToolBar="state.showToolBar"
            :scroll="props.scroll"
            :selectTypeAfterload="state.selectTypeAfterload"
            :dataFilter="state.dataFilter"
            @row-click="handleClick"
            @row-dblclick="handleDblclick"
            @loadSuccess="handleLoadSuccess"
            @edit-in-dlg="handleEditInDlg"
            @get-query-data="handleGetQueryData"
        >
          <template #headerCell="{ column }">
            <template v-if="column.key==='ACTION'">
              <div v-if="state.operateBtnOption?.headBtnOption?.ifShow">
                <i
                    v-for="(item,index) in state.operateBtnOption.headBtnOption.btnOption"
                    :key='index'
                    :title="item.title?item.title:(locale.value === 'zh' ? item.zhTitle : item.endTitle)"
                    :class="item.icon"
                    :style="{'color': item.color?item.color:'#388ef4', marginLeft: state.operateBtnOption.headBtnOption.mLeft + 'px'}"
                    @click="item.clickEvent"></i>
              </div>
              <span v-else>{{ t("Formula.Common.Operate") }}</span>
            </template>
          </template>
        </lt-a-table>
      </Card>
    </a-layout-content>
  </a-layout>
  <!--  </a-spin>-->
</template>

<script setup lang="tsx">
import {ref, PropType, onMounted, computed, unref, reactive, onBeforeMount, nextTick} from "vue"
import {UseFormatShowCols} from "./cols"
import {checkNull,GuidID} from "../../commonMethods/commonMethods";
import {useI18n} from "vue-i18n";
import {cloneDeep} from "lodash-es"
import {ColInter, ColumnFilterItemInter} from "@/utils/common-type";
import $ from "jquery";
import {Card} from "ant-design-vue";

const {t} = useI18n()
const {locale} = useI18n()

const props = defineProps({
  /*tableClass:{
    type:String,
    default:''
  },*/
  rowSelection: {
    type: Object || Boolean
  },
  //提交数据格式化
  formatShowSaveFun: Function,
  scroll: {
    type: Object,
    default() {
      return {x: '100%', y: '200px'}
    }
  },
  tableParams: {
    type: Object,
    default() {
      return {
        selectedRowKeys: [],
        selectData: null,
        selectionData: [],
        isShowTextOperate: false,
        isShowIconOperate: false,
        saveUrl: "",

        columnFilter: [] as ColumnFilterItemInter[] | string[],
        columns: [] as any[],
        url: '',
        isAutoEdit: false,
        remoteQueryMode: 2,
        dataName: 'Datas',
        showIndex: true,
        showEditInDialog: false,
        ellipsis: true,
        rowKey: "",
        pagination: {
          pageSize: 25,
          hideOnSinglePage: false
        },
        showToolBar: false,
        queryParams: {} as any,
        searchBox: false,
        operateBtnOption:{
          headBtnOption:{
            ifShow:false,
            btnOption: [
              {
                visible: true,
                zhTitle: '新增',
                enTitle: 'add',
                icon: "fa fa-plus",
                clickEvent: ()=>{},
                customVisible: ((row) => {
                  return true
                })
              }
            ]
          },
          rowBtnOption:{
            ifShow:false,
            btnBaseWidth: 70,
            btnNum: 3,
            btnOption: [
              {
                visible: true,
                zhTitle: '复制',
                enTitle: 'add',
                icon: "fa fa-copy",
                clickEvent: ()=>{

                },
                customVisible: ((row) => {
                  return true
                })
              },
            ],
            mLeft: 5
          }
        },
        dataFilter:(data:any[])=>{
          return data
        }
      }
    }
  }
})

const emits = defineEmits([
  "moreDetailClick",
  "edit-in-dlg",
  "update:selectRow",
  "dbClick",
  "update:selectionRows",
  "rowClick",
  "loadSuccess",
  "update:queryData"
])

const state = reactive({
  tableClass:GuidID(),
  isShowTable: false,
  selectData: null,
  isShowTextOperate: false,
  isShowIconOperate: false,
  saveUrl: "",

  ifShowCheck:false,
  selectTypeAfterload:2,
  url: '',
  isAutoEdit: false,
  remoteQueryMode: 2,
  dataName: 'Datas',
  showIndex: true,
  showEditInDialog: false,
  ellipsis: true,
  rowKey: "",
  pagination: {
    pageSize: 30,
    hideOnSinglePage: false
  },
  showToolBar: false,
  queryParams: {} as any,
  searchBox: false,
  operateBtnOption:{
    headBtnOption:{
      ifShow:false,
      btnOption: [
        {
          visible: true,
          zhTitle: '新增',
          enTitle: 'add',
          icon: "fa fa-plus",
          clickEvent: ()=>{},
          customVisible: ((row) => {
            return true
          })
        }
      ]
    },
    rowBtnOption:{
      ifShow:false,
      btnBaseWidth: 70,
      btnNum: 3,
      btnOption: [
        {
          visible: true,
          zhTitle: '复制',
          enTitle: 'add',
          icon: "fa fa-copy",
          clickEvent: ()=>{

          },
          customVisible: ((row) => {
            return true
          })
        },
      ],
      mLeft: 5
    }
  },
  dataFilter:(data:any[])=>{
    return data
  }
})

const spinning = ref(false)
const ltTableRemoteRef = ref(null)
let selectedRowKeys=ref([])
let selectionData=ref([])
let columnFilter=ref<ColumnFilterItemInter[] | string[]>([])
let columns=ref<ColInter[]>([])
let innerCols=ref([])
let currentPageData=ref([])

let key = ''
let saveURL = ''
let formatShowSaveFun = null
let isShowTextOperate = false
let isShowIconOperate = false
let rowBtnOption=null
let headBtnOption=null

// 选中的
const localShowSelection = computed(() => {
  if(state.ifShowCheck){
    return {
      selectedRowKeys: selectedRowKeys.value, onChange: onSelectChange
    }
  }else{
    return null
  }
  // if (typeof props.rowSelection == "undefined") {

  // } else {
  //   return props.rowSelection
  // }
})
const showCols = computed(() => {
  return innerCols.value
})
const load = function (){
  state.selectTypeAfterload=1
  ltTableRemoteRef.value.reload(true)
  selectedRowKeys.value=[]
  selectionData.value=[]
  emits("update:selectionRows", [])
  nextTick(()=>{
    state.selectTypeAfterload=2
  })
}
const reload = function () {
  state.selectTypeAfterload=2
  ltTableRemoteRef.value.reload()
  selectedRowKeys.value=[]
  selectionData.value=[]
  emits("update:selectionRows", [])
}
const handleLoadSuccess = function (data: any[], index: number,) {
  // console.log('返回index',index)
  let selectIndex=0
  if (data.length > 0) {
    selectIndex =index!==-1?index:0
    emits("update:selectRow", data[selectIndex])
    state.selectData = data[selectIndex]
  }else{
    emits("update:selectRow", null)
  }
  let realIndex= selectIndex
  if(ltTableRemoteRef.value.paginationRef&&ltTableRemoteRef.value.paginationRef.current>1){
    realIndex=(ltTableRemoteRef.value.paginationRef.current-1)*ltTableRemoteRef.value.paginationRef.pageSize+selectIndex
  }
  currentPageData.value=data
  // console.log('真正的选项',realIndex)
  emits('loadSuccess',data,realIndex)
  calcTableBody()
}
const handleClick = function (row: any,dataIndex: number,) {
  state.selectData = row
  emits("update:selectRow", row)
  let realIndex= dataIndex
  if(ltTableRemoteRef.value.paginationRef&&ltTableRemoteRef.value.paginationRef.current>1){
    realIndex=(ltTableRemoteRef.value.paginationRef.current-1)*ltTableRemoteRef.value.paginationRef.pageSize+dataIndex
  }
  // console.log('真正的选项',realIndex)
  emits("rowClick", row,realIndex)
}
const handleDblclick = function (row: any, dataIndex: number, event: any) {
  state.selectData = row
  emits("update:selectRow", row)
  let realIndex= dataIndex
  if(ltTableRemoteRef.value.paginationRef&&ltTableRemoteRef.value.paginationRef.current>1){
    realIndex=(ltTableRemoteRef.value.paginationRef.current-1)*ltTableRemoteRef.value.paginationRef.pageSize+dataIndex
  }
  // console.log('真正的选项',realIndex)
  emits('dbClick',row,realIndex)
}
const onSelectChange = function (rowKeys: any[],selection: any[]) {
  const currPageRowKeys = currentPageData.value.map((item:any)=>{
    return item[state.rowKey]
  })
  if(state.rowKey){
    const noSelectRowKeys = selectedRowKeys.value.filter((item:any)=>{
      return currPageRowKeys.includes(item)&&!rowKeys.includes(item)
    })
    for(let i=0;i<selectedRowKeys.value.length;i++){
      if(noSelectRowKeys.includes(selectedRowKeys.value[i])){
        selectedRowKeys.value.splice(i,1)
        i--
      }
    }
    selectedRowKeys.value = Array.from(new Set(selectedRowKeys.value.concat(rowKeys)))
    for(let i=0;i<selectionData.value.length;i++){
      if(noSelectRowKeys.includes(selectionData.value[i][state.rowKey])){
        selectionData.value.splice(i,1)
        i--
      }
    }
    selection.forEach((item:any)=>{
      const target = selectionData.value.find((item2:any)=>item2[state.rowKey]===item[state.rowKey])
      if(checkNull(target)){
        selectionData.value.push(item)
      }
    })
  }else{
    selectionData.value=selection
    selectedRowKeys.value=rowKeys
  }
  emits("update:selectionRows", selectionData.value)
}
const handleEditInDlg = function (record: any) {
  emits("edit-in-dlg", record)
}
const moreDetailClick = function (record:any) {
  emits("moreDetailClick", record)
}
const _initTableParams = () => {
  for (let key in props.tableParams) {
    if (state[key] !== undefined) {
      state[key] = props.tableParams[key]
    }
  }
  columnFilter.value = props.tableParams.columnFilter
  selectedRowKeys.value=checkNull(props.tableParams.selectedRowKeys)?[]:cloneDeep(props.tableParams.selectedRowKeys)
  key = unref(state.rowKey)
  saveURL = unref(state.saveUrl)
  formatShowSaveFun = unref(props.formatShowSaveFun)
  isShowTextOperate = unref(state.isShowTextOperate)
  isShowIconOperate = unref(state.isShowIconOperate)
  rowBtnOption = unref(state.operateBtnOption.rowBtnOption)
  headBtnOption = unref(state.operateBtnOption.headBtnOption)
}

const calcTableBody=()=>{
  nextTick(()=>{
    if($('.lt-common-table-remote-' + state.tableClass).css('height')) {
      const containerHeight = Number($('.lt-common-table-remote-' + state.tableClass).css('height').replace('px', ''))
      const tableHeaderHeight = Number($('.lt-common-table-remote-' + state.tableClass + ' .ant-table-header').css('height').replace('px', ''))//66
      const paginationClass = '.lt-common-table-remote-' + state.tableClass + ' .ant-pagination'
      let tablePaginationHeight = 0
      if ($(paginationClass).css('height')) {
        tablePaginationHeight = Number($(paginationClass).css('height').replace('px', ''))
      }
      if (tablePaginationHeight) {
        // margin
        tablePaginationHeight = tablePaginationHeight + 20
      }
      const tablePadding = 6 + 2
      const tableBodyHeight = containerHeight - tableHeaderHeight - tablePaginationHeight - tablePadding
      console.log('高度', containerHeight, tableHeaderHeight, tablePaginationHeight, tableBodyHeight)
      $('.lt-common-table-remote-' + state.tableClass + ' .ant-table-body').css('height', tableBodyHeight + 'px')
    }
  })
}
const handleGetQueryData=(queryData: any)=>{
  emits("update:queryData", queryData);
}

onBeforeMount(() => {
  _initTableParams()
  innerCols.value = UseFormatShowCols({
    props, key, saveURL, formatShowSaveFun, spinning, isShowTextOperate, reload,rowBtnOption,headBtnOption,moreDetailClick
  }).innerCols.value
})
onMounted(() => {
  state.isShowTable = true
})

defineExpose({load,reload})
</script>