<template>
  <div class="user-page flex-column card h-100 overflow-hidden">
    <div class="header-filter-form">
      <SearchForm
        :callback="search"
        :config="searchConfig"
        @search="search"
        @add="addDialog"
        @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>
            <el-upload
              class="upload-demo"
              action
              :show-file-list="false"
              :before-upload="onBeforeUploadImage"
              :http-request="updateExcel"
            >
              <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"
          :seq-config="{
            seqMethod: (row:any) => {
              if (mergeCells?.length) {
                return row.row.seq
              }

              return row.seq
            },
          }"
          border="full"
          @getCheckboxRecords="handleCheckboxRecords"
        ></CustomizeTable>
      </div>
      <ElPagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[100, 200, 300, 400, 500]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="allTotal"
        style="margin: 10px auto 0; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></ElPagination>
    </div>
  </div>

  <LogDialog
    :title="editForm.id ? '编辑物流报价' : '新增物流报价'"
    dialogWidth="1000px"
    v-model="dialogVisible"
    @close="cancelFn"
  >
    <CustomizeForm
      ref="editFormRef"
      v-model="editForm"
      :config="formConfig"
      formItemWidth="100%"
    >
    </CustomizeForm>

    <template #footer>
      <div style="text-align: center">
        <ElButton @click="cancelFn">取消</ElButton>

        <ElButton type="primary" @click="save">保存</ElButton>
      </div>
    </template>
  </LogDialog>

  <LogDialog
    title="操作日志"
    v-model="logDialogVisible"
    @close="logDialogVisible = false"
  >
    <div v-for="item in logList" :key="item.id" style="margin-bottom: 8px">
      <span style="margin-right: 10px">{{ item.createTime }}</span>
      <span>{{ item.description }}</span>
    </div>
  </LogDialog>
</template>

<script setup lang="tsx">
defineOptions({
  name: 'LogisticsQuotation',
})
import {
  getlogisticsWayAllList,
  getlogisticsQuotationList,
  addLogisticsQuotation,
  updateLogisticsQuotation,
  deleteLogisticsQuotation,
  importLogisticsQuotation,
  downloadLogisticsQuotationTemplate,
  getLogisticsLog,
  getlogisticsQuotationPage,
} from '@/api/logistics'
import { ISeachFormConfig } from '@/types/searchType'
import { TableColumn } from '@/components/VxeTable'

import SearchForm from '@/components/SearchForm.tsx'
import LogDialog from './components/LogDialog.tsx'
import CustomizeForm from '@/components/CustomizeForm.tsx'
import CustomizeTable from '@/components/VxeTable.tsx'
import type { VxeTablePropTypes } from 'vxe-table'
// import usePageList from '@/utils/hooks/usePageList'
import { useValue } from './hooks/useValue'
import { showConfirm } from '@/utils/ui'
import { Edit, List } from '@element-plus/icons-vue'
import { debounce } from 'lodash-es'
import { LogisticsQuotation } from './types/logisticsQuotation'
const [searchForm] = useValue({ logisticsIdList: [] })
const [editForm, resetEditForm] = useValue<LogisticsQuotation>({
  unit: 'oz',
})
// const {
//   loading,
//   currentPage,
//   pageSize,
//   data,
//   total,
//   refresh: search,
//   onCurrentPageChange: handleCurrentChange,
//   onPageSizeChange: handleSizeChange,
// } = usePageList({
//   query: (page, pageSize) =>
//     getlogisticsQuotationPage({
//       ...searchForm.value,
//       pageSize: pageSize,
//       currentPage: page,
//     }).then(({ data }) => {
//       return data
//     }),
// })

const allTotal = ref(0)
const dialogVisible = ref(false)
const formVisible = ref(false)
const editFormRef = ref<InstanceType<typeof CustomizeForm> | null>(null)
const selection = ref([])
const mergeCells = ref<VxeTablePropTypes.MergeCells>([])
const tableData = ref<LogisticsQuotation[]>([])
const currentPage = ref<number>(1)
const pageSize = ref<number>(100)
const loading = ref<boolean>(false)
const searchConfig = computed<ISeachFormConfig[]>(() => [
  {
    prop: 'logisticsIdList',
    type: 'select',
    label: '物流方式',

    attrs: {
      placeholder: '请选择物流方式',
      multiple: true,
      clearable: true,
      value: 'id',
      label: 'name',
      collapseTags: true,
      collapseTagsTooltip: true,
      options: [...(logisticsWayList.value || [])],
    },
  },
])

