<template>
  <div class="card flex-column h-100 overflow-hidden">
    <div class="header-filter-form">
      <ElForm ref="searchFormRef" :model="searchForm" inline>
        <ElFormItem label="发货时间">
          <el-date-picker
            :default-time="[
              new Date(0, 0, 0, 0, 0, 0),
              new Date(0, 0, 0, 23, 59, 59),
            ]"
            v-model="dateRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            clearable
            style="width: 360px"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </ElFormItem>
        <ElFormItem label="客户">
          <ElSelect
            v-model="searchForm.userMark"
            clearable
            placeholder="请选择客户"
            style="width: 160px"
          >
            <ElOption
              v-for="item in nameSpaceList"
              :key="item"
              :label="item"
              :value="item"
            ></ElOption>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="订单号">
          <ElInput
            v-model="searchForm.factoryOrderNumber"
            clearable
            placeholder="请输入订单号"
            style="width: 160px"
          />
        </ElFormItem>

        <ElFormItem label="子单号">
          <ElInput
            v-model="searchForm.factorySubOrderNumber"
            placeholder="子订单"
            clearable
            style="width: 160px"
          ></ElInput>
        </ElFormItem>
        <ElFormItem label="收货人">
          <ElInput
            v-model="searchForm.lanshouName"
            clearable
            placeholder="请输入收货人"
            style="width: 160px"
          />
        </ElFormItem>
        <ElFormItem label="送货方式">
          <ElSelect
            v-model="searchForm.shippingWay"
            clearable
            placeholder="请选择送货方式"
            style="width: 160px"
          >
            <ElOption label="快递" :value="2"></ElOption>
            <ElOption label="送货上门" :value="1"></ElOption>
          </ElSelect>
        </ElFormItem>

        <ElFormItem label="物流跟踪号" prop="logisticsTracking">
          <ElInput
            v-model="searchForm.logisticsTracking"
            placeholder="请输入物流跟踪号"
            clearable
            style="width: 160px"
          />
        </ElFormItem>
        <ElFormItem>
          <ElButton ref="searchBtnRef" type="primary" @click="search"
            >查询</ElButton
          >
        </ElFormItem>
        <ElFormItem>
          <ElButton @click="resetSearchForm">重置</ElButton>
        </ElFormItem>
        <ElFormItem>
          <ElButton type="success" @click="onConfirmDateRange"
            >导出发货单</ElButton
          >
        </ElFormItem>
      </ElForm>
    </div>
    <div class="delivery-note-content flex-1 flex-column overflow-hidden">
      <div class="delivery-note-list flex-1 overflow-hidden">
        <TableView
          :paginated-data="tableData"
          :columns="tableColumns"
          :cell-class-name="onCellClassName"
        >
          <template #deliveryNote="{ row }">
            <div class="send-order-column">
              <div
                v-for="od in row.shipmentDetails"
                :key="od.id"
                class="send-order-product-item"
              >
                <div class="send-order-product-image">
                  <img :src="od.variantImage" :alt="od.productName" />
                </div>
                <div
                  v-for="(p, i) in productProps"
                  :key="i"
                  class="send-order-prop-list"
                >
                  <div
                    v-for="(pi, index) in p"
                    :key="index"
                    :title="pi.label + '：' + val(od, pi.key || '')"
                    class="send-order-prop-item"
                  >
                    <span> {{ pi.label }}：{{ val(od, pi.key || '') }} </span>
                    <el-icon
                      v-if="pi.copyable"
                      class="icon"
                      @click="copy(val(od, pi.key || ''))"
                    >
                      <DocumentCopy />
                    </el-icon>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <template #logisticsInfo="{ row }">
            <div class="send-order-logistics">
              <div
                v-for="pi in logisticsProps"
                :key="pi.label"
                :title="pi.label + '：' + val(row, pi.key)"
                class="send-order-prop-item"
              >
                <span v-if="val(row, pi.key)"
                  >{{ pi.label }}：{{ val(row, pi.key) }}</span
                >
                <el-icon
                  v-if="pi.copyable && val(row, pi.key)"
                  class="icon"
                  @click="copy(val(row, pi.key || ''))"
                >
                  <DocumentCopy />
                </el-icon>
              </div>
            </div>
          </template>
          <template #operate="{ row }">
            <el-button type="text" @click="showDetail(row)">查看详情</el-button>
          </template>
        </TableView>
      </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="total"
        style="margin: 10px auto 0; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></ElPagination>
    </div>
    <ElDrawer
      v-model="detailVisible"
      title="查看详情"
      direction="rtl"
      size="40%"
      :close-on-click-modal="false"
    >
      <OrderDetail :order-detail-data="orderDetailData" />
    </ElDrawer>
  </div>
</template>

<script lang="tsx" setup>
import { getUserMarkList } from '@/api/auth'
import {
  getDeliveryNoteList,
  printDeliveryNote,
  getPodJomallOrderByFactoryNumber,
} from '@/api/podOrder'
import TableView from '@/components/TableView.vue'
import {
  DeliveryNoteData,
  PodDeliveryNoteSearchForm,
} from '@/types/api/podOrder'
import { useEnterKeyTrigger } from '@/utils/hooks/useEnterKeyTrigger.ts'

