<template>
  <div class="user-page flex-column card h-100 overflow-hidden">
    <div class="header-filter-form">
      <SearchForm
        :config="searchConfig"
        @search="search"
        :isAddBtn="false"
        @delete="deleteFn"
        v-model="searchForm"
      >
        <template #ontherBtn>
          <div style="margin-left: 10px; display: flex; gap: 10px">
            <ElButton @click="downloadExcel" type="primary" plain
              >下载模版</ElButton
            >

            <el-upload
              class="upload-demo"
              action
              :show-file-list="false"
              :before-upload="onBeforeUploadImage"
              :http-request="exportExcel"
            >
              <ElButton type="primary" plain> 导入</ElButton>
            </el-upload>
          </div>
        </template></SearchForm
      >
    </div>
    <div
      v-loading="loading"
      class="user-content flex-1 flex-column overflow-hidden"
    >
      <div class="user-list flex-1 overflow-hidden">
        <CustomizeTable
          v-model="tableData"
          :config="tableConfig"
          :merge-cells="mergeCells"
          @edit-closed="editClosed"
          :tableEditConfig="{
            enabled: true,
          }"
          align="center"
          border="full"
          @getCheckboxRecords="handleCheckboxRecords"
        ></CustomizeTable>
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx">
defineOptions({
  name: 'LogisticsPartition',
})
import {
  getLogisticsZoneList,
  updateLogisticsZone,
  deleteLogisticsZone,
  importLogisticsZone,
  exportExcelLogisticsZone,
  getlogisticsWayAllList,
} from '@/api/logistics'

import SearchForm from '@/components/SearchForm.tsx'
import { ISeachFormConfig } from '@/types/searchType'

import CustomizeTable from '@/components/VxeTable.tsx'
import type { VxeTablePropTypes } from 'vxe-table'
import { useValue } from './hooks/useValue'
import { showConfirm } from '@/utils/ui'
import { ElInput } from 'element-plus'
import { TableColumn } from '@/components/VxeTable'

const [searchForm] = useValue<{
  logisticsIdList?: string[] | string
  codePrefix?: string
}>({ logisticsIdList: [] })

const selection = ref([])
const mergeCells = ref<VxeTablePropTypes.MergeCells>([])
const tableData = ref([])
const searchConfig = ref<ISeachFormConfig[]>([
  {
    prop: 'logisticsIdList',
    type: 'select',
    label: '物流方式',

    attrs: {
      placeholder: '请选择物流方式',
      multiple: true,
      clearable: true,
      value: 'id',
      label: 'name',
      collapseTags: true,
      collapseTagsTooltip: true,
      options: [],
    },
  },
  {
    prop: 'codePrefix',
    type: 'input',
    label: '邮编编码',
    attrs: {
      clearable: true,
      placeholder: '请输入邮编编码',
    },
  },
])

const tableConfig = ref<TableColumn[]>([])

onMounted(() => {
  getAllList()
})

/**
 * @description: 搜索
 */
async function search() {
  await getList(searchForm.value)
  setCellStyle()
}

/**
 * @description: 转换表格数据
 */

// 定义物流区域项的类型
interface LogisticsZoneItem {
  logistics: string
  codePrefix: string
  highlight: boolean
  logisticsId: string
}

// 定义父项的类型，允许动态添加属性
interface ParentItem {
  logisticsZoneList: LogisticsZoneItem[]
  [key: string]: unknown // 添加索引签名，允许任意字符串键
}

function getTableData(arr: ParentItem[]) {
  if (!Array.isArray(arr) || arr.length === 0) return []
  return arr.map((parentItem) => {
    const quotationList = parentItem.logisticsZoneList ?? []
    quotationList?.forEach((el) => {
      parentItem[el.logistics] = {
        codePrefix: el.codePrefix || '',
        highlight: el.highlight,
        logisticsId: el.logisticsId,
      }
    })
    return {
      ...parentItem,
    }
  })
}

/**
 * @description: 删除按钮
 */
async function deleteFn() {
  if (!selection.value.length) {
    return ElMessage({
      message: '请选择分区',
      type: 'warning',
    })
  }
  try {
    await showConfirm('是否删除改分区下物流方式的邮编编码', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const whiteList = ['logisticsZoneList', 'zoneName', '_X_ROW_KEY']

    const zomList = selection.value.map((item) => {
      const arr = []
      for (const key in item) {
        if (!whiteList.includes(key)) {
          arr.push(key)
        }
      }
      return [...arr]
    })

    const params = {
      logisticsList: zomList[0],
      zoneNameList: selection.value.map(
        (item: { zoneName: string }) => item.zoneName,
      ),
    }
    await deleteLogisticsZone(params)
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    getList(searchForm.value)
  } catch (e) {
    getList(searchForm.value)
    // showError(e)
  }
}

const loading = ref(false)
const editParams = ref({})

/**
 * @description: 获取列表
 */
async function getList(data?: {
  logisticsIdList?: string[] | string
  codePrefix?: string
}) {
  loading.value = true
  try {
    const res = await getLogisticsZoneList({
      ...data,
    })

    tableData.value = [...res.data]

    const arr = await getTableData(tableData.value)

    const whiteList = ['logisticsZoneList', 'zoneName']
    const oldConfig = [
      {
        prop: 'zoneName',
        label: '分区',
      },
    ]
    const newConfig = []
    if (arr.length) {
      for (const key in arr[0]) {
        if (!whiteList.includes(key)) {
          newConfig.push({
            prop: key,
            label: key,
            attrs: {
              'edit-render': {},
            },
            render: {
              edit: ({
                row,
              }: {
                row: {
                  [key: string]: { codePrefix: string; logisticsId: string }
                }
              }) => {
                return (
                  <div>
                    <ElInput
                      style={{ height: '24px' }}
                      modelValue={row[key]?.codePrefix}
                      onInput={(e) => {
                        console.log(233, row)
                        row[key].codePrefix = e
                        editParams.value = {
                          zoneName: row.zoneName,
                          logistics: key,
                          codePrefix: e || '',
                          logisticsId: row[key].logisticsId,
                        }
                      }}
                    />
                  </div>
                )
              },
              default: ({
                row,
              }: {
                row: {
                  [key: string]: { codePrefix: string; highlight: string }
                }
              }) => {
                return (
                  <span
                    class={row[key]?.highlight ? 'tableCell' : 'primaryCell'}
                  >
                    {row[key]?.codePrefix}
                  </span>
                )
              },
            },
          })
        }
      }
    }
    tableConfig.value = [...oldConfig, ...newConfig] as TableColumn[]
    console.log(545, tableConfig.value)
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

/**
 * @description: 处理复选框
 */
function handleCheckboxRecords(value: never[]) {
  console.log(351, value)
  selection.value = value
}

/**
 * @description: 设置单元格样式
 */
function setCellStyle() {
  const [cell, primaryCell] = ['.tableCell', '.primaryCell'].map((selector) =>
    document.querySelectorAll(selector),
  )
  const getAncestor = (element: Element, level = 2) => {
    let current = element
    while (level-- > 0 && current) {
      current = current.parentElement as Element
    }
    return current || null
  }

  const safeSetBackground = (element: HTMLElement, color: string) => {
    if (element?.style && typeof color === 'string') {
      element.style.backgroundColor = color
    }
  }
  if (cell.length) {
    cell.forEach((item) => {
      const grandParent = getAncestor(item)
      safeSetBackground(grandParent as HTMLElement, '#e6f7ff')
    })
  }
  if (primaryCell.length) {
    primaryCell.forEach((item) => {
      const grandParent = getAncestor(item)
      safeSetBackground(grandParent as HTMLElement, 'transparent')
    })
  }
}

/**
 * @description: 获取物流方式列表
 */
async function getAllList() {
  try {
    const res = await Promise.allSettled([getlogisticsWayAllList()])
    res.forEach(
      (item: PromiseSettledResult<{ code: number; data: never[] }>, index) => {
        if (item?.status === 'fulfilled') {
          if (item.value.code === 200) {
            if (index == 0) {
              searchConfig.value[0].attrs!.options = [
                ...(item.value.data || []),
              ]
            }
          }
        }
      },
    )
    getList()
  } catch (error) {
    console.log(error)
  }
}

/**
 * @description: 上传文件
 */
function onBeforeUploadImage(file: File) {
  const isIMAGE =
    file.type ==
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

  if (!isIMAGE) {
    ElMessage.error('上传文件只能是excel格式!')
  }

  return isIMAGE
}

/**
 * @description: 下载模版
 */
async function downloadExcel() {
  try {
    const res = await exportExcelLogisticsZone()
    const blob = new Blob([res as unknown as BlobPart])
    const filename = '物流分区模版.xlsx'
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = filename
    link.click()
  } catch (error) {
    console.log(error)
  }
}

/**
 * @description: 导入
 */
async function exportExcel(file: { file: File }) {
  try {
    const formData = new FormData()
    formData.append('file', file.file)

    const res = await importLogisticsZone(formData)
    if (res.code === 200) {
      ElMessage.success('导入成功!')
      getList(searchForm.value)
    }
  } catch (error) {
    ElMessage.error('导入失败!')
  }
}

/**
 * @description: table编辑关闭事件
 */
async function editClosed() {
  console.log(1111111, editParams.value)
  try {
    if (Object.keys(editParams.value).length) {
      await updateLogisticsZone(editParams.value)
      ElMessage.success('修改成功!')
      getList(searchForm.value)
    }
  } catch {
    getList(searchForm.value)
  } finally {
    editParams.value = {}
  }
}
</script>

<style lang="scss" scoped>
.header-filter-form {
  margin-bottom: 20px;

  :deep(.el-form-item) {
    margin-right: 14px;
    margin-bottom: 10px;
  }
}
.user-operate-btn {
  margin-bottom: 10px;
}
.dialog-footer {
  text-align: center;
}
</style>