const formConfig = computed(() => [
  {
    prop: 'logistics',
    type: 'select',
    label: '物流方式',

    attrs: {
      placeholder: '请选择物流方式',
      value: 'name',
      label: 'name',
      options: [...(logisticsWayList.value || [])],
      disabled: editForm.value?.['id'] ? true : false,
      onChange: (val: { name: string; id: number }) => {
        editForm.value['logisticsId'] = val.id
      },
    },
    rules: [{ required: true, message: '请选择物流方式' }],
  },
  {
    prop: 'rate',
    type: 'amountInput',
    label: 'Rate(oz/LB)',
    attrs: {
      placeholder: '请输入Rate(oz/LB)',
      disabled: editForm.value?.['id'] ? true : false,
      hasSuffix: false,
      hasAppend: true,
      appendRender: () => {
        return h(
          ElSelect,
          {
            modelValue: editForm.value['unit'],
            'onUpdate:modelValue': (val) => (editForm.value['unit'] = val),
            disabled: editForm.value['id'] ? true : false,
            placeholder: 'Select',
            style: { width: '115px' },
          },
          () => [
            h(ElOption, { label: 'oz', value: 'oz' }),
            h(ElOption, { label: 'LB', value: 'LB' }),
          ],
        )
      },
    },
    rules: [{ required: true, message: '请输入Rate' }],
  },
  {
    prop: 'zone1',
    type: 'amountInput',
    label: 'ZONE 1($)',
    attrs: {
      hasSuffix: false,
      placeholder: '请输入ZONE 1',
    },
  },
  {
    prop: 'zone2',
    type: 'amountInput',
    label: 'ZONE 2($)',
    attrs: {
      hasSuffix: false,
      placeholder: '请输入ZONE 2',
    },
  },
  {
    prop: 'zone3',
    type: 'amountInput',
    label: 'ZONE 3($)',
    attrs: {
      hasSuffix: false,
      placeholder: '请输入ZONE 3',
    },
  },
  {
    prop: 'zone4',
    type: 'amountInput',
    label: 'ZONE 4($)',
    attrs: {
      hasSuffix: false,
      placeholder: '请输入ZONE 4',
    },
  },
  {
    prop: 'zone5',
    type: 'amountInput',
    label: 'ZONE 5($)',
    attrs: {
      hasSuffix: false,
      placeholder: '请输入ZONE 5',
    },
  },
  {
    prop: 'zone6',
    type: 'amountInput',
    label: 'ZONE 6($)',
    attrs: {
      hasSuffix: false,
      placeholder: '请输入ZONE 6',
    },
  },
  {
    prop: 'zone7',
    type: 'amountInput',
    label: 'ZONE 7($)',
    attrs: {
      hasSuffix: false,
      placeholder: '请输入ZONE 7',
    },
  },
  {
    prop: 'zone8',
    type: 'amountInput',
    label: 'ZONE 8($)',
    attrs: {
      hasSuffix: false,
      placeholder: '请输入ZONE 8',
    },
  },
  {
    prop: 'zone9',
    type: 'amountInput',
    label: 'ZONE 9($)',
    attrs: {
      hasSuffix: false,
      placeholder: '请输入ZONE 9',
    },
  },
])

