<template>
  <div class="page card h-100 flex-gap-10 overflow-hidden flex">
    <div class="left">
      <ElTree
        ref="treeRef"
        default-expand-all
        :expand-on-click-node="false"
        :default-expanded-keys="[]"
        :highlight-current="true"
        node-key="code"
        :data="treeData"
        :props="{ children: 'children', label: 'name' }"
        @node-click="nodeClick"
      >
        <template #default="{ data }">
          <div class="tree-node">
            <div class="tree-node-label">{{ data.name }}</div>
            <div
              v-if="data.countQuantity || data.countQuantity === 0"
              class="tree-node-count"
            >
              {{ `(${data.countQuantity})` }}
            </div>
          </div>
        </template>
      </ElTree>
    </div>
    <div class="right">
      <div class="delivery-note-page flex-column card h-100 overflow-hidden">
        <splitDiv size="50">
          <template #top>
            <div class="header-filter-form">
              <ElForm ref="searchFormRef" :model="searchForm" inline>
                <ElFormItem label="采购仓库">
                  <ElSelect
                    v-model="searchForm.warehouseId"
                    clearable
                    placeholder="请选择仓库"
                    style="width: 160px"
                  >
                    <ElOption
                      v-for="item in warehouseList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></ElOption>
                  </ElSelect>
                </ElFormItem>
                <ElFormItem label="入库时间">
                  <el-date-picker
                    v-model="tradingTime"
                    :shortcuts="pickerOptions.shortcuts"
                    :default-time="[
                      new Date(0, 0, 0, 0, 0, 0),
                      new Date(0, 0, 0, 23, 59, 59),
                    ]"
                    type="datetimerange"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    clearable
                    style="width: 260px"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </ElFormItem>
                <ElFormItem label="入库单号">
                  <ElInput
                    v-model.trim="searchForm.inNo"
                    clearable
                    placeholder="请输入入库单号"
                    style="width: 160px"
                  />
                </ElFormItem>
                <ElFormItem style="margin-right: 10px" label="库存SKU">
                  <ElInput
                    v-model="searchForm.warehouseSku"
                    clearable
                    placeholder="请输入库存SKU"
                    style="width: 160px"
                  />
                </ElFormItem>
                <ElFormItem style="margin-right: 10px" label="入库单ID">
                  <ElInput
                    v-model.trim="searchForm.id"
                    clearable
                    placeholder="请输入入库单ID"
                    style="width: 160px"
                  />
                </ElFormItem>
                <ElFormItem>
                  <ElButton ref="searchBtnRef" type="primary" @click="search"
                    >查询</ElButton
                  >
                </ElFormItem>
                <ElFormItem>
                  <ElButton @click="resetSearchForm">重置</ElButton>
                </ElFormItem>
                <ElFormItem v-if="nodeCode === 'PENDING_SUBMIT'">
                  <el-button type="primary" @click="addDialog(1, null)">
                    新增
                  </el-button>
                </ElFormItem>
                <ElFormItem v-if="nodeCode === 'PENDING_AUDIT'">
                  <el-button type="danger" @click="rejectedInRecord">
                    驳回
                  </el-button>
                </ElFormItem>
                <ElFormItem v-if="nodeCode === 'PENDING_SUBMIT'">
                  <el-button type="danger" @click="handleBatchDelete">
                    删除
                  </el-button>
                </ElFormItem>
                <ElFormItem>
                  <el-button type="success" @click="handleExport">
                    导出</el-button
                  >
                </ElFormItem>
                <ElFormItem v-if="nodeCode === 'PENDING_AUDIT'">
                  <el-button type="warning" @click="auditOrder('audit')">
                    审核
                  </el-button>
                </ElFormItem>
                <ElFormItem v-if="nodeCode === 'PENDING_SUBMIT'">
                  <el-button type="success" @click="auditOrder('submitAudit')">
                    提交审核
                  </el-button>
                </ElFormItem>
                <ElFormItem v-if="nodeCode === 'PENDING_SUBMIT'">
                  <el-button type="danger" @click="auditOrder('invalid')">
                    作废
                  </el-button>
                </ElFormItem>
                <ElFormItem>
                  <el-button type="primary" @click="printProductTag">
                    打印库存SKU标签
                  </el-button>
                </ElFormItem>
                <ElFormItem>
                  <el-button
                    v-if="nodeCode === 'COMPLETED'"
                    type="success"
                    @click="auditOrder('archiving')"
                  >
                    归档
                  </el-button>
                </ElFormItem>
              </ElForm>
            </div>
            <div
              class="delivery-note-content flex-1 flex-column overflow-hidden"
            >
              <div class="delivery-note-list flex-1 overflow-hidden">
                <ElTable
                  ref="singleTableRef"
                  highlight-current-row
                  :data="tableData"
                  default-expand-all
                  size="small"
                  style="width: 100%; height: 100%"
                  border
                  @current-change="rowClick"
                  @selection-change="handleSelectionChange"
                >
                  <ElTableColumn
                    type="selection"
                    width="70"
                    header-align="center"
                    align="center"
                  ></ElTableColumn>
                  <ElTableColumn
                    type="index"
                    label="序号"
                    width="60"
                    fixed="left"
                    header-align="center"
                    align="center"
                  ></ElTableColumn>
                  <ElTableColumn
                    label="入库单号"
                    show-overflow-tooltip
                    prop="inNo"
                    width="130"
                    header-align="center"
                    align="center"
                  ></ElTableColumn>
                  <ElTableColumn
                    label="来源单号"
                    show-overflow-tooltip
                    prop="sourceOn"
                    width="130"
                    header-align="center"
                    align="center"
                  ></ElTableColumn>
                  <ElTableColumn
                    label="单据状态"
                    width="130"
                    prop="billStatusTxt"
                    header-align="center"
                    align="center"
                  ></ElTableColumn>
                  <ElTableColumn
                    label="仓库名称"
                    show-overflow-tooltip
                    prop="warehouseName"
                    width="130"
                    header-align="center"
                    align="center"
                  ></ElTableColumn>
                  <ElTableColumn
                    label="工厂编号"
                    show-overflow-tooltip
                    prop="factoryCode"
                    width="90"
                    header-align="center"
                    align="center"
                  ></ElTableColumn>
                  <ElTableColumn
                    label="物流单号"
                    show-overflow-tooltip
                    prop="shipmentNumber"
                    width="200"
                    header-align="center"
                    align="center"
                  ></ElTableColumn>
                  <ElTableColumn
                    label="币种"
                    show-overflow-tooltip
                    width="80"
                    prop="currencyName"
                    header-align="center"
                    align="center"
                  ></ElTableColumn>
                  <ElTableColumn
                    label="总金额"
                    show-overflow-tooltip
                    width="120"
                    prop="totalPrice"
                    header-align="center"
                    align="center"
                  ></ElTableColumn>
                  <ElTableColumn
                    label="SKU数量"
                    header-align="center"
                    prop="skuAmount"
                    width="90"
                    align="center"
                    show-overflow-tooltip
                  >
                  </ElTableColumn>
                  <ElTableColumn
                    label="总数量"
                    header-align="center"
                    prop="total"
                    width="90"
                    align="center"
                    show-overflow-tooltip
                  >
                  </ElTableColumn>
                  <ElTableColumn
                    label="驳回原因"
                    show-overflow-tooltip
                    prop="rejectReason"
                    header-align="center"
                    align="center"
                  ></ElTableColumn>
                  <ElTableColumn
                    label="备注"
                    show-overflow-tooltip
                    prop="remark"
                    header-align="center"
                    align="center"
                  ></ElTableColumn>
                  <ElTableColumn
                    v-if="nodeCode === 'PENDING_SUBMIT'"
                    width="100"
                    align="center"
                    header-align="center"
                    label="操作"
                  >
                    <template #default="{ row }">
                      <ElButton
                        :disabled="row.source === 'StockingUpWarehouseApply'"
                        :title="
                          row.source === 'StockingUpWarehouseApply'
                            ? '来源为入库申请单，不允许编辑！请先操作取消，再重新提交入库单'
                            : ''
                        "
                        type="primary"
                        link
                        @click="addDialog(2, row)"
                        >编辑
                      </ElButton>
                    </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>
          </template>
          <template #bottom>
            <el-tabs
              v-loading="showDetailLoading"
              v-model="tabsValue"
              @tab-click="tabsClick"
            >
              <el-tab-pane name="0" label="入库商品">
                <div class="table-wrap">
                  <ElTable size="small" :data="detailList" height="100%" border>
                    <ElTableColumn
                      show-overflow-tooltip
                      width="60"
                      align="center"
                      label="序号"
                      type="index"
                    />
                    <ElTableColumn
                      show-overflow-tooltip
                      align="center"
                      width="100"
                      label="SKU图片"
                      prop="factory_order_number"
                    >
                      <template #default="{ row }">
                        <ImageView
                          :src="row.skuImage"
                          width="40px"
                          height="40px"
                        />
                      </template>
                    </ElTableColumn>
                    <ElTableColumn
                      show-overflow-tooltip
                      align="center"
                      label="库存SKU"
                      width="180"
                      prop="warehouseSku"
                    >
                    </ElTableColumn>

                    <ElTableColumn
                      show-overflow-tooltip
                      align="center"
                      label="商品名称"
                      prop="skuName"
                    />
                    <ElTableColumn
                      show-overflow-tooltip
                      align="center"
                      label="款号"
                      prop="productNo"
                    />
                    <ElTableColumn
                      show-overflow-tooltip
                      align="center"
                      width="90"
                      label="入库数量"
                      prop="buyStored"
                    />
                    <ElTableColumn
                      show-overflow-tooltip
                      align="center"
                      label="库位"
                      prop="locationCode"
                    />
                    <ElTableColumn
                      show-overflow-tooltip
                      align="center"
                      label="币种"
                      width="80"
                      prop="currencyName"
                    />
                    <ElTableColumn
                      show-overflow-tooltip
                      align="center"
                      label="成本价"
                      prop="costPrice"
                    />
                    <ElTableColumn
                      show-overflow-tooltip
                      align="center"
                      label="总成本"
                      prop="totalPrice"
                    />
                    <ElTableColumn
                      show-overflow-tooltip
                      align="center"
                      label="所属客户"
                      prop="userMark"
                    />
                    <ElTableColumn
                      show-overflow-tooltip
                      align="center"
                      width="240"
                      label="备注"
                      prop="remark"
                    />
                    <ElTableColumn
                      show-overflow-tooltip
                      align="center"
                      label="创建时间"
                      width="130"
                      prop="createTime"
                    />
                    <ElTableColumn
                      show-overflow-tooltip
                      align="center"
                      label="更新时间"
                      width="130"
                      prop="updateTime"
                    />
                  </ElTable>
                </div>
                <!-- <ElPagination
                  v-model:current-page="detailPager.page"
                  v-model:page-size="detailPager.rows"
                  :page-sizes="[100, 200, 300, 400, 500]"
                  background
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="detailPager.total"
                  style="margin: 10px auto 0; text-align: right"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                ></ElPagination> -->
              </el-tab-pane>
              <el-tab-pane name="1" label="操作日志">
                <ul
                  style="
                    color: #333;
                    font-size: 12px;
                    height: 100%;
                    overflow: auto;
                  "
                >
                  <li
                    v-for="(item, index) in logList"
                    :key="index"
                    style="display: flex"
                  >
                    <span style="display: inline-block">
                      {{ item.createdTime }}&emsp;&emsp;
                    </span>
                    <span style="display: inline-block">{{
                      item.description
                    }}</span>
                  </li>
                </ul>
              </el-tab-pane>
            </el-tabs>
          </template>
        </splitDiv>
      </div>
    </div>
  </div>
  <ElDialog
    v-model="importDialogVisible"
    title="导入入库单"
    width="500px"
    :close-on-click-modal="false"
  >
    <div class="import-dialog">
      <div class="label" style="margin-bottom: 10px">
        <span style="margin-right: 10px">所属客户：</span>
        <el-select v-model="importUserMark" size="small" style="width: 100px">
          <el-option
            v-for="user in userMarkList"
            :key="user.userId"
            :label="user.userMark"
            :value="user.userId"
          ></el-option>
        </el-select>
      </div>
      <div class="import-content">
        <UploadExcel
          v-model="importedFileUrl"
          :import-type="'localAndXlsx'"
          :import-name="'入库单'"
          :import-url="'/files/warehousingEntry.xlsx'"
          @imported="handleLocalImport"
        />
      </div>
    </div>
  </ElDialog>
  <ReceiptProductDialog
    ref="receiptProductDialogRef"
    v-model:visible="newDialogVisible"
    v-model:user-mark="userMark"
    v-model:select-sku="selectSku"
    :title="formId ? '编辑' : '新增'"
    :disable-warehouse="!!formId"
    :edit-form="editForm"
    :rules="rules"
    :warehouse-list="warehouseList"
    :other-purchase-data="otherPurchaseData"
    :location-list="locationList"
    :user-mark-list="userMarkList"
    :sku-data="skuData"
    :filter-sku-data="filterSkuData"
    :show-user-mark-filter="true"
    :show-batch-add-button="true"
    :show-import-button="true"
    @warehouse-change="handleWarehouseChange"
    @selection-change="productSelectionChange"
    @set-cost-price="setCostPrice"
    @location-change="handleLocationChange"
    @query-sku="selectbySku"
    @sku-add="skudblclick"
    @batch-add="addPurchase"
    @delete="deleteOtherWarehousing"
    @import="importData"
    @update:remark="updateEditRemark"
    @update:warehouse-id="updateEditWarehouseId"
    @save="addOtherCurrency"
  />
  <ElDialog
    v-model="exportVisible"
    title="导出选项"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form :model="exportForm" label-width="80px">
      <el-form-item label="" prop="resource">
        <el-radio-group v-model="exportForm.resource" @change="isAllExport">
          <el-radio :label="0">导出本页</el-radio>
          <el-radio :label="1">导出选中</el-radio>
          <el-radio :label="2">全部</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="">
        <el-checkbox v-model="exportForm.delivery"> 包含详情</el-checkbox>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exportVisible = false">取消</el-button>
        <el-button type="primary" @click="submitExportForm">确认</el-button>
      </span>
    </template>
  </ElDialog>
  <el-dialog v-model="showPrintDialog" title="打印参数设置">
    <el-table height="400px" :data="printData" border>
      <el-table-column
        width="60"
        align="center"
        type="index"
        label="序号"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="skuName"
        label="商品名称"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="warehouseSku"
        label="库存SKU"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="locationName"
        label="库位编码"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="supplierItemNo"
        label="款号"
      ></el-table-column>
      <el-table-column align="center" prop="number" label="打印数量">
        <template #default="{ row }">
          <el-input
            v-model.number="row.number"
            oninput="value=value.replace(/[^\-?\d.]/g,'')"
            placeholder="打印数量"
            clearable
          ></el-input>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="showPrintDialog = false">取消</el-button>
      <el-button type="primary" @click="handlePrintProductTag">打印</el-button>
    </template>
  </el-dialog>
  <ElDialog
    v-model="addPurchaseVisible"
    title="批量添加"
    width="500px"
    :close-on-click-modal="false"
  >
    <div class="label" style="margin-bottom: 10px">
      <span style="margin-right: 10px">所属客户：</span>
      <el-select v-model="batchUserMark" size="small" style="width: 100px">
        <el-option
          v-for="user in userMarkList"
          :key="user.userId"
          :label="user.userMark"
          :value="user.userId"
        ></el-option>
      </el-select>
    </div>
    <div>
      <el-input
        v-model.trim="purchaseTextarea"
        type="textarea"
        placeholder="请输入库存 SKU"
        :rows="5"
        minlength="1"
        maxlength="1000"
        show-word-limit
      />
      <div style="margin-top: 12px; color: #777">多个字段使用","隔开</div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addPurchaseVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPurchase">确认</el-button>
      </span>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ElMessage, ElRadioGroup, ElTree } from 'element-plus'
