<script setup lang="ts">
import {
  factoryWarehouseInfo,
  warehouseInfo,
  warehouseInfoGetAll,
} from '@/api/warehouse.ts'
import { getListCraftApi, getProductionClientApi } from '@/api/podUsOrder'
import {
  SearchForm,
  CraftListData,
  ProductionClient,
} from '@/types/api/podUsOrder'
import platformJson from '../../../json/platform.json'
import dayjs from 'dayjs'
import { getUserMarkList } from '@/api/common'
import { CaretBottom, CaretTop, DocumentCopy } from '@element-plus/icons-vue'
import SplitDiv from '@/components/splitDiv/splitDiv.vue'

import { useValue } from '@/utils/hooks/useValue'

const [searchForm, resetSearchForm] = useValue<SearchForm>({
  timeType: 1,
  shopNumber: '',
  shipmentType: '',
  userMark: '',
  logisticsTracking: '',
  baseSku: '',
  factoryOrderNumber: '',
  sku: '',
  factorySubOrderNumber: '',
  status: '',
  customizedQuantity: '',
  multi: null,
  startTime: null,
  endTime: null,
  exceptionHandling: undefined,
  platform: '',
  productionClient: '',
  warehouseId: '',
  thirdSkuCode: '',
  supplierProductNo: '',
  batchArrangeNumber: '',
  craftCode: '',
  thirdStockSku: '',
})
const tableColumns = computed(() => {
  return [
    {
      label: '商品',
      prop: 'goods',
      slot: 'goods',
      minWidth: 920,
    },
    {
      label: '订单详情',
      prop: 'orderDetail',
      slot: 'orderDetail',
      width: 300,
    },
    {
      label: '单价',
      slot: 'price',
      width: 160,
      prop: 'price',
      align: 'left',
    },
    {
      label: '时间',
      slot: 'time',
      width: 180,
      prop: 'time',
      align: 'left',
    },

    {
      label: '异常原因',
      width: 300,
      prop: 'exceptionReason',
      slot: 'exceptionReason',
      align: 'left',
    },
  ]
})
const tableData = ref([])
const searchVisible = ref(false)

const warehouseList = ref<warehouseInfo[]>([])
const timeRange = ref<string[]>([])
const pickerOptions = {
  shortcuts: [
    {
      text: '今日',
      value: () => getDateRange(0),
    },
    {
      text: '昨天',
      value: () => getDateRange(1),
    },
    {
      text: '最近7天',
      value: () => getDateRange(6),
    },
    {
      text: '最近14天',
      value: () => getDateRange(13),
    },
    {
      text: '最近30天',
      value: () => getDateRange(29),
    },
    {
      text: '本周',
      value: () => getWeekRange(0),
    },
    {
      text: '上周',
      value: () => getWeekRange(1),
    },
    {
      text: '本月',
      value: () => getMonthRange(0),
    },
    {
      text: '上月',
      value: () => getMonthRange(1),
    },
    {
      text: '历史',
      value: () => {
        const end = dayjs().endOf('day').toDate()
        const start = dayjs('2000-01-01').startOf('day').toDate()
        return [start, end]
      },
    },
  ],
}

const pagination = ref<factoryWarehouseInfo>({
  pageSize: 50,
  currentPage: 1,
  total: 0,
})
const search = () => {}

const getDateRange = (days = 0, type: 'past' | 'future' = 'past') => {
  const end = dayjs()
  const start =
    type === 'past' ? end.subtract(days, 'day') : end.add(days, 'day')
  return [start.startOf('day').toDate(), end.endOf('day').toDate()]
}
const getMonthRange = (months = 0, type: 'past' | 'future' = 'past') => {
  const now = dayjs()
  const start =
    type === 'past' ? now.subtract(months, 'month') : now.add(months, 'month')
  return [start.startOf('month').toDate(), start.endOf('month').toDate()]
}
const getWeekRange = (weeks = 0, type: 'past' | 'future' = 'past') => {
  const now = dayjs()
  const start =
    type === 'past' ? now.subtract(weeks, 'week') : now.add(weeks, 'week')
  return [start.startOf('week').toDate(), start.endOf('week').toDate()]
}