const tableConfig = ref<TableColumn[]>([
  {
    prop: 'rateType',
    label: 'Rate(oz/LB)',
    attrs: {
      align: 'center',
      width: 100,
    },
  },
  {
    prop: 'rateG',
    label: 'Rate(g)',
  },

  {
    prop: 'rateKg',
    label: 'Rate(kg)',
  },

  {
    prop: 'logistics',
    label: 'Logistics',
  },
  {
    prop: 'zone1',
    label: 'ZONE 1($)',
  },
  {
    prop: 'zone2',
    label: 'ZONE 2($)',
  },
  {
    prop: 'zone3',
    label: 'ZONE 3($)',
  },
  {
    prop: 'zone4',
    label: 'ZONE 4($)',
  },
  {
    prop: 'zone5',
    label: 'ZONE 5($)',
  },
  {
    prop: 'zone6',
    label: 'ZONE 6($)',
  },
  {
    prop: 'zone7',
    label: 'ZONE 7($)',
  },
  {
    prop: 'zone8',
    label: 'ZONE 8($)',
  },
  {
    prop: 'zone9',
    label: 'ZONE 9($)',
  },

  {
    prop: 'opeare',
    label: '操作',
    attrs: {
      align: 'center',
    },
    render: {
      default: ({ row }) => (
        <div>
          <el-icon
            size="24"
            title="编辑"
            color="#EF6C00"
            style="cursor: pointer; vertical-align: middle"
            onclick={() => editWay(row)}
          >
            <Edit />
          </el-icon>
          <el-icon
            size="24"
            title="日志"
            color="#008aff"
            style="cursor: pointer; vertical-align: middle"
            onclick={() => showLog(row as unknown as LogisticsQuotation)}
          >
            <List />
          </el-icon>
        </div>
      ),
    },
  },
])

/**
 * @description: 监听表格合并单元格数据
 */
// watch(
//   () => data.value as LogisticsQuotation[],
//   (val) => {
//     console.log(1111111111111)
//     const isEqual =
//       JSON.stringify(searchForm.value) ===
//       JSON.stringify({ logisticsIdList: [] })
//     if (isEqual) {
//       tableData.value = [...val]
//       allTotal.value = total.value as number
//       mergeCells.value = []
//     }
//   },

//   { deep: true },
// )

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

async function search() {
  // loading.value = true
  const isEqual =
    JSON.stringify(searchForm.value) === JSON.stringify({ logisticsIdList: [] })
  try {
    if (isEqual) {
      await getList()
    } else {
      await getSearchList()
    }
  } catch (e) {
    console.log(e)
  } finally {
    // loading.value = false
  }
}

/**
 * @description: 转换表格数据
 */
function getTableData(arr: LogisticsQuotation[]) {
  if (!arr.length) return []
  return arr.flatMap((parentItem, index) => {
    const quotations = parentItem.logisticsQuotationList
    if (!quotations?.length) return []
    return quotations.map((quotation) => ({
      ...quotation,
      seq: index + 1,
    }))
  })
}

/**
 * @description: 取消按钮
 */
function cancelFn() {
  dialogVisible.value = false
  // editFormRef.value?.resetFields()
  formVisible.value = false
  resetEditForm()
}

/**
 * @description: 编辑按钮
 */
async function editWay(item: LogisticsQuotation) {
  try {
    editForm.value = { ...item }
    console.log(432, editForm.value)
    editFormRef.value?.refashConfig()
    dialogVisible.value = true
  } catch (e) {
    console.log(e)
  }
}

/**
 * @description: 检查数据
 */
async function checkData() {
  const [isValid, postData] = await Promise.all([
    new Promise<boolean>((resolve) => {
      editFormRef.value
        ?.validate()
        .then(() => resolve(true))
        .catch((err) => {
          resolve(false)
          console.log(err)
        })
    }),
    new Promise<LogisticsQuotation>((resolve) => {
      const params = { ...editForm.value }

      resolve(params)
    }),
  ])
  console.log(isValid, postData)

  return { isValid, postData }
}

/**
 * @description: 保存提交表单数据
 */
const save = debounce(async () => {
  const { isValid, postData } = await checkData()
  if (isValid) {
    try {
      if (!postData.id) {
        await addLogisticsQuotation({
          ...postData,
        })
      } else {
        await updateLogisticsQuotation({
          ...postData,
        })
      }
      ElMessage({
        message: postData.id ? '更新成功' : '新增成功',
        type: 'success',
      })

      cancelFn()
      search()
    } catch (e) {
      return
    }
  }
}, 400)