import splitDiv from '@/components/splitDiv/splitDiv.vue'
import { ElTable } from 'element-plus'
import ReceiptProductDialog from './components/ReceiptProductDialog.vue'
import usePageList from '@/utils/hooks/usePageList'
import { checkUpdateParams, AnyObject } from '@/utils/hooks/commonUtil'
import { useValue } from '@/utils/hooks/useValue'
import { useReceiptProductDialog } from './hooks/useReceiptProductDialog'
import {
  getInRecordStatusTree,
  warehouseInRecordListPageApi,
  getWarehouseInRecordDetailApi,
  warehouseInfoGetAll,
  getByWareHouseIdAndCodeApi,
  addInRecordApi,
  updateInRecordApi,
  deleteWarehouseInRecordApi,
  auditOrderApi,
  getInRecordLogApi,
  rejectInRecordApi,
  LogListData,
  warehouseInfo,
  InRecordBatchCheckPrintApi,
  factoryWarehouseInventoryPrint,
  warehouseInRecordExport, getLocalFactoryList,
} from '@/api/warehouse'
import { filePath } from '@/api/axios.ts'
import BigNumber from 'bignumber.js'
import { ref, onMounted, watch, nextTick, computed } from 'vue'
import 'element-plus/dist/index.css'
import {
  warehouseSearchForm,
  InterWarehousePage,
  InterWarehouseTree,
  InterProductList,
  ILocation,
  InterWarehouseDetail,
} from '@/types/api/warehouse'
import ImageView from '@/components/ImageView.vue'
import UploadExcel from '@/components/UploadExcel.vue'
import { useEnterKeyTrigger } from '@/utils/hooks/useEnterKeyTrigger.ts'
interface UserMark {
  userId: number
  userMark: string
  userName: string
}
const warehouseList = ref<warehouseInfo[]>([])
const userMarkList = ref<UserMark[]>([])
const pickerOptions = {
  shortcuts: [
    {
      text: '今日',
      value: () => {
        const start = new Date(new Date(getStartTime()).getTime())
        const end = new Date()
        return [start, end]
      },
    },
    {
      text: '昨天',
      value: () => {
        const start = new Date()
        const end = new Date(new Date(getStartTime()).getTime() - 1)
        start.setTime(end.getTime() - 3600 * 1000 * 24 * 1 + 1)
        return [start, end]
      },
    },
    {
      text: '最近7天',
      value: () => {
        const end = new Date()
        const start = new Date(getStartTime())
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
        return [start, end]
      },
    },
    {
      text: '最近14天',
      value: () => {
        const end = new Date()
        const start = new Date(getStartTime())
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 13)
        return [start, end]
      },
    },
    {
      text: '最近30天',
      value: () => {
        const end = new Date()
        const start = new Date(getStartTime())
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
        return [start, end]
      },
    },
    {
      text: '本星期',
      value: () => {
        const end = new Date()
        const start = new Date()
        const nowDay = new Date().getDay() - 1
        start.setTime(
          new Date(getStartTime()).getTime() - 3600 * 1000 * 24 * nowDay,
        )
        return [start, end]
      },
    },
    {
      text: '上星期',
      value: () => {
        const end = new Date()
        const start = new Date()
        const nowDay = new Date().getDay() - 1
        end.setTime(
          new Date(getStartTime()).getTime() - 3600 * 1000 * 24 * nowDay - 1,
        )
        start.setTime(end.getTime() - 3600 * 1000 * 24 * 7 + 1)
        return [start, end]
      },
    },
    {
      text: '这个月',
      value: () => {
        const end = new Date()
        const start = new Date()
        const nowDate = new Date().getDate() - 1
        start.setTime(
          new Date(getStartTime()).getTime() - 3600 * 1000 * 24 * nowDate,
        )
        return [start, end]
      },
    },
    {
      text: '上个月',
      value: () => {
        const date = new Date()
        let year = date.getFullYear()
        let month = date.getMonth()
        const end = new Date(
          new Date(`${year}-${month + 1}-1 00:00:00`).getTime() - 1,
        )
        if (month === 0) {
          month = 12
          year = year - 1
        }
        const start = new Date(
          new Date(`${year}-${month}-1 00:00:00`).getTime(),
        )
        return [start, end]
      },
    },
    {
      text: '历史',
      value: () => {
        return ['', '']
      },
    },
  ],
}

function getStartTime() {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${year}-${month}-${day} 00:00:00`
}
const selectSku = ref('')
const userMark = ref(0)
const batchUserMark = ref(0)
const importUserMark = ref(0)
const treeData = ref<InterWarehouseTree[]>()
const [searchForm, resetSearchForm] = useValue<warehouseSearchForm>({})

const tradingTime = ref<string[]>([])
const selections = ref<InterWarehousePage[]>([])
const detailList = ref<InterProductList[]>([])
const tabsValue = ref<string>('0')
const singleTableRef = ref<InstanceType<typeof ElTable>>()
const currentRow = ref<InterWarehousePage | null>(null)
const logList = ref<LogListData[]>([])
const detailLoading = ref(false)
const showDetailLoading = computed(() => {
  return detailLoading.value && !newDialogVisible.value
})
const rules = {
  warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
}
const isAllExport = () => {
  if (exportForm.value.resource == '2') {
    ElMessage.warning('最多支持5000条!')
  }
}
const nodeCode = ref<string>(
  sessionStorage.getItem('InRecord_NodeCode') || 'all',
)

const treeRef = ref<InstanceType<typeof ElTree>>()
const {
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) =>
    warehouseInRecordListPageApi(
      {
        ...searchForm.value,
        billStatus: nodeCode.value == 'all' ? 'all' : nodeCode.value,
        createTimeStart: tradingTime.value && tradingTime.value[0],
        createTimeEnd: tradingTime.value && tradingTime.value[1],
      },
      page,
      pageSize,
    ).then((res) => res.data),
})

const getTreeNum = async () => {
  try {
    const res = await getInRecordStatusTree()
    res.data = [{ code: 'all', name: '全部', children: res.data }]
    treeData.value = res.data
    await nextTick(() => {
      treeRef.value!.setCurrentKey(nodeCode.value, true)
    })
  } catch (e) {
    console.error(e)
  }
}
const showPrintDialog = ref(false)
const printData = ref([])
const printProductTag = async () => {
  if (!selections.value.length) {
    return ElMessage.warning('请选择要操作的数据')
  }
  const str = selections.value.map((el: InterWarehousePage) => el.id).join(',')
  try {
    const res = await InRecordBatchCheckPrintApi(str)
    if (res.code === 200) {
      printData.value = res.data
      showPrintDialog.value = true
    } else {
      ElMessage.error(res.message)
    }
  } catch (e) {
    console.error(e)
  }
}

async function handlePrintProductTag() {
  const flag = printData.value.every(
    (el: InterWarehousePage) => el.number && el.number != '0',
  )
  if (!flag) {
    return ElMessage.warning('打印数量需大于0')
  }
  const list = printData.value.map(
    ({
      skuName = '',
      warehouseSku = '',
      supplierItemNo = '',
      number = '',
      locationName = '',
    }) => ({
      skuName,
      warehouseSku,
      supplierItemNo,
      number,
      locationName,
    }),
  )
  const res = await factoryWarehouseInventoryPrint({
    list,
    code: 'PT002',
  })
  showPrintDialog.value = false
  window.open(filePath + res.message, '_blank')
}


interface InterImportData {
  warehouseSku: string
  remark?: string | null

  [key: string]: unknown
}

// 前端导入Excel
const excelFieldMap: Record<string, keyof InterProductList> = {
  // SKU图片: 'skuImage',
  库存SKU: 'warehouseSku',
  // SKU名称: 'skuName',
  入库数量: 'buyStored',
  // '成本价(￥)': 'costPrice',
  // '总成本(￥)': 'totalPrice',
  库位编码: 'locationCode',
  备注: 'remark',
}

const handleLocalImport = async ({
  path,
  data,
}: {
  path: string
  data: InterImportData[]
}) => {
  // 1. 将原始导入数据映射到 InterImportData[]
  const importedData: InterImportData[] = data
    .map((item) => {
      const obj: InterImportData = { warehouseSku: '' }
      Object.keys(excelFieldMap).forEach((excelKey) => {
        const field = excelFieldMap[excelKey]
        const value = item[excelKey]

        if (field === 'warehouseSku') {
          obj[field] = typeof value === 'string' ? value : String(value ?? '')
        } else if (field === 'remark') {
          obj[field] =
            typeof value === 'string'
              ? value
              : value === null || value === undefined
              ? null
              : String(value)
        } else if (field === 'buyStored') {
          // 确保 value 是一个有效的数字或数字字符串，否则设置为 null
          if (
            typeof value === 'number' ||
            (typeof value === 'string' && !isNaN(Number(value)))
          ) {
            obj[field] = String(value) // 转换为字符串
          } else {
            obj[field] = null // 无效值设置为 null
          }
        } else {
          obj[field] = value
        }
      })
      return obj
    })
    .filter((item) => item.warehouseSku)
  // console.log('@', importedData, data)
  if (importedData.length === 0) {
    ElMessage.warning('导入数据中没有有效的商品SKU')
    importDialogVisible.value = false
    return
  }
  // 2. 提取导入的 SKU 列表
  const importedSkus = importedData.map((item) => item.warehouseSku).join(',')
  // 3. 调用 batchAddCommodity 获取商品的完整信息并过滤掉已有的 SKU
  const filteredSkusList = await batchAddCommodity(importedSkus, '3') // 使用 await 等待结果
  if (filteredSkusList.length === 0) {
    ElMessage.warning('导入的商品SKU已存在或无效')
    importedFileUrl.value = path
    importDialogVisible.value = false
    return
  }
  // 4. 将备注信息合并到获取到的商品列表中
  const mergedProductList = filteredSkusList.map((skuItem) => {
    // 在导入数据中找到匹配的备注信息
    const importedItem = importedData.find((item) =>
      skuItem.warehouseSku?.includes(item.warehouseSku),
    )
    const target = locationList.value.find((item: InterProductList) => {
      return item.locationCode == importedItem?.locationCode
    })
    const item = userMarkList.value.find(
      (e) => e.userId === importUserMark.value,
    )
    return {
      customerId: importUserMark.value !== 0 ? importUserMark.value : null,
      customerName: importUserMark.value !== 0 ? item?.userName || '' : null,
      userMark: importUserMark.value !== 0 ? item?.userMark : null,
      skuImage: skuItem.skuImage,
      currencyName: skuItem.currencyName,
      currencyCode: skuItem.currencyCode,
      warehouseSku: skuItem.warehouseSku,
      skuName: skuItem.productName,
      productNo: skuItem.productNo,
      locationCode: target?.locationCode ?? '',
      locationId: target?.locationId,
      costPrice: skuItem.costPrice,
      buyStored: importedItem?.buyStored ?? null,
      totalPrice: new BigNumber(
        (importedItem?.buyStored ?? 0) as number | string,
      )
        .multipliedBy(skuItem.costPrice ?? 0)
        .toNumber(),
      usableInventory: skuItem.usableInventory,
      remark: importedItem?.remark ?? null,
    } as InterProductList // 明确类型
  })
  // 5. 更新 otherPurchaseData
  otherPurchaseData.value = [...otherPurchaseData.value, ...mergedProductList]
  importedFileUrl.value = path
  importDialogVisible.value = false
}
const exportVisible = ref(false)
const exportForm = ref({
  delivery: false,
  resource: '',
})
const handleExport = () => {
  exportVisible.value = true
}
const submitExportForm = async () => {
  if (exportForm.value.resource === '') {
    return ElMessage.error('请选择导出类型')
  }
  let purchaseIds = ''
  let exportTotal: number | undefined = undefined
  const params: AnyObject = {}
  const resourceType = Number(exportForm.value.resource)
  if (resourceType === 0) {
    purchaseIds = tableData.value
      .map((el: InterWarehousePage) => el.id)
      .join(',')
  } else if (resourceType === 1) {
    purchaseIds = selections.value
      .map((el: InterWarehousePage) => el.id)
      .join(',')
  } else if (resourceType === 2) {
    purchaseIds = ''
    exportTotal = total.value
    params.billStatus = nodeCode.value == 'all' ? 'all' : nodeCode.value
  }
  params.idList = purchaseIds
  if (exportTotal !== undefined) {
    params.total = exportTotal
  }
  try {
    const res = await warehouseInRecordExport({
      showDetail: exportForm.value.delivery,
      ...params,
      ...searchForm.value,
    })
    window.open(filePath + res.message, '_blank')
    exportVisible.value = false
  } catch (e) {
    exportVisible.value = false
  }
}
const getWarehouseList = async () => {
  try {
    const res = await warehouseInfoGetAll()
    warehouseList.value = res.data
    await nextTick(() => {
      treeRef.value!.setCurrentKey(nodeCode.value, true)
    })
  } catch (e) {
    console.error(e)
  }
}
const rowClick = (row: InterWarehousePage) => {
  if (!row) {
    currentRow.value = null
  }
  currentRow.value = row
  tabsClick()
}
const tabsClick = async () => {
  if (!currentRow.value) {
    detailList.value = []
    logList.value = []
    return
  }
  await nextTick()
  if (tabsValue.value === '0') {
    searchDetail()
  } else if (tabsValue.value === '1') {
    getLogList()
  }
}
const [editForm, resetEditForm] = useValue<InterWarehouseDetail>({
  inNo: '',
  warehouseId: '',
  warehouseName: '',
  remark: '',
  factoryCode: '',
  factoryId: 0,
  productList: [],
})
const updateEditRemark = (value: string) => {
  editForm.value.remark = value
}
const updateEditWarehouseId = (value: number | string | undefined) => {
  editForm.value.warehouseId = value
}
const newDialogVisible = ref(false)
const receiptProductDialogRef = ref<{
  validateForm: () => Promise<void>
} | null>(null)
const editForm2 = ref({})
const formId = ref<number | undefined>(undefined)
const otherPurchaseData = ref<InterProductList[]>([])
const {
  skuData,
  setCostPrice,
  batchAddCommodity,
  selectbySku,
  skudblclick,
  filterSkuData,
} = useReceiptProductDialog({
  editForm,
  otherPurchaseData,
  userMark,
  batchUserMark,
  importUserMark,
  selectSku,
  userMarkList,
})

const getUserMark = async () => {
  const { data } = await getLocalFactoryList()
  userMarkList.value = [
    ...[{ userMark: '九猫商品', userId: 0, userName: '' }],
    ...data,
  ]
}

const addDialog = async (i: number, v: InterWarehousePage | null) => {
  await getUserMark()
  if (i === 2) {
    if (v) formId.value = v.id
    if (v) getProduct(v.id)
    if (!formId.value) return ElMessage('请勾选至少一条记录')
    // editForm.value = JSON.parse(JSON.stringify(v))
  } else {
    await nextTick()

    editForm.value = JSON.parse(JSON.stringify(editForm2.value))
    resetEditForm()
    const userJson = localStorage.getItem('user')
    if (userJson) {
      try {
        const userData = JSON.parse(userJson)
        editForm.value.factoryCode = userData.factoryCode || ''
        editForm.value.factoryId = userData.factoryId || 0
        const defaultWarehouse = warehouseList.value.find(
          (item: warehouseInfo) => item.defaulted === 1,
        )
        if (defaultWarehouse) {
          editForm.value.warehouseId = defaultWarehouse.id
          editForm.value.warehouseName = defaultWarehouse.name
        }
      } catch {
        // ignore
      }
    }
    otherPurchaseData.value = []
    formId.value = undefined
  }
  selectSku.value = ''
  newDialogVisible.value = true
}
const getProduct = async (id: number | undefined) => {
  try {
    const res = await getWarehouseInRecordDetailApi(id)
    editForm.value = JSON.parse(JSON.stringify(res.data))
    otherPurchaseData.value = res.data?.productList || []
  } catch (e) {
    console.error(e)
  }
}
const handleSelectionChange = (v: InterWarehousePage[]) => {
  selections.value = v
}
const otherWarehouseSelection = ref<InterProductList[]>([])
const productSelectionChange = (v: InterProductList[]) => {
  otherWarehouseSelection.value = v
}
const auditOrder = (key: string) => {
  if (selections.value.length === 0) {
    return ElMessage.warning('请选择要操作的数据')
  }
  let url = ''
  let text = ''
  switch (key) {
    case 'invalid':
      url = 'factory/warehouseInRecord/invalid'
      text = '作废'
      break
    case 'archiving':
      url = 'factory/warehouseInRecord/archive'
      text = '归档'
      break
    case 'submitAudit':
      url = 'factory/warehouseInRecord/submitAudit'
      text = '提交审核'
      break
    case 'audit':
      url = 'factory/warehouseInRecord/audit'
      text = '审核'
      break
  }
  const confimText =
    key === 'audit'
      ? '确定进行审核？点"确定"将会直接更改库存数量，请在审核前确认数量是否正确。'
      : `确定对选中的信息进行${text}？`
  ElMessageBox.confirm(confimText, '重要提示', {
    confirmButtonText: '确定',
    type: 'warning',
  }).then(async () => {
    const data = selections.value.map(
      ({ id, dataVersion }: InterWarehousePage) => ({
        id,
        dataVersion,
      }),
    )
    const loading = ElLoading.service({
      fullscreen: true,
      text: '操作中...',
      background: 'rgba(0, 0, 0, 0.3)',
    })
    try {
      await auditOrderApi(url, data)
      ElMessage.success('操作成功')
      search()
      await getTreeNum()
    } catch (e) {
      console.error(e)
    } finally {
      loading.close()
    }
  })
}
const rejectedInRecord = () => {
  if (selections.value.length === 0) {
    return ElMessage.warning('请选择要操作的数据')
  }
  ElMessageBox.prompt('请输入驳回原因', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    inputPattern: /.+/,
    customClass: 'reject',
    inputErrorMessage: '请输入驳回原因',
    inputPlaceholder: '驳回原因',
  }).then(async ({ value }: { value: string }) => {
    const data = selections.value.map(
      ({ id, dataVersion }: InterWarehousePage) => ({
        id,
        dataVersion,
      }),
    )
    try {
      await rejectInRecordApi({ list: data, rejectReason: value })
      ElMessage.success('操作成功')
      search()
      await getTreeNum()
    } catch (e) {
      console.error(e)
    }
  })
}
watch(
  () => tableData.value,
  () => {
    if (tableData.value && tableData.value.length > 0) {
      if (singleTableRef.value) {
        singleTableRef.value!.setCurrentRow(tableData.value[0])
        currentRow.value = (tableData.value as never)[0]
      }
    } else {
      detailList.value = []
    }
  },
  { immediate: true },
)
watch(
  () => editForm.value.warehouseId,
  (newVal: number | string | undefined) => {
    if (newVal) {
      fetchLocationList('')
    }
  },
)
const addOtherCurrency = async () => {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    try {
      await receiptProductDialogRef.value?.validateForm()
    } catch {
      return
    }
    const arr = otherPurchaseData.value
    if (arr.length === 0) {
      ElMessage.error('请至少选择一条数据')
      return
    }

    for (let i = 0; i < arr.length; i++) {
      if (!arr[i].buyStored) {
        ElMessage.error('请输入入库数量')
        return
      }
      if (!arr[i].locationId) {
        ElMessage.error('请选择库位')
        return
      }
      const found = locationList.value.find(
        (item: InterProductList) => item.locationId === arr[i].locationId,
      )
      if (!arr[i].locationCode) {
        arr[i].locationCode = found ? found?.locationCode : ''
      }
    }
    if (!formId.value) {
      await addSection()
    } else {
      await upSection()
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.close()
  }
}

const addSection = async () => {
  const params = { ...editForm.value }
  params.productList = otherPurchaseData.value
  try {
    await addInRecordApi(params)
    ElMessage.success('保存成功')
    newDialogVisible.value = false
    search()
    await getTreeNum()
  } catch (e) {
    console.error(e)
  }
  // post(url, params).then((res: any) => {
  //   if (res.code === 200) {
  //     otherDialogVisible.value = false;
  //     ElConfirm('保存成功，是否打印标签?', '提示', {
  //       confirmButtonText: '确定',
  //       cancelButtonText: '取消',
  //       type: 'warning',
  //     })
  //       .then(() => {
  //         if (res.message) {
  //           getPrintData(res.message, true);
  //         } else {
  //           ElMessage.warning('入口单号为空，无法打印');
  //         }
  //       })
  //       .catch((e: any) => {
  //         console.error(e);
  //       });
  //     getList();
  //     getStatusAmount();
  //   } else {
  //     ElAlert(res.message, '错误提示', {
  //       dangerouslyUseHTMLString: true,
  //     });
  //   }
  // });
}
const upSection = async () => {
  const params = { ...editForm.value }
  // params.productList = otherPurchaseData.value
  const result = checkUpdateParams(
    { ...params, productList: otherPurchaseData.value },
    editForm.value as unknown as AnyObject,
    'id',
    {
      productList: 'warehouseSku',
    },
  )

  try {
    await updateInRecordApi(result)
    newDialogVisible.value = false
    ElMessage.success('修改成功')
    search()
    await getTreeNum()
  } catch (e) {
    console.error(e)
  }
}
const addPurchaseVisible = ref(false)
const purchaseTextarea = ref('')
const addPurchase = async () => {
  addPurchaseVisible.value = true
  batchUserMark.value = 0
  purchaseTextarea.value = ''
}
const submitPurchase = async () => {
  if (!purchaseTextarea.value) {
    ElMessage.warning('请输入库存 SKU')
    return
  }
  const item = userMarkList.value.find((e) => e.userId === batchUserMark.value)
  const filteredSkusList = await batchAddCommodity(purchaseTextarea.value, '2')
  const mergedProductList = filteredSkusList.map((skuItem) => {
    return {
      customerId: batchUserMark.value !== 0 ? batchUserMark.value : null,
      customerName: batchUserMark.value !== 0 ? item?.userName || '' : null,
      userMark: batchUserMark.value !== 0 ? item?.userMark : null,
      skuImage: skuItem.skuImage,
      warehouseSku: skuItem.warehouseSku,
      currencyName: skuItem.currencyName,
      currencyCode: skuItem.currencyCode,
      skuName: skuItem.productName,
      productNo: skuItem.productNo,
      locationCode: skuItem.locationCode ?? '',
      locationId: skuItem.locationId ?? null,
      costPrice: skuItem.costPrice,
      buyStored: null,
      totalPrice: null,
      usableInventory: skuItem.usableInventory,
      remark: null,
    } as InterProductList
  })
  otherPurchaseData.value = [...otherPurchaseData.value, ...mergedProductList]
  addPurchaseVisible.value = false
}
const deleteOtherWarehousing = () => {
  const arr = otherWarehouseSelection.value
  if (arr.length === 0) return
  const idList = arr.map((v: InterProductList) => v.warehouseSku)
  otherPurchaseData.value = otherPurchaseData.value.filter(
    (item: InterProductList) => !idList.includes(item.warehouseSku),
  )
}
const importDialogVisible = ref(false)
const importedFileUrl = ref('')
const importData = async () => {
  importDialogVisible.value = true
  importedFileUrl.value = ''
  importUserMark.value = 0
}
const handleBatchDelete = async () => {
  if (!selections.value.length) {
    return ElMessage.warning('请选择要删除的数据')
  }
  await ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  const str = selections.value.map((el: InterWarehousePage) => el.id).join(',')
  await deleteWarehouseInRecordApi(str)
  ElMessage.success('删除成功')
  search()
  await getTreeNum()
}
const nodeClick = (data: InterWarehouseTree) => {
  nodeCode.value = data.code ?? ''
  sessionStorage.setItem('InRecord_NodeCode', data.code ?? '')
  search()
}
// const detailPager = ref({
//   page: 1,
//   rows: 100,
//   total: 0,
// })
const searchDetail = async () => {
  detailLoading.value = true
  try {
    const res = await getWarehouseInRecordDetailApi(currentRow.value?.id)
    res.data.productList.forEach((item) => {
      item.currencyName = res.data.currencyName || ''
      item.currencyCode = res.data.currencyCode || ''
    })
    detailList.value = res.data?.productList || []
  } catch (e) {
    console.error(e)
  } finally {
    detailLoading.value = false
  }
}
const getLogList = async () => {
  detailLoading.value = true
  try {
    const res = await getInRecordLogApi(currentRow.value?.id)
    logList.value = res.data
  } catch (e) {
    console.error(e)
  } finally {
    detailLoading.value = false
  }
}
const locationList = ref<ILocation[]>([])
const locationLoading = ref(false)

const fetchLocationList = async (query: string) => {
  // if (!query) {
  //   locationList.value = []
  //   return
  // }
  if (!editForm.value.warehouseId) return
  locationLoading.value = true
  try {
    const res = await getByWareHouseIdAndCodeApi(
      editForm.value.warehouseId,
      query,
    )
    const result = res.data || []
    locationList.value = result.map((item: ILocation) => {
      return {
        locationId: item.id,
        locationCode: item.locationCode,
      }
    })
    if (otherPurchaseData.value?.length > 0) {
      //const importedSkus = otherPurchaseData.value.map((item) => item.warehouseSku).join(',')
      // // 3. 调用 batchAddCommodity 获取商品的完整信息并过滤掉已有的 SKU
      // const filteredSkusList = await batchAddCommodity(importedSkus)
      // console.log('filteredSkusList', otherPurchaseData.value)
      // 新增时切换仓库将重新匹配表格库位，确保该商品的库位和仓库一一对应
      otherPurchaseData.value = otherPurchaseData.value.map(
        (item: InterProductList) => {
          const foundItem = locationList.value.find(
            (locationItem: ILocation) =>
              locationItem.locationCode === item.locationCode,
          )
          // 创建新对象而不是修改原对象
          return {
            ...item,
            locationCode: foundItem ? foundItem.locationCode : '',
            locationId: foundItem ? foundItem.locationId : null,
          }
        },
      )
    }
  } catch (e) {
    locationList.value = []
  } finally {
    locationLoading.value = false
  }
}
// 输入2秒后再调用接口(节流)
// const handleLocationSearch = debounce(fetchLocationList, 2000)
const handleLocationChange = (
  val: number | null | undefined,
  row: InterProductList,
) => {
  const found = locationList.value.find(
    (item: InterProductList) => item.locationId === val,
  )
  row.locationCode = found ? found.locationCode : ''
}
const handleWarehouseChange = (val: number | string | undefined) => {
  const found = warehouseList.value.find(
    (item: warehouseInfo) => item.id === val,
  )
  editForm.value.warehouseName = found ? found.name : ''
}

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

useEnterKeyTrigger({
  formRef: searchFormRef,
  btnRef: searchBtnRef,

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

onMounted(() => {
  getTreeNum()
  getWarehouseList()
})
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: inline-block;
  width: 500px;
  text-align: center;
}

.header-filter-form {
  :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;
}

.delivery-note-list {
  :deep(.vertical-align-top) {
    vertical-align: top;
  }
}

.left {
  width: 160px;

  :deep(.el-tree-node__content) {
    height: 30px;
    line-height: 30px;
  }

  :deep(.el-tree-node__label) {
    font-size: 13px;
    cursor: pointer;
    display: inline-block;
    width: 100%;
    color: black !important;

    padding: 3px 7px;
  }

  :deep(.el-tree-node__expand-icon) {
    display: none;
  }

  :deep(.is-current) {
    .tree-node-label,
    .tree-node-count {
      background-color: #ecf5ff;
      color: #409eff !important;
    }

    .el-tree-node__children {
      .tree-node-label,
      .tree-node-count {
        background-color: transparent !important;
        color: black !important;
      }
    }
  }
}

.tree-node {
  display: flex;
  color: #333;
  font-weight: 500;
}

.right {
  flex: 1;
  flex-shrink: 0;
  background: white;
  overflow: hidden;
}

::v-deep(.el-tree-node__label) {
  font-size: 13px;
  color: rgb(96, 98, 102);
  cursor: pointer;
}

::v-deep(.el-tree-node__expand-icon) {
  display: none;
}

::v-deep(.el-tree-node__label) {
  display: inline-block;
  width: 100%;
  color: black !important;

  padding: 3px 7px;
}

::v-deep(.is-current) {
  .el-tree-node__label {
    background-color: #ecf5ff;
    color: #409eff !important;
  }

  .el-tree-node__children {
    .el-tree-node__label {
      background-color: transparent !important;
      color: black !important;
    }
  }
}

::v-deep(.splitpanes__pane) {
  display: flex;
  flex-direction: column;
}

::v-deep(.splitpanes--horizontal > .splitpanes__splitter) {
  min-height: 5px;
  margin-top: 10px;
}

.draw-line {
  width: 100%;
  height: 5px;
  background: #eff3f6;
}

.btn-list {
  margin-bottom: 10px;
}

::v-deep(.el-tree-node) {
  cursor: pointer;
}

::v-deep(.el-tree-node__label) {
  font-size: 14px;
}

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

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

    .el-tab-pane {
      height: 100%;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
  }
}

.delivery-note-page {
  :deep(#top) {
    height: 100%;
  }
}

.import-dialog {
  .import-content {
    padding-bottom: 20px;
  }
}

.import-success {
  text-align: center;
  padding: 20px 0;

  .success-icon {
    font-size: 48px;
    margin-bottom: 16px;
  }

  .success-text {
    font-size: 16px;
    color: #67c23a;
    margin-bottom: 16px;
  }

  .file-link {
    a {
      color: #409eff;
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }
  }
}
</style>