async function getData() {}

const copy = (text: string) => {
  navigator.clipboard.writeText(text)
  ElMessage.success('复制成功')
}
const handleSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize
  getData()
}
const handleCurrentChange = (currentPage: number) => {
  pagination.value.currentPage = currentPage
  getData()
}

const productionClient = ref<ProductionClient[]>()

const loadProductionClient = async () => {
  try {
    const res = await getProductionClientApi()
    if (res.code !== 200) return
    productionClient.value = res.data
  } catch (e) {
    console.error(e)
  }
}

const getWarehouse = async () => {
  const { data } = await warehouseInfoGetAll()
  warehouseList.value = data
}
const userMarkList = ref<string[]>([])
const getUserMark = async () => {
  try {
    const res = await getUserMarkList()
    userMarkList.value = res.data
  } catch (error) {
    //showError(error)
  }
}

const craftList = ref<CraftListData[]>([])

const loadCraftList = async () => {
  try {
    const res = await getListCraftApi()
    if (res.code !== 200) return
    craftList.value = res.data
  } catch (e) {
    console.error(e)
  }
}
loadProductionClient()
getUserMark()
loadCraftList()
getData()
getWarehouse()
</script>

<template>
  <split-div>
    <template #top>
      <el-card>
        <ElForm :model="searchForm" size="default" inline class="search-form">
          <div>
            <ElFormItem label="仓库">
              <ElSelect
                v-model="searchForm.warehouseId"
                clearable
                filterable
                placeholder="请输入"
                style="width: 150px"
              >
                <el-option
                  v-for="item in warehouseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </ElSelect>
            </ElFormItem>
            <ElFormItem label="平台">
              <ElSelect
                v-model="searchForm.platform"
                value-key=""
                placeholder="请选择"
                clearable
                filterable
                popper-class="customize-select-style"
                style="width: 150px"
              >
                <ElOption
                  v-for="(item, index) in platformJson"
                  :key="index"
                  :label="item.type"
                  :value="item.type"
                  style="width: 160px"
                >
                  <img
                    :src="`/images/icon/${item.icon.split('/').pop()}`"
                    style="height: 20px; margin: 5px 10px 0 0"
                  />
                  <span :title="item.type">{{ item.type }}</span>
                </ElOption>
              </ElSelect>
            </ElFormItem>

            <ElFormItem label="工艺">
              <ElSelect
                v-model="searchForm.craftCode"
                clearable
                filterable
                placeholder="请输入工艺"
                style="width: 150px"
              >
                <el-option
                  v-for="item in craftList"
                  :key="item.craftCode"
                  :label="item.craftName"
                  :value="item.craftCode"
                ></el-option>
              </ElSelect>
            </ElFormItem>
            <ElFormItem label="库存SKU">
              <ElInput
                v-model.trim="searchForm.thirdSkuCode"
                placeholder="库存SKU"
                clearable
                style="width: 150px"
              ></ElInput>
            </ElFormItem>
            <ElFormItem label="款号">
              <ElInput
                v-model="searchForm.supplierProductNo"
                placeholder="款号"
                clearable
                style="width: 150px"
              />
            </ElFormItem>
            <ElFormItem label="批次号">
              <ElInput
                v-model="searchForm.batchArrangeNumber"
                placeholder="批次号"
                clearable
                style="width: 150px"
              />
            </ElFormItem>
            <ElFormItem label="生产单号">
              <ElInput
                v-model="searchForm.factorySubOrderNumber"
                placeholder="生产单号"
                clearable
                style="width: 150px"
              />
            </ElFormItem>
            <ElFormItem label="店铺单号">
              <ElInput
                v-model="searchForm.shopNumber"
                placeholder="店铺单号"
                clearable
                style="width: 150px"
              />
            </ElFormItem>
          </div>
          <ElFormItem label="类型">
            <el-radio-group v-model="searchForm.customizedQuantity">
              <el-radio-button label="single">单面</el-radio-button>
              <el-radio-button label="multiple">多面</el-radio-button>
            </el-radio-group>
          </ElFormItem>
          <ElFormItem label="数量">
            <el-radio-group v-model="searchForm.multi">
              <el-radio-button :label="false">单件</el-radio-button>
              <el-radio-button :label="true">多件</el-radio-button>
            </el-radio-group>
          </ElFormItem>
          <ElFormItem>
            <ElPopover placement="bottom" width="600" trigger="click">
              <ElForm
                :model="searchForm"
                size="default"
                inline
                label-width="100px"
              >
                <ElFormItem style="width: 100%; padding-right: 40px">
                  <div style="width: 100%; display: flex; flex-wrap: nowrap">
                    <el-select
                      v-model="searchForm.timeType"
                      clearable
                      :teleported="false"
                      placeholder="时间类型"
                      style="flex: 1; margin-right: 10px"
                    >
                      <el-option :value="1" label="创建时间"></el-option>
                      <el-option :value="2" label="确认时间"></el-option>
                      <el-option :value="3" label="完成时间"></el-option>
                    </el-select>
                    <el-date-picker
                      v-model="timeRange"
                      :teleported="false"
                      :default-time="[
                        new Date(0, 0, 0, 0, 0, 0),
                        new Date(0, 0, 0, 23, 59, 59),
                      ]"
                      placeholder="收货人"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetimerange"
                      style="width: 280px"
                      :shortcuts="pickerOptions.shortcuts"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      clearable
                    >
                    </el-date-picker>
                  </div>
                </ElFormItem>
                <ElFormItem label="订单号">
                  <ElInput
                    v-model="searchForm.factoryOrderNumber"
                    placeholder="订单号"
                    clearable
                    style="width: 150px"
                  />
                </ElFormItem>

                <ElFormItem label="客户">
                  <el-select
                    v-model="searchForm.userMark"
                    clearable
                    filterable
                    :teleported="false"
                    style="width: 150px"
                    placeholder="客户"
                  >
                    <el-option
                      v-for="item in userMarkList"
                      :key="item"
                      :value="item"
                      :label="item"
                    ></el-option>
                  </el-select>
                </ElFormItem>

                <ElFormItem label="生产端">
                  <ElSelect
                    v-model="searchForm.productionClient"
                    placeholder="生产端"
                    clearable
                    :teleported="false"
                    style="width: 150px"
                  >
                    <ElOption
                      v-for="(item, index) in productionClient"
                      :key="index"
                      :value="item.code || ''"
                      :label="`${item.remark}(${item.code})`"
                    ></ElOption>
                  </ElSelect>
                </ElFormItem>
                <ElFormItem label="Variant SKU">
                  <ElInput
                    v-model.trim="searchForm.sku"
                    placeholder="Variant SKU"
                    clearable
                    style="width: 150px"
                  ></ElInput>
                </ElFormItem>
                <!-- <ElFormItem label="Base SKU">
                <ElInput
                  v-model.trim="searchForm.baseSku"
                  placeholder=" Base SKU"
                  clearable
                  style="width: 150px"
                ></ElInput>
              </ElFormItem> -->
                <ElFormItem label="物流跟踪号">
                  <ElInput
                    v-model.trim="searchForm.logisticsTracking"
                    placeholder="物流跟踪号"
                    clearable
                    style="width: 150px"
                  ></ElInput>
                </ElFormItem>
                <ElFormItem label="物流类型">
                  <ElSelect
                    v-model="searchForm.shipmentType"
                    placeholder="物流类型"
                    clearable
                    :teleported="false"
                    style="width: 150px"
                  >
                    <ElOption
                      v-for="(item, index) in ['自有物流', '工厂物流']"
                      :key="index"
                      :value="index"
                      :label="item"
                    ></ElOption>
                  </ElSelect>
                </ElFormItem>
              </ElForm>
              <template #reference>
                <el-button
                  type="warning"
                  @click="searchVisible = !searchVisible"
                >
                  <el-icon v-if="searchVisible">
                    <CaretTop />
                  </el-icon>
                  <el-icon v-else>
                    <CaretBottom />
                  </el-icon>
                </el-button>
              </template>
            </ElPopover>
          </ElFormItem>
          <ElFormItem>
            <span>
              <ElButton link @click="resetSearchForm" style="font-size: 12px"
                ><span title="重置查询条件">重置</span></ElButton
              >
            </span>
          </ElFormItem>
          <ElFormItem>
            <span>
              <ElButton type="primary" @click="search">查询</ElButton>
            </span>
          </ElFormItem>
        </ElForm>
      </el-card>
    </template>
    <template #bottom>
      <el-card style="height: 100%">
        <div class="manage">
          <div class="table-flex">
            <div class="top-table">
              <div class="table-container">
                <TableView
                  ref="tableRef"
                  :columns="tableColumns"
                  :serial-numberable="true"
                  :selectionable="true"
                  :paginated-data="tableData"
                >
                  <template #goods="{ row }">
                    <div class="goods-info-box">
                      <div class="goods-list">
                        <div
                          v-for="item in row.productList"
                          :key="item"
                          class="goods-item"
                        >
                          <div class="goods-item-img">
                            <img :src="item.variantImage" alt="商品图片" />
                          </div>
                          <div class="goods-item-info">
                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label"
                                >商品名称:</span
                              >
                              <span class="goods-item-info-item-value">
                                {{ item.productName }}
                              </span>
                            </div>

                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label"
                                >变体SKU:</span
                              >
                              <span class="goods-item-info-item-value">
                                {{ item.variantSku }}
                              </span>
                              <el-icon
                                class="icon"
                                @click="copy(item.variantSku || '')"
                              >
                                <DocumentCopy />
                              </el-icon>
                            </div>
                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label"
                                >库存SKU:</span
                              >
                              <span class="goods-item-info-item-value">
                                {{ item.thirdSkuCode }}
                              </span>
                              <el-icon
                                class="icon"
                                @click="copy(item.thirdSkuCode || '')"
                              >
                                <DocumentCopy />
                              </el-icon>
                            </div>
                            <div
                              v-if="item.thirdStockSku"
                              class="goods-item-info-item"
                            >
                              <span class="goods-item-info-item-label"
                                >货号:</span
                              >
                              <span class="goods-item-info-item-value">
                                {{ item.thirdStockSku }}
                              </span>
                              <el-icon
                                class="icon"
                                @click="copy(item.thirdStockSku || '')"
                              >
                                <DocumentCopy />
                              </el-icon>
                            </div>
                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label"
                                >工艺:</span
                              >
                              <span class="goods-item-info-item-value">
                                {{ item.craftName }}
                              </span>
                            </div>
                          </div>
                          <div class="goods-item-info">
                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label"
                                >生产单号:</span
                              >
                              <span
                                class="goods-item-info-item-value"
                                :title="item.factorySubOrderNumber"
                              >
                                {{ item.factorySubOrderNumber }}
                              </span>
                              <el-icon
                                class="icon"
                                @click="copy(item.factorySubOrderNumber || '')"
                              >
                                <DocumentCopy />
                              </el-icon>
                            </div>
                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label"
                                >第三方生产单号:</span
                              >
                              <span
                                class="goods-item-info-item-value"
                                :title="item.thirdSubOrderNumber"
                              >
                                {{ item.thirdSubOrderNumber }}
                              </span>
                              <el-icon
                                class="icon"
                                @click="copy(item.thirdSubOrderNumber || '')"
                              >
                                <DocumentCopy />
                              </el-icon>
                            </div>
                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label"
                                >工厂:</span
                              >
                              <span class="goods-item-info-item-value">
                                {{ item.factoryCode }}
                              </span>
                            </div>
                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label"
                                >款号:</span
                              >
                              <span class="goods-item-info-item-value">
                                {{ item.supplierProductNo }}
                              </span>
                            </div>
                            <div
                              v-if="item.isReplenishment"
                              class="goods-item-info-item"
                            >
                              <!-- <span class="goods-item-info-item-label">补胚状态:</span> -->
                              <el-tag size="small" effect="dark" type="danger"
                                >补胚中
                              </el-tag>
                            </div>
                          </div>
                          <div class="goods-item-info">
                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label"
                                >价格:</span
                              >
                              <span class="goods-item-info-item-value">
                                {{ item.productPrice }}($)
                              </span>
                            </div>
                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label"
                                >模板金额:</span
                              >
                              <span class="goods-item-info-item-value">
                                {{ item.templatePrice }}($)
                              </span>
                            </div>
                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label"
                                >工艺金额:</span
                              >
                              <span class="goods-item-info-item-value">
                                {{ item.craftPrice }}($)
                              </span>
                            </div>
                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label"
                                >付款金额:</span
                              >
                              <span class="goods-item-info-item-value">
                                {{ item.payAmount }}($)
                              </span>
                            </div>

                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label">{{
                                '已生产数量:'
                              }}</span>
                              <span class="goods-item-info-item-value">
                                {{ item.passNum }}
                              </span>
                            </div>
                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label"
                                >补胚数量:</span
                              >
                              <span
                                class="goods-item-info-item-value"
                                :title="item.replenishmentSumNum"
                              >
                                {{ item.replenishmentSumNum || 0 }}
                              </span>
                            </div>
                            <div class="goods-item-info-item">
                              <span class="goods-item-info-item-label"
                                >克重:</span
                              >
                              <span
                                v-if="item.weight"
                                class="goods-item-info-item-value"
                              >
                                {{ item.weight }}g
                              </span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                </TableView>
              </div>
              <div class="pagination">
                <el-pagination
                  size="small"
                  v-model:current-page="pagination.currentPage"
                  v-model:page-size="pagination.pageSize"
                  :page-sizes="[50, 100, 150, 200]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="pagination.total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </template>
    <template #other>
      <div class="bottom-table">
        <el-tabs>
          <el-tab-pane label="库存操作明细"> </el-tab-pane>
        </el-tabs>
      </div>
    </template>
  </split-div>
</template>

<style scoped lang="scss">
::v-deep(.search-form) {
  .el-form-item {
    margin-bottom: 10px;
    margin-right: 14px;
  }
}

.el-card {
  ::v-deep(.el-card__body) {
    padding: 10px;
    padding-bottom: 0;
    height: 100%;
  }
}

.manage {
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    margin-bottom: 10px;
  }

  .table-flex {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .right-table {
    flex: 1;
    margin-left: 10px;
    flex-shrink: 0;
  }

  .top-table {
    height: 100%;
    display: flex;
    width: 100%;
    flex-direction: column;

    .pagination {
      display: flex;
      margin: 10px 0;
      justify-content: center;
    }

    .table-container {
      flex: 1;
      flex-shrink: 0;
      overflow: hidden;
    }
  }
}

.bottom-table {
  height: 100%;
  background: white;
  box-sizing: border-box;
  padding: 10px;

  ::v-deep(.el-tabs) {
    height: 100%;
    display: flex;

    .el-tabs__content {
      flex: 1;
      flex-shrink: 0;

      .el-tab-pane {
        height: 100%;

        ul {
          height: 100%;
        }
      }
    }
  }
}
</style>
