<template>
  <div class="delivery-note-page flex-column card 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.subOrderNumber"
            clearable
            placeholder="请输入生产单号"
            style="width: 160px"
          />
        </ElFormItem>

        <ElFormItem label="订单号">
          <ElInput
            v-model="searchForm.orderNumber"
            placeholder="订单号"
            clearable
            style="width: 160px"
          ></ElInput>
        </ElFormItem>
        <ElFormItem label="发货单号">
          <ElInput
            v-model="searchForm.billNumber"
            clearable
            placeholder="请输入发货单号"
            style="width: 160px"
          />
        </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
            v-loading="btnLoading"
            type="success"
            @click="onConfirmDateRange"
            >导出发货单
          </ElButton>
        </ElFormItem>
        <!-- <ElFormItem>
          <ElButton type="primary" @click="generateStatement"
          >生成对账单
          </ElButton
          >
        </ElFormItem> -->
      </ElForm>
    </div>
    <div class="delivery-note-content flex-1 flex-column overflow-hidden">
      <div class="delivery-note-list flex-1 overflow-hidden">
        <ElTable
          :data="tableData"
          default-expand-all
          style="width: 100%; height: 100%"
          border
          :cell-class-name="onCellClassName"
          @selection-change="handleSelectionChange"
        >
          <ElTableColumn
            type="selection"
            width="50"
            header-align="center"
            align="center"
          ></ElTableColumn>
          <ElTableColumn
            type="index"
            label="序号"
            width="60"
            header-align="center"
            align="center"
          ></ElTableColumn>
          <ElTableColumn
            label="发货单号"
            show-overflow-tooltip
            prop="billNumber"
            header-align="center"
            align="center"
            width="180"
          ></ElTableColumn>
          <ElTableColumn
            label="发货单信息"
            header-align="center"
            prop="billNumberInfo"
            min-width="300"
          >
            <template #default="scope">
              <div class="send-order-column">
                <div
                  v-for="od in scope.row.detailList"
                  :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>
          </ElTableColumn>
          <ElTableColumn
            label="物流信息"
            header-align="center"
            prop="logisticsInfo"
          >
            <template #default="{ 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>
          </ElTableColumn>
          <ElTableColumn
            label="操作"
            header-align="center"
            align="center"
            prop="operation"
            width="180"
          >
            <template #default="{ row }">
              <div>
                <ElButton link @click="onViewOrder(row)">查看订单 </ElButton>
              </div>
            </template>
          </ElTableColumn>
        </ElTable>
      </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>
  </div>

  <ElDrawer
    v-model="orderDetailDialogVisible"
    title="查看订单"
    direction="rtl"
    size="40%"
    :close-on-click-modal="false"
  >
    <OrderDetail :order-detail-data="orderDetailData" />
  </ElDrawer>
</template>

<script setup lang="ts">
import { DocumentCopy } from '@element-plus/icons-vue'
import {
  DeliveryNoteSearchForm,
  DeliveryNoteData,
} from '@/types/api/deliveryNote'
import { OrderData } from '@/types/api/order'
import usePageList from '@/utils/hooks/usePageList'
import { useValue } from '@/utils/hooks/useValue'
import {
  getDeliveryNoteList,
  printDeliveryNote,
  getOrderByIdApi,
} from '@/api/order'
import { getUserMarkList } from '@/api/auth'
import { ref, onMounted } from 'vue'
import { val } from '@/utils'
// import { showConfirm } from '@/utils/ui'
import { filePath } from '@/api/axios'
import { type CellCls, ElMessage } from 'element-plus'
import OrderDetail from './order/OrderDetail.vue'
import { useEnterKeyTrigger } from '@/utils/hooks/useEnterKeyTrigger.ts'

const [searchForm, resetSearchForm] = useValue<DeliveryNoteSearchForm>({})
const selection = ref<DeliveryNoteData[]>([])
const dateRange = ref<string[]>([])
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' },
    { label: '质检(通过)', key: 'passNum' },
    { label: '质检(不通过)', key: 'notPassNum' },
  ],
]

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 btnLoading = ref<boolean>(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 getNameSpaceList = async () => {
  try {
    const res = await getUserMarkList()
    nameSpaceList.value = res.data
  } catch (e) {
    // showError(e)
  }
}
const dialogVisible = ref(false)
const handleSelectionChange = (s: DeliveryNoteData[]) => {
  selection.value = s
}

const onConfirmDateRange = async () => {
  if (dateRange.value.length === 0) {
    return ElMessage({
      message: '请选择时间',
      type: 'warning',
      offset: window.innerHeight / 2,
    })
  }
  btnLoading.value = true
  try {
    const res = await printDeliveryNote(
      dateRange.value,
      searchForm.value?.userMark,
    )
    window.open(filePath + res.message)
    dateRange.value = []
    dialogVisible.value = false
    search()
    btnLoading.value = false
  } catch (e) {
    // showError(e)
    btnLoading.value = false
  }
}
// const generateStatement = async () => {
//   if (selection.value.length === 0) {
//     return ElMessage({
//       message: '请选择数据后生成',
//       type: 'warning',

//     })
//   }
//   try {
//     await showConfirm('是否生成对账单？', {
//       confirmButtonText: '确认',
//       cancelButtonText: '取消',
//       type: 'warning',
//     })
//   } catch {
//     return
//   }
//   try {
//     await createReconciliation({ shipmentIdList: selection.value.map(el => el.id) })
//     search()
//     ElMessage.success('操作成功')
//   } catch (e) {
//     //showError(e)
//     btnLoading.value = false
//   }
// }

const onCellClassName: CellCls<DeliveryNoteData> = ({ column }) => {
  if (
    column.property === 'billNumberInfo' ||
    column.property === 'logisticsInfo' ||
    column.property === 'operation'
  ) {
    return 'vertical-align-top'
  } else {
    return ''
  }
}
// const onViewProductionOrder = async (item: DetailList) => {
//   try {
//     const res = await getProductionOrderList(item.subOrderNumber as string)
//   } catch (e) {
//     showError(e)
//   }
// }
const orderDetailDialogVisible = ref(false)
const orderDetailData = ref<OrderData>({} as OrderData)
const onViewOrder = async (item: DeliveryNoteData) => {
  try {
    const res = await getOrderByIdApi(item.detailList[0]?.customOrderId)
    orderDetailData.value = res.data
    orderDetailDialogVisible.value = true
  } catch (e) {
    //showError(e)
  }
}
const copy = (text: string) => {
  navigator.clipboard.writeText(text)
  ElMessage.success('复制成功')
}

/**
 * @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>
