<template>
<!--  <a-spin size="small" :spinning="spinning">-->
    <a-layout style="height: 100%" :class="{['lt-common-table-local-'+state.tableClass]:true,'lt-common-table-local':true}">
      <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="ltTablelocalRef"
            size="small"
            bordered
            :columns="showCols"
            :columnFilter="columnFilter"
            :showIndex="state.showIndex"
            :is-auto-editable="state.isAutoEdit"
            :rowSelection="localShowSelection"
            :showEditInDialog="state.showEditInDialog"
            :ellipsis="state.ellipsis"
            :searchBox="state.searchBox"
            :row-key="state.rowKey"
            :pagination="state.pagination"
            :showToolBar="state.showToolBar"
            :scroll="props.scroll"
            :dataSource="props.tableData"
            :selectTypeAfterload="state.selectTypeAfterload"
            :rowClassName="state.rowClassName"
            :dataFilter="state.dataFilter"
            @row-click="handleClick"
            @row-dblclick="handleDblclick"
            @loadSuccess="handleLoadSuccess"
        >
          <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="locale.value === 'zh' ? item.zhTitle : item.zhTitle"
                    :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>
          <template v-if="state.ifShowExpandedTable" v-slot:expandedRowRender="slotProps">
            <slot name="expandedRowRender" :slotProps="slotProps"></slot>
          </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, toRaw, watch} 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 {
        isShowTable: false,
        selectedRowKeys: [],
        selectData: null,
        selectionData: [],
        isShowTextOperate: false,
        saveUrl: "",

        columnFilter: [] as ColumnFilterItemInter[] | string[],
        columns: [] as any[],
        url: '',
        isAutoEdit: false,
        showIndex: true,
        showEditInDialog: false,
        ellipsis: true,
        rowKey: "",
        pagination: {
          pageSize: 25,
          hideOnSinglePage: false
        },
        showToolBar: false,
        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
          }
        }
      }
    }
  },
  tableData:{
    type:Array as PropType<any[]>,
    default(){
      return []
    }
  }
})

const emits = defineEmits(["combox-select-change", "edit-in-dlg","dbClick","update:selectRow", "update:selectionRows","changeTable"])

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

  ifShowExpandedTable:false,
  ifShowCheck:false,
  selectTypeAfterload:0,
  isAutoEdit: false,
  showIndex: true,
  showEditInDialog: false,
  ellipsis: true,
  rowKey: "",
  pagination: {
    pageSize: 30,
    hideOnSinglePage: false
  },
  showToolBar: false,
  searchBox: false,
  rowClassName:null,
  operateBtnOption:{
    headBtnOption:{
      ifShow:false,
      btnOption: [
        {
          visible: true,
          zhTitle: '新增',
          enTitle: 'add',
          icon: "fa fa-plus",
          clickEvent: ()=>{},
        }
      ]
    },
    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 ltTableLocalRef = ref(null)
let selectedRowKeys=ref([])
let selectionData=ref([])
let columnFilter=ref<ColumnFilterItemInter[] | string[]>([])
let columns=ref<ColInter[]>([])
let innerCols=ref([])

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


// 选中的
const localShowSelection = computed(() => {
  if(state.ifShowCheck){
    return {
      selectedRowKeys: selectedRowKeys.value, onChange: onSelectChange
    }
  }else{
    return null
  }
})
const showCols = computed(() => {
  return innerCols.value
})

const reload = function () {
  ltTableLocalRef.value.reload()
}
// 只有初始化时触发，什么鬼
const handleLoadSuccess = function (data: any[], index: number) {
  emits("update:selectionRows", [])
  // debugger
  if (data.length > 0) {
    const selectIndex =index!==-1?index:0
    // debugger
    emits("update:selectRow", data[selectIndex])
    state.selectData = data[selectIndex]
  }else{
    emits("update:selectionRows", [])
    emits("update:selectRow", null)
    selectedRowKeys.value=[]
  }
  calcTableBody()
}
const handleClick = function (row: any) {
  state.selectData = row
  emits("update:selectRow", row)
}
const handleDblclick = function (row: any, dataIndex: number, event: any) {
  state.selectData = row
  emits("update:selectRow", row)
  emits('dbClick',row)
}
const onSelectChange = function (rowKeys: any[],selection: any[]) {
  selectedRowKeys.value = rowKeys
  selectionData.value = selection
  emits("update:selectionRows", selection)
}
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)
  rowBtnOption = unref(state.operateBtnOption.rowBtnOption)
  headBtnOption = unref(state.operateBtnOption.headBtnOption)
}

const calcTableBody=()=>{
  nextTick(()=>{
    if($('.lt-common-table-local-' + state.tableClass).css('height')) {
      const containerHeight = Number($('.lt-common-table-local-' + state.tableClass).css('height').replace('px', ''))
      const tableHeaderHeight = Number($('.lt-common-table-local-' + state.tableClass + ' .ant-table-header').css('height').replace('px', ''))//66
      const paginationClass = '.lt-common-table-local-' + 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-local-' + state.tableClass + ' .ant-table-body').css('height', tableBodyHeight + 'px')
    }
  })
}
const handleChangeTableShow=()=>{
  emits('changeTable')
}

watch(()=>props.tableData,(nVal)=>{
  if(props.tableData.length>0){
    emits("update:selectRow", props.tableData[0])
    emits("update:selectionRows", [])
    selectedRowKeys.value=[]
    selectionData.value=[]
  }else{
    emits("update:selectionRows", [])
    emits("update:selectRow", null)
    selectedRowKeys.value=[]
    selectionData.value=[]
  }
},)

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

defineExpose({})
//通过子元素找父元素
/*.lt-common-table-local >>> .ant-table-cell-fix-left:has(> .ant-table-row-expand-icon){
  display: flex;
  justify-content: center;
}*/
</script>


<style scoped lang="less">
.lt-common-table-local /deep/{
   .ant-table-row-expand-icon {
    margin-left: 15px;
  }
  //.class1{
  //  background-color: red;
  //}
}
</style>