<template>
  <div class="page card h-100 flex-gap-10 overflow-hidden flex">
    <div class="left">
      {{ nodeCode }}
      <ElTree
        ref="treeRef"
        default-expand-all
        :expand-on-click-node="false"
        :default-expanded-keys="[]"
        :highlight-current="true"
        node-key="status"
        :data="treeData"
        :props="{ children: 'children', label: 'remark' }"
        @node-click="nodeClick"
      >
        <template #default="{ data }">
          <div class="tree-node">
            <div class="tree-node-label">{{ data.remark }}</div>
            <div v-if="data.count || data.count === 0" class="tree-node-count">
              {{ `(${data.count})` }}
            </div>
          </div>
        </template>
      </ElTree>
    </div>
    <div class="right">
      <div class="delivery-note-page flex-column card h-100 overflow-hidden">
        <el-tabs
          v-if="
            nodeCode != null &&
            ['38', '33', '35', '40'].includes(String(nodeCode))
          "
          v-model="activeSuspendTab"
          class="demo-tabs"
          @tab-click="handTabClick"
        >
          <el-tab-pane
            v-for="label in suspendTabs"
            :key="label.status"
            :label="`${label.remark} (${label.count || 0})`"
            :name="label.status"
          >
          </el-tab-pane>
        </el-tabs>
        <div class="header-filter-form">
          <ElForm ref="queryParamsRef" :model="queryParams" inline>
            <el-form-item label="商品名称">
              <el-input
                v-model="queryParams.name"
                clearable
                maxlength="40"
                style="width: 150px"
                show-word-limit
                placeholder="请输入商品名称"
              />
            </el-form-item>

            <el-form-item label="SKU">
              <el-input
                v-model="queryParams.sku"
                clearable
                style="width: 150px"
                placeholder="请输入sku"
              />
            </el-form-item>

            <el-form-item label="商品类型">
              <el-select
                v-model="queryParams.print_type"
                style="width: 150px"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in PRINT_TYPE_OPTIONS"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品类目">
              <el-cascader
                ref="categoryCascader"
                v-model="queryParams.category_id"
                :options="categoryTree"
                clearable
                style="width: 150px"
                :props="{
                  label: 'name',
                  value: 'id',
                  emitPath: false, // 只返回最后一级 id
                  checkStrictly: true, // ← 关键：允许点击任意一级
                }"
                :show-all-levels="false"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="商品归属" prop="product_type">
              <el-select
                v-model="queryParams.product_type"
                clearable
                style="width: 150px"
              >
                <el-option
                  v-for="item in productTypeList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
            <ElFormItem>
              <ElButton type="primary" @click="searchCard"> 查询 </ElButton>
            </ElFormItem>
            <ElFormItem>
              <ElButton @click="resetSearchForm()"> 重置 </ElButton>
            </ElFormItem>
            <ElFormItem v-if="['-20', '-10'].includes(nodeCode)">
              <ElButton type="success" @click="addProductInfo()">
                新增
              </ElButton>
            </ElFormItem>
            <ElFormItem v-if="['-20'].includes(nodeCode)">
              <ElButton
                type="warning"
                @click="
                  stateReasonBtn('将选中的商品转至挂起状态', '挂起原因', 33)
                "
              >
                挂起
              </ElButton>
            </ElFormItem>
            <ElFormItem
              v-if="
                ['38', '33', '35'].includes(nodeCode) &&
                ['35'].includes(String(activeSuspendTab))
              "
            >
              <ElButton type="success" @click="stateTransitionBtn('取消挂起')">
                取消挂起
              </ElButton>
            </ElFormItem>
            <ElFormItem v-if="['38', '33', '35'].includes(nodeCode)">
              <ElButton
                type="warning"
                @click="
                  stateReasonBtn(
                    '对选中的商品进行取消注册操作',
                    '取消原因',
                    -10,
                  )
                "
              >
                取消注册
              </ElButton>
            </ElFormItem>
            <ElFormItem>
              <ElButton
                v-if="['10,20,30,1'].includes(nodeCode)"
                type="success"
                @click="generateWarehouseReceiptBtn"
              >
                生成入库单
              </ElButton>
            </ElFormItem>
          </ElForm>
        </div>
        <div class="delivery-note-content flex-1 flex-column overflow-hidden">
          <div class="card-wrapper flex-1 flex-column overflow-hidden">
            <div v-if="tableData.length > 0" class="card-list">
              <div
                v-for="cardItem in tableData"
                :key="cardItem.id"
                class="card-list-item"
                @click="cardClick(cardItem)"
              >
                <CommonCard
                  :card-item="cardItem"
                  :active="isSelectStatused(cardItem)"
                  :show-sku="false"
                  :show-product-info="false"
                  :image-field="'img_url'"
                  @contextmenu.prevent="(v: MouseEvent) => rightClick(v)"
                >
                  <template #operations>
                    <img
                      title="操作日志"
                      width="26"
                      height="26"
                      src="@/assets/images/log.png"
                      alt=""
                      @click="operationLog(cardItem.id)"
                    />
                    <img
                      style="margin: 0 5px"
                      title="查看详情"
                      width="28"
                      height="28"
                      src="@/assets/images/preview.png"
                      alt=""
                      @click="obtainProductInfoBtn(cardItem.id, 'preview')"
                    />
                    <img
                      v-if="['-20', '-10'].includes(nodeCode)"
                      title="编辑"
                      width="26"
                      height="26"
                      src="@/assets/images/edit.png"
                      alt=""
                      @click="obtainProductInfoBtn(cardItem.id, 'edit')"
                    />
                    <img
                      v-if="['-20'].includes(nodeCode)"
                      style="margin: 0 5px"
                      title="供应链确认"
                      width="26"
                      height="26"
                      src="@/assets/images/confirm.png"
                      alt=""
                      @click="obtainProductInfoBtn(cardItem.id, 'confirm')"
                    />
                  </template>
                  <template #images>
                    <div class="flex-between">
                      <div
                        v-if="cardItem.colorImageList"
                        class="images-position"
                      >
                        <div
                          v-for="(item, index) in cardItem.colorImageList"
                          :key="index"
                          :title="item"
                          class="item-image"
                        >
                          <img
                            :src="item"
                            height="28"
                            @click="handlePictureCardPreview(item)"
                          />
                        </div>
                      </div>
                    </div>
                  </template>
                  <template #info>
                    <div class="grid-container">
                      <div class="grid-item">
                        {{ cardItem.create_time }}
                      </div>
                    </div>
                    <div class="grid-container">
                      <div class="grid-item">
                        {{ cardItem.sku }}
                      </div>
                      <div class="grid-item tag-position">
                        <el-tag :type="printTag(cardItem.print_type).type">
                          {{ printTag(cardItem.print_type).label }}
                        </el-tag>
                      </div>
                    </div>
                  </template>
                </CommonCard>
              </div>
            </div>
            <div v-else class="empty">暂无数据</div>
          </div>
          <div class="pagination">
            <div class="total">
              <span
                >已选择
                <span style="color: red">{{ cardSelection.length }}</span>
                条数据</span
              >
            </div>
            <ElPagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[50, 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>
      </div>
    </div>
    <createProduct
      ref="shopRef"
      v-model:visible="createVisible"
      :category-tree="categoryTree"
      :product-type-list="productTypeList"
      :currency-list="currencyList"
      :craft-list="craftList"
      @success="loadTreeData"
      @close="createVisible = false"
    />
  </div>
  <receiptOrder
    ref="receiptRef"
    v-model:visible="receiptVisible"
    :warehouse-list="warehouseList"
    @success="loadTreeData"
    @close="receiptVisible = false"
  />
  <RightClickMenu
    ref="rightMenuRef"
    :show-copy-count="false"
    :show-copy-shop-number="false"
    :show-copy-sub-shop-number="false"
    @on-change="rightChange"
  >
    <template #default>
      <div class="menu-item" @click="rightChange('sku')">复制SKU</div>
    </template>
  </RightClickMenu>
  <el-dialog v-model="dialogVisible" width="35%">
    <img :src="dialogImageUrl" alt="商品预览图片" />
  </el-dialog>
  <el-dialog
    v-model="logVisible"
    title="操作日志"
    width="1000px"
    :close-on-click-modal="false"
  >
    <LogList :log-list="logList" />
  </el-dialog>
</template>
<script setup lang="ts">
import {
  getStatusCountApi,
  getCardListPageApi,
  getLogListApi,
  getByIdApi,
  updateStatusApi,
} from '@/api/product'
import {
  IntercategoryTree,
  InterSearchCriteria,
  InterCategoryNode,
  InterCardItem,
  InterCraftItem,
  CurrencyType,
  ProcessTypeData,
  InterProductType,
  ProductSku,
} from '@/types/api/product'
import {
  clearNonEmptyChildren,
  findNodeById,
  processType,
} from '@/utils/product'
import { ElTree } from 'element-plus'
import type { TabsPaneContext } from 'element-plus'
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData = ref<IntercategoryTree[]>()
const rawTreeData = ref<IntercategoryTree[]>([])
const nodeCode = ref<string>(
  sessionStorage.getItem('Product_NodeCode') || '-20',
)
import { useValue } from '@/utils/hooks/useValue'
import usePageList from '@/utils/hooks/usePageList'
const [queryParams, resetSearchForm] = useValue<InterSearchCriteria>({
  name: '',
  sku: '',
  print_type: null,
  category_id: null,
  product_type: '',
  diyUserId: null,
})
const {
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: searchCard,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) => {
    return getCardListPageApi(
      { ...queryParams.value, status: nodeCode.value },
      page,
      pageSize,
    ).then((res) => {
      return res.data
    })
  },
})
const loadTreeData = async () => {
  try {
    const res = await getStatusCountApi()
    rawTreeData.value = res.data
    // 生成渲染数据：将所有有值的 children 清空
    treeData.value = clearNonEmptyChildren(res.data)
    await nextTick(() => {
      treeRef.value!.setCurrentKey(nodeCode.value, true)
      searchCard()
    })
  } catch (e) {
    console.error(e)
  }
}
import { LogListData } from '@/types/api/podCnOrder'
const logList = ref<LogListData[]>([])
const logVisible = ref(false)
const operationLog = async (id: number) => {
  try {
    const res = await getLogListApi(id)
    if (res.code !== 200) return
    logList.value = res.data
    logVisible.value = true
  } catch (e) {
    console.error(e)
  }
}
const cardSelection = ref<InterCardItem[]>([])
const cardClick = (data: InterCardItem) => {
  const status = isSelectStatused(data)
  if (status) {
    cardSelection.value = cardSelection.value.filter(
      (item: InterCardItem) => item.id !== data.id,
    )
  } else {
    cardSelection.value.push(data as InterCardItem)
  }
}
const isSelectStatused = (data: InterCardItem) => {
  const index = cardSelection.value.findIndex(
    (item: InterCardItem) => item.id === data.id,
  )
  return index !== -1
}
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const handlePictureCardPreview = (fileUrl: string) => {
  dialogImageUrl.value = fileUrl
  dialogVisible.value = true
}
import RightClickMenu from '@/components/RightClickMenu.vue'

const rightMenuRef = ref()
const rightClick = (e: MouseEvent) => {
  rightMenuRef.value.setPosition({
    x: e.clientX,
    y: e.clientY,
  })
}
const rightChange = async (code: string) => {
  if (code === 'select-all') {
    cardSelection.value = JSON.parse(JSON.stringify(tableData.value))
  } else if (code === 'cancel-select') {
    cardSelection.value = []
  } else if (code === 'sku') {
    const str = (tableData.value as InterCardItem[])
      .map((item) => item?.sku)
      .filter(Boolean)
      .join(',')
    if (!str) return ElMessage.warning('当前数据没有SKU')
    navigator.clipboard.writeText(str)
    ElMessage.success('复制成功')
  }
}
import { useOptions } from '@/utils/product'
const { getOptions } = useOptions()
const categoryTree = ref<InterCategoryNode[]>([])
const productTypeList = ref<InterProductType[]>([
  { name: '平台共享', code: 'platform' },
  { name: '客户私有', code: 'customer' },
])
const PRINT_TYPE_OPTIONS = [
  { label: '局部印', value: 1, type: 'warning' },
  { label: '代发普货', value: 2, type: 'danger' },
] as const
const printTag = computed(() => (val: number | string) => {
  const numVal = typeof val === 'string' ? parseInt(val, 10) : val
  const result = PRINT_TYPE_OPTIONS.find((item) => item.value === numVal)
  return result || { label: '未知', type: 'danger' }
})
import { IAllList } from '@/types/api/podUsOrder'
const craftList = ref<IAllList[]>([])
const processTypeMap = processType.value.reduce(
  (acc: Record<string, string>, cur: ProcessTypeData) => {
    acc[cur.value] = cur.label
    return acc
  },
  {},
)
const currencyList = ref<CurrencyType[]>([])
onMounted(async () => {
  loadTreeData()
  const result = await getOptions(['category', 'craft', 'currency'])
  categoryTree.value = result.category as unknown as InterCategoryNode[]
  const data: InterCraftItem[] = result.craft as unknown as InterCraftItem[]
  craftList.value = data.map((item) => ({
    id: item.id,
    name: item.craft_name,
    warehouseName: processTypeMap[item.craft_type] ?? '其他',
  })) as IAllList[]
  currencyList.value = result.currency as unknown as CurrencyType[]
})
const suspendTabs = ref<IntercategoryTree[]>([])
const activeSuspendTab = ref<string>('33')
const nodeClick = async (data: IntercategoryTree) => {
  sessionStorage.setItem('Product_NodeCode', String(data.status))
  // 如果状态为38(挂起)，从原始树数据中查找该节点并获取其 children去渲染右侧的tabs
  if (data.status === 38) {
    const targetNode = findNodeById(rawTreeData.value, 38)
    if (targetNode && targetNode.children) {
      suspendTabs.value = targetNode.children
      activeSuspendTab.value = String(suspendTabs.value[0]?.status) || '33' // 默认选中第一个子节点
    } else {
      console.warn('未找到 id 为 38 的节点或其没有子节点')
    }
  }
  cardSelection.value = []
  const statusValue =
    data.status != 38 ? data.status : activeSuspendTab.value ?? 0
  nodeCode.value = String(statusValue)
  currentPage.value = 1
  searchCard()
}
const handTabClick = (tab: TabsPaneContext) => {
  nodeCode.value = String(tab.paneName)
  currentPage.value = 1
  searchCard()
}
import createProduct from './components/createProduct.vue'
const shopRef = shallowRef<InstanceType<typeof createProduct>>()
const createVisible = ref(false)
const addProductInfo = () => {
  createVisible.value = true
  shopRef.value?.open('add')
}
const obtainProductInfoBtn = async (
  id: number,
  type: 'add' | 'edit' | 'preview' | 'confirm' | 'success',
) => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    const res = await getByIdApi(id as number)
    if (res.code === 200) {
      createVisible.value = true
      shopRef.value?.open(type, res.data)
    }
  } catch (error) {
    ElMessage.error('加载数据失败，请重试')
  } finally {
    loading.close()
  }
}
const stateTransitionBtn = async (name: string, toStatus?: number) => {
  if (cardSelection.value.length == 0) {
    return ElMessage.warning('请选择商品')
  }
  try {
    await ElMessageBox.confirm(`确定对选中的商品进行${name}操作？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch (e) {
    return
  }
  const res = await updateStatusApi({
    ids: cardSelection.value.toString(),
    status: toStatus,
    remark: null,
  })
  if (res.code === 200) {
    loadTreeData()
    cardSelection.value = []
    ElMessage.success('提交成功')
  } else {
    ElMessage.error(res.message)
  }
}
const stateReasonBtn = async (
  name: string,
  reason: string,
  toStatus: number,
) => {
  if (cardSelection.value.length == 0) {
    return ElMessage.warning('请选择商品')
  }
  ElMessageBox.prompt(`确定${name}?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: `请输入${reason}`,
    inputPattern: /.+/,
    inputErrorMessage: `${reason}不能为空`,
  }).then(async ({ value }: { value: string }) => {
    const res = await updateStatusApi({
      ids: cardSelection.value.toString(),
      status: toStatus,
      remark: value,
    })
    if (res.code === 200) {
      loadTreeData()
      cardSelection.value = []
      ElMessage.success('提交成功')
    } else {
      ElMessage.error(res.message)
    }
  })
}
import { warehouseInfo } from '@/api/warehouse'
import receiptOrder from './components/receiptOrder.vue'
const receiptRef = shallowRef<InstanceType<typeof receiptOrder>>()
const receiptVisible = ref(false)
const warehouseList = ref<warehouseInfo[]>([])
const generateWarehouseReceiptBtn = async () => {
  try {
    const warehouseResult = await getOptions(['warehouse'])
    warehouseList.value =
      warehouseResult.warehouse as unknown as warehouseInfo[]
    const loading = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })

    try {
      const id = cardSelection.value[0].id
      const res = await getByIdApi(id)
      if (res.code === 200) {
        const productList =
          (res.data as unknown as { productList: ProductSku[] })?.productList ||
          []
        receiptVisible.value = true
        receiptRef.value?.open?.(productList)
      }
    } catch (err) {
      console.error(err)
      ElMessage.error('加载数据失败，请重试')
    } finally {
      loading.close()
    }
  } catch (err) {
    console.error(err)
    ElMessage.error('获取仓库列表失败，请重试')
  }
}
</script>
<style lang="scss" scoped>
@use './product.scss';
</style>