import usePageList from '@/utils/hooks/usePageList'
import { computed, onMounted, ref } from 'vue'
import { val } from '@/utils'
import { CellCls } from 'element-plus'
import { useValue } from '@/utils/hooks/useValue'
import { filePath } from '@/api/axios'
import OrderDetail from './OrderDetail.vue'
import { OrderData } from '@/types/api/order.ts'
const [searchForm, resetSearchForm] = useValue<PodDeliveryNoteSearchForm>({})
const dateRange = ref<string[]>([])
const orderDetailData = ref<OrderData | undefined>()
const detailVisible = ref(false)
const {
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) =>
    getDeliveryNoteList(
      {
        ...searchForm.value,
        startTime: dateRange.value && dateRange.value[0],
        endTime: dateRange.value && dateRange.value[1],
      },
      page,
      pageSize,
    ).then((res) => res.data),
})
const nameSpaceList = ref<string[]>([])
onMounted(() => {
  getNameSpaceList()
})

const showDetail = async (row: DeliveryNoteData) => {
  const { data } = await getPodJomallOrderByFactoryNumber(
    row.factoryOrderNumber as string,
  )
  detailVisible.value = true
  orderDetailData.value = data
}
const getNameSpaceList = async () => {
  try {
    const res = await getUserMarkList()
    nameSpaceList.value = res.data
  } catch (e) {
    // showError(e)
    console.error(e)
  }
}
const tableColumns = computed(() => {
  return [
    {
      label: '序号',
      type: 'index',
      width: 60,
      align: 'center',
    },
    {
      label: '发货单号',
      prop: 'shipmentNumber',
      align: 'center',
      width: 180,
    },
    {
      label: '订单号',
      prop: 'factoryOrderNumber',
      align: 'center',
      width: 180,
    },
    {
      label: '发货单信息',
      minWidth: 280,
      prop: 'shipmentNumberInfo',
      slot: 'deliveryNote',
    },
    {
      label: '物流信息',
      prop: 'logisticsInfo',
      width: 280,
      slot: 'logisticsInfo',
    },
    {
      label: '操作',
      prop: 'action',
      width: 100,
      slot: 'operate',
    },
  ]
})
const productProps = [
  [
    { label: '商品名', key: 'productName' },
    { label: 'Base SKU', key: 'baseSku', copyable: true },
    { label: '变体SKU', key: 'variantSku', copyable: true },
  ],
  [{ label: '生产单号', key: 'subOrderNumber', copyable: true }],
  [
    // { label: '生产数', key: 'productionNum' },
    { label: '发货数', key: 'shipmentNum' },
  ],
]
const logisticsProps = [
  { label: '订单号', key: 'orderNumber', copyable: true },
  {
    label: '发货方式',
    key: (d: DeliveryNoteData) =>
      d.shippingWay && { 1: '送货上门', 2: '快递' }[d.shippingWay],
  },
  {
    label: '物流跟踪号',
    key: 'logisticsTracking',
    copyable: true,
  },
  { label: '创建时间', key: 'createTime' },
  { label: '收货人', key: 'lanshouName' },
  { label: '收货人电话', key: 'lanshouPhone' },
  { label: '邮编', key: 'lanshouPost' },
  {
    label: '收货地址',
    key: (d: DeliveryNoteData) =>
      `${d.lanshouRegion || ''}${d.lanshouAddress || ''}`,
  },
]
const onCellClassName: CellCls<DeliveryNoteData> = ({ column }) => {
  console.log('column', column.property)
  if (
    column.property === 'shipmentNumberInfo' ||
    column.property === 'logisticsInfo' ||
    column.property === 'operation'
  ) {
    return 'vertical-align-top'
  } else {
    return ''
  }
}
const copy = (text: string) => {
  navigator.clipboard.writeText(text)
  ElMessage.success('复制成功')
}
const onConfirmDateRange = async () => {
  if (dateRange.value.length === 0) {
    return ElMessage({
      message: '请选择时间',
      type: 'warning',
      offset: window.innerHeight / 2,
    })
  }
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    const res = await printDeliveryNote(
      dateRange.value,
      searchForm.value?.userMark,
    )
    window.open(filePath + res.message)
    dateRange.value = []
    search()
  } catch (e) {
    // showError(e)
    console.error(e)
  } finally {
    loading.close()
  }
}

/**
 * @description: 页面添加回车监听
 */
const searchFormRef = ref()

const searchBtnRef = ref()

useEnterKeyTrigger({
  formRef: searchFormRef,
  btnRef: searchBtnRef,

  callback: (event: KeyboardEvent) => {
    console.log('回车键被按下', event)
    search()
  },
})
</script>

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

  :deep(.el-form-item) {
    margin-right: 14px;
    margin-bottom: 10px;
  }
}

$border: solid 1px #ddd;

.send-order-list {
  display: grid;
  grid-template-columns: 2fr 1fr;
  border-left: $border;
  border-top: $border;
}

.send-order-column {
  padding: 10px 16px;
  line-height: 1.5;
}

.send-order-header {
  font-weight: bold;
  text-align: center;
  background-color: #f8f8f9;
}

.send-order-product-item {
  display: flex;
  justify-content: space-between;
  gap: 20px;

  &:not(:first-child) {
    border-top: $border;
    padding: 10px 0;
  }

  .send-order-prop-list {
    flex: 1;
  }
}

.send-order-product-image {
  width: 100px;
}

.dialog-footer {
  text-align: center;
}

.delivery-note-list {
  :deep(.vertical-align-top) {
    vertical-align: top;
  }
}
</style>
