<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { columns, searchFormSchema } from '../exa.data'
import type { TableActionType } from '@/components/Table'
import { BasicTable, TableAction, useTable } from '@/components/Table'
import { getEXAPage } from '@/api/alert/exa'
import { useI18n } from '@/hooks/web/useI18n'
import { IconEnum } from '@/enums/appEnum'
import { BasicModal, useModalInner } from '@/components/Modal'

const props = defineProps({
  source: { type: String, default: '' },
  rowSelectType: { type: String, default: 'checkbox' },
  selectedData: { type: Array<Recordable>, default: [] },
  selectedRowKeys: { type: Array<number>, default: [] },
})
const emit = defineEmits(['success', 'register'])
const [registerPointModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  setModalProps({ confirmLoading: false })
})
const { t } = useI18n()

const selectedData = ref<Recordable[]>(props.selectedData)

interface RowKeys {
  selectedRowKeys: number[]
}
const state = reactive<RowKeys>({
  selectedRowKeys: props.selectedRowKeys,

})

const tableRef = ref<Nullable<TableActionType>>(null)
const tableRef1 = ref<Nullable<TableActionType>>(null)

const [registerTable] = useTable({
  title: '测点列表',
  api: getEXAPage,
  immediate: false,
  showTableSetting: false,
  tableSetting: {
    // 是否显示刷新按钮
    redo: false,
    // 是否显示尺寸调整按钮
    size: false,
    // 是否显示字段调整按钮
    setting: false,
    // 是否显示全屏按
    fullScreen: false,
  },
  columns,
  formConfig: {
    labelWidth: 150,
    schemas: searchFormSchema,
    showResetButton: false,
    actionColOptions: {
      span: 3,
    },
  },
  rowKey: 'serialNumber',
  useSearchForm: true,
  showIndexColumn: false,

})

// 这个必须写在computed计算属性里，心酸啊，弄一下午！
const rowSelection = computed(() => {
  return {
    preserveSelectedRowKeys: true, // 2.加这一行
    type: props.rowSelectType,
    selectedRowKeys: state.selectedRowKeys,
    onChange: onSelectChange,

  }
})

// defaultChecked: record.serialNumber === 93,
watch(
  () => props.selectedRowKeys,
  () => {
    state.selectedRowKeys = props.selectedRowKeys
    selectedData.value = props.selectedData
  },
)
const [registerSelectedTable] = useTable({
  title: '已选中测点列表',
  showTableSetting: false,
  tableSetting: {
    // 是否显示刷新按钮
    redo: false,
    // 是否显示尺寸调整按钮
    size: false,
    // 是否显示字段调整按钮
    setting: false,
    // 是否显示全屏按
    fullScreen: false,
  },
  columns,
  formConfig: {
    labelWidth: 150,
    schemas: searchFormSchema,
    showResetButton: false,
    actionColOptions: {
      span: 2,
    },
  },
  rowKey: 'serialNumber',
  useSearchForm: false,
  showIndexColumn: false,
  actionColumn: {
    width: 80,
    title: t('common.action'),
    dataIndex: 'action',
    fixed: 'right',
  },
})

function onSelectChange(selectedRowKeys, selectedRows) {
  console.log(selectedRowKeys, selectedRows)
  state.selectedRowKeys = selectedRowKeys
  let selectionRows: any[] = []
  console.log('3', selectedData.value)

  selectionRows = selectedData.value.concat(selectedRows)
  console.log('2', selectionRows)

  selectionRows = selectionRows.filter(item => selectedRowKeys.includes(item.serialNumber))
  console.log('1', selectionRows)
  // 数组对象去重
  const map = new Map()
  for (const item of selectionRows) {
  	if (!map.has(item.serialNumber))
       	map.set(item.serialNumber, item)
  };
  selectedData.value = [...map.values()]
}

function handleOk() {
  console.log(props.source)
  if (props.source === 'run') {
    console.log('来自运行中心-模型实例-更换测点')

    if (selectedData.value.length !== 0) {
      emit('success', selectedData.value)
      closeModal()
    }
    else { message.error('请选择替换的测点,若不进行替换,请点击取消返回') }
  }
  else {
    console.log('onOk:')
    localStorage.setItem('pointInfo', JSON.stringify(state.selectedRowKeys))
    localStorage.setItem('pointInfoList', JSON.stringify(selectedData.value))
    closeModal()
    emit('success')
  }
}
async function handleDelete(record: Recordable) {
  const newArr = state.selectedRowKeys.filter((value) => {
    return value !== record.serialNumber
  })
  state.selectedRowKeys = newArr
  localStorage.setItem('pointInfo', JSON.stringify(state.selectedRowKeys))

  const newArrObj = selectedData.value.filter((value) => {
    return value.serialNumber !== record.serialNumber
  })
  selectedData.value = newArrObj
}
function handleClearAndClose() {
  state.selectedRowKeys = []
  selectedData.value = []
  localStorage.setItem('pointInfo', JSON.stringify(state.selectedRowKeys))
  localStorage.setItem('pointInfoList', JSON.stringify(selectedData.value))
  closeModal()
  emit('success')
}

function onCanel() {
  state.selectedRowKeys = []
  selectedData.value = []
}
</script>

<template>
  <BasicModal v-bind="$attrs" :min-height="500" title="测点配置" width="850px" @cancel="onCanel" @register="registerPointModal" @ok="handleOk">
    <BasicTable
      ref="tableRef" title="所有测点" :can-resize="false"
      :row-selection="rowSelection" size="small" @register="registerTable"
    />
    <BasicTable
      ref="tableRef1"
      :pagination="false" size="small" :data-source="selectedData" :can-resize="false"
      title="已选中测点" @register="registerSelectedTable"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[{
              icon: IconEnum.DELETE,
              danger: true,
              label: t('action.delete'),
              auth: 'system:role:delete',
              popConfirm: {
                title: t('common.delMessage'),
                placement: 'left',
                confirm: handleDelete.bind(null, record),
              },
            },
            ]"
          />
        </template>
      </template>
      <template v-if="props.source !== 'run'" #toolbar>
        <a-button v-auth="['system:role:create']" type="primary" :pre-icon="IconEnum.DELETE" @click="handleClearAndClose">
          {{ t('action.clearAllandClose') }}
        </a-button>
        <!-- <a-button v-auth="['system:role:create']" :pre-icon="IconEnum.EXPORT" @click="handleExport">
          {{ t('action.export') }}
        </a-button> -->
      </template>
    </BasicTable>
  </BasicModal>
</template>

<style>

</style>
