<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"
          :otherAttrs="{
            fixed: 'left',
          }"
        ></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: '分区',
        attrs: { 'min-width': '100px', fixed: 'left' },
      },
    ]
    const newConfig = []
    if (arr.length) {
      for (const key in arr[0]) {
        if (!whiteList.includes(key)) {
          newConfig.push({
            prop: key,
            label: key,
            attrs: {
              'edit-render': {},
              'min-width': '300px',
            },
            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: formatString(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 = 3) => {
    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 = {}
  }
}

function formatString(input: string) {
  // 1. 替换所有中文逗号为英文逗号
  // 2. 移除所有空格
  // 3. 将连续逗号替换为单个逗号
  // 4. 去除首尾可能的逗号
  return input
    .replace(/，/g, ',') // 中文逗号转英文逗号
    .replace(/\s+/g, '') // 移除所有空格
    .replace(/,+/g, ',') // 连续逗号替换为单个逗号
    .replace(/^,|,$/g, '') // 去除首尾逗号
}
</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;
}
:deep() {
  // .vxe-cell {
  //   padding: 15px 10px !important;
  // }
  .col--edit::after {
    content: '双击修改';
    display: none;
    position: absolute;
    top: 0;
    z-index: 99;
    left: 50%;
    transform: translate(-50%);
    // width: 85px;
    // height: 20px;
    font-size: 10px;
    line-height: 1;
    border-radius: 5px;
    padding: 2px 5px;
    opacity: 0.5;
    background-color: black;
    text-align: center; /* 使文本居中 */

    color: white; /* 文本颜色 */
  }

  .col--edit:hover::after {
    display: block;
  }
  .col--active:hover::after {
    content: '单击其他单元格确认';
    white-space: nowrap;
  }
}
</style>
