import {
  TableColumnProps, Table, Row, Col, Space, Tooltip, Dropdown, Menu,
  Button, DropdownButton, PaginationProps
} from 'ant-design-vue'
import { DownOutlined } from '@ant-design/icons-vue'
import {
  PropType, computed, defineComponent, reactive, ref, defineEmits, FunctionalComponent,
  onMounted
} from 'vue'

/**
 * @description Table Pro 超级table 将各种业务与操作融合起来
 */

interface Props {
  columns: TableColumnProps[],
  pagination: PaginationProps | false
  request: {
    get: (record: any) => {data, sum},
    params: any
  },
  easy: boolean
}

// const TablePro: FunctionalComponent<Props> = (props) => {
//   const { request, easy, columns } = props

//   const emits = defineEmits(['add'])

//   const loading = ref<boolean>(false)

//   const columnsPro = ref<(TableColumnProps & {hidden: boolean}) []>(columns.map(column => ({ ...column, hidden: false })))

//   const columnsFilter = computed(() => columnsPro.value.filter(column => !column.hidden))

//   const rowCustomized = computed(() => columns.map(item => ({ title: item.title, key: item.key })))

//   const pagination = reactive<PaginationProps>(Object.assign({}, {
//     current: 1,
//     pageSize: 10,
//     total: 0,
//     onChange: (page: number, pageSize: number) => onChangePage(page, pageSize)
//   }, typeof props.pagination === 'boolean' ? {} : { ...props.pagination }))

//   const dataSource = ref([])

//   const opraMeun = (
//     <Menu>
//       <Menu.item key={0} onClick={emits('add')} > 新增 </Menu.item>
//       <Menu.item key={2} onClick={() => exportExcel()}> 导出 </Menu.item>
//       <Menu.item key={3} onClick={() => pure()}> 纯净 </Menu.item>
//     </Menu>
//   )

//   const exportExcel = () => {}

//   const pure = () => {}

//   const reload = () => dispatchRequest()

//   const onChangePage = (page: number, pageSize: number) => {
//     pagination.current = page
//     pagination.pageSize = pageSize
//     dispatchRequest()
//   }

//   const dispatchRequest = async () => {
//     loading.value = true
//     const { data, sum } = await request.get({
//       ...request.params,
//       page: pagination.current,
//       pageSize: pagination.pageSize
//     })
//     loading.value = false
//     pagination.total = sum
//     dataSource.value = data
//   }

//   /**
//    * 展示或者隐藏对应的column
//    */
//   const swicthColumn = (index: number) => {
//     columnsPro.value[index].hidden = !columnsPro.value[index].hidden
//   }

//   const RenderOpraRow = () => {
//     return (
//       <>
//         {easy
//           ? null
//           : <Row gutter={[8, 8]}>
//           <Col span={12} >
//             {/* <solt name="search" ></solt> */}
//           </Col>
//           <Col span={12} >
//             <Space>
//               <Tooltip title='列表定制' >
//                  {/*  @click.prevent */}
//                  {/*  <a class="ant-dropdown-link"> <menu-outlined /> </a> */}
//                 <Dropdown
//                   trigger={['click']}
//                   overlay={
//                   <Menu>
//                     {
//                       rowCustomized.value.map((item, index) => (
//                         <Menu.item key={item.key} onClick={() => swicthColumn(index)} >
//                           {item.title}
//                         </Menu.item>
//                       ))
//                     }
//                   </Menu>}
//                 >
//                 </Dropdown>
//               </Tooltip>
//                  {/*  @click.prevent */}
//                  {/*  <a class="ant-dropdown-link"> <menu-outlined /> </a> */}
//                 <DropdownButton
//                   trigger={['click']}
//                   overlay={opraMeun}
//                   icon={<DownOutlined />}
//                   onClick={reload}
//                 >
//                   <Button>刷新</Button>
//                 </DropdownButton>
//             </Space>
//           </Col>
//         </Row>}
//       </>
//     )
//   }

//   return (
//       <>
//         <RenderOpraRow />
//         {/*       */}
//         <Table
//           style="margin-top: 20px;"
//           columns={columnsFilter.value}
//           loading={loading.value}
//           pagination={typeof props.pagination === 'boolean' ? false : pagination}
//           dataSource={dataSource.value}
//         >
//           <slot></slot>
//           <slot name='action'></slot>
//         </Table>
//       </>
//   )
// }

// export default TablePro

const TablePro = defineComponent({
  props: {
    columns: {
      type: Array as PropType<TableColumnProps[]>,
      require: true
    },
    service: {
      type: Function,
      default: () => {}
    },
    serviceParams: {
      type: Object,
      default: () => {}
    },
    easy: {
      type: Boolean,
      default: true
    },
    pagination: {
      type: Object as PropType<{pageSize: number}>,
      default: () => ({ pageSize: 10 })
    }
  },
  emits: ['add'],
  setup (props, ctx) {
    const { columns, service, pagination, serviceParams } = props

    const loading = ref<boolean>(false)

    const paginationRef = ref({
      current: 1,
      pageSize: pagination.pageSize ? pagination.pageSize : 10,
      total: 0
    })

    const dataSource = ref([])

    const reload = (params?: {page: number}) => {
      if (params?.page) {
        paginationRef.value.current = params.page
      }
      dispatchRequest()
    }
    const dispatchRequest = async () => {
      loading.value = true
      const { data, sum } = await service({
        ...serviceParams,
        page: paginationRef.value.current,
        pageSize: paginationRef.value.pageSize
      })
      loading.value = false
      paginationRef.value.total = sum
      dataSource.value = data
      console.log('data:', data)
    }

    const onChangePage = (page: number, pageSize: number) => {
      paginationRef.value.current = page
      paginationRef.value.pageSize = pageSize
    }

    onMounted(() => {
      service && dispatchRequest()
    })

    const opraMeun = (
      <Menu>
        <Menu.Item key={0} onClick={() => ctx.emit('add')} > 新增 </Menu.Item>
      </Menu>
    )

    ctx.expose({ reload })

    return () => (

      <Row style={{ width: '100%' }} >
        <Col span={24} >
          <Row style={{ width: '100%' }} >
            <Col span={12} >
              {ctx.slots.search?.()}
            </Col>
            <Col span={12} style={{ display: 'flex', justifyContent: 'end' }} >
              <Space>
              <Dropdown
                  trigger={['click', 'hover']}
                  overlay={opraMeun}
                >
                  <Button onClick={() => reload()} >刷新<DownOutlined /></Button>
                </Dropdown>
              </Space>
            </Col>
          </Row>
        </Col>

        <Col span={24} >
          <Table
            style={{ marginTop: '20px' }}
            columns={columns}
            loading={loading.value}
            pagination={{ ...paginationRef.value, onChange: onChangePage }}
            dataSource={dataSource.value}
            v-slots={{
              bodyCell (scope) {
                return ctx.slots.render?.({ column: scope.column, record: scope.record })
              }
            }}
          >
          </Table>
        </Col>
      </Row>

    )
  }
})

export default TablePro