/**
 * @description: 新增按钮打开弹窗
 */
async function addDialog() {
  // await getAllList()
  formVisible.value = true

  dialogVisible.value = true

  console.log(502, editForm.value)
}

/**
 * @description: 删除按钮
 */
async function deleteFn() {
  try {
    if (!selection.value.length) {
      return ElMessage({
        message: '请选择物流报价',
        type: 'warning',
      })
    }

    await showConfirm('是否删除物流报价', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const isEqual =
      JSON.stringify(searchForm.value) ===
      JSON.stringify({ logisticsIdList: [] })
    let ids
    if (isEqual) {
      ids = {
        ids: selection.value.map((item: { id: number }) => item.id).join(','),
      }
    } else {
      console.log(589, selection.value)
      const rateTypes = selection.value.map(
        (item: { rateType: string }) => item.rateType,
      )
      const data = templeData.value.filter((item) =>
        rateTypes.includes(item.rateType as string),
      )
      ids = {
        ids: getTableData(data)
          .map((item) => item.id)
          .join(','),
      }
    }
    await deleteLogisticsQuotation(ids)
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    search()
  } catch (e) {
    search()
    ElMessage({
      message: '删除失败',
      type: 'error',
    })
    // showError(e)
  }
}

/**
 * @description: 获取选中数据
 */
function handleCheckboxRecords(value: never[]) {
  console.log(351, value)
  selection.value = value
}

/**
 * @description: 获取物流方式列表
 */

const logisticsWayList = ref([])
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) {
              logisticsWayList.value = [...(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 downloadLogisticsQuotationTemplate()

    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)
    formData.append('type', 'add')

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

/**
 * @description: 更新文件
 */
async function updateExcel(file: { file: File }) {
  try {
    const formData = new FormData()
    formData.append('file', file.file)
    formData.append('type', 'update')

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

function handleCurrentChange(val: number) {
  currentPage.value = val
  search()
}

function handleSizeChange(val: number) {
  pageSize.value = val
  search()
}

async function getList() {
  loading.value = true
  try {
    const { data } = await getlogisticsQuotationPage({
      ...searchForm.value,
      pageSize: pageSize.value,
      currentPage: currentPage.value,
    })
    tableData.value = [...(data as { records: LogisticsQuotation[] }).records]

    allTotal.value = (data as { total: number }).total
    mergeCells.value = []
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}
const templeData = ref<LogisticsQuotation[]>([])
async function getSearchList() {
  loading.value = true
  try {
    const { data } = await getlogisticsQuotationList({
      ...searchForm.value,
      pageSize: pageSize.value,
      currentPage: currentPage.value,
    })
    templeData.value = [...(data as { records: LogisticsQuotation[] }).records]
    tableData.value = getTableData([
      ...(data as { records: LogisticsQuotation[] }).records,
    ])

    allTotal.value = (data as { total: number }).total
    let startRow = 0
    const newMergeCells = []
    console.log(477, tableData.value)

    for (
      let i = 0;
      i < (data as { records: LogisticsQuotation[] }).records.length;
      i++
    ) {
      const item = (data as { records: LogisticsQuotation[] }).records[i]
      const rowspan = item.logisticsQuotationList?.length || 0
      if (rowspan > 0) {
        for (let col = 0; col < 5; col++) {
          newMergeCells.push({
            row: startRow,
            col: col,
            rowspan: rowspan,
            colspan: 1,
          })
        }
        startRow += rowspan
      }
    }

    mergeCells.value = newMergeCells
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

/**
 * @description: 日志弹窗
 */
interface LogList {
  id?: number
  createTime?: string
  description?: string
}
const logList = ref<LogList[]>([])

const logDialogVisible = ref(false)
async function showLog(row: LogisticsQuotation) {
  logDialogVisible.value = true
  try {
    const { data } = await getLogisticsLog({
      logType: 'logistics_quotation',
      relaId: row.id as number,
    })
    logList.value = data
  } catch (error) {
    console.log(error)
  }
}
</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>
