<script setup lang="ts">
import {
  factoryWarehouseInfo,
  warehouseInfo,
  warehouseInfoGetAll,
  updateLocationApi,
  updateProductNoApi,
  updateCustomSkuApi,
  getWarehouseInventoryInfo,
  factoryLogWarehouseLog,
  LogListData,
  WarehouseWarning,
  factoryWarehouseInventoryPrint,
  exportWarehouseInfo,
  loactionData,
} from '@/api/warehouse.ts'
import { AnyObject } from '@/types/api/warehouse'
import { ref, computed } from 'vue'
import SplitDiv from '@/components/splitDiv/splitDiv.vue'
import { filePath } from '@/api/axios.ts'
import { useEnterKeyTrigger } from '@/utils/hooks/useEnterKeyTrigger.ts'
import { getInventoryLowerLimitApi } from '@/api/externalAuth'
import { LocationInfoGetAll } from '@/api/common'

const searchForm = ref({
  warehouseId: '',
  inventoryStart: '',
  inventoryEnd: '',
  productNo: '',
  skuName: '',
  warehouseSku: '',
  occupyInventory: '',
  freezeInventory: '',
  inventory: '',
  usableInventoryStart: '',
  usableInventoryEnd: '',
  occupyInventoryEnd: '',
  occupyInventoryStart: '',
})
const warehouseList = ref<warehouseInfo[]>([])
const logList = ref<LogListData[]>([])
const selections = ref<WarehouseWarning[]>([])
const leftData = ref<WarehouseWarning[]>([])
const pagination = ref<factoryWarehouseInfo>({
  pageSize: 50,
  currentPage: 1,
  total: 0,
})
const isSameWarehouse = computed(() => {
  if (selections.value.length === 0) return false
  const firstId = selections.value[0]?.warehouseId
  return selections.value.every(
    (item: WarehouseWarning) => item.warehouseId === firstId,
  )
})
const modifyLocationDialog = ref(false)
const modifyProductNoDialog = ref(false)
const modifyCustomSkuDialog = ref(false)

/** 修改库位 */
const locationForm = ref({
  warehouseId: '',
})
const submitLocationForm = async () => {
  if (locationForm.value.warehouseId) {
    const idList = selections.value.map((el: WarehouseWarning) => Number(el.id))
    const res = await updateLocationApi({
      idList: idList,
      locationId: locationForm.value.warehouseId,
    })
    if (res.code == 200) {
      modifyLocationDialog.value = false
      ElMessage.success('修改成功')
      getData()
    }
  } else {
    ElMessage.warning('请选择库位')
  }
}
const LocationList = ref<loactionData[]>([])
const modifyStorageLocation = async () => {
  locationForm.value.warehouseId = ''
  modifyLocationDialog.value = true
  const { data } = await LocationInfoGetAll(selections.value[0]?.warehouseId)
  LocationList.value = data
}

/** 修改款号 */
const productNoForm = ref({
  productNo: '',
})
const productNoRules = {
  productNo: [{ required: true, message: '款号不能为空', trigger: 'change' }],
}
const productNoFormRef = ref()
const modifyProductNo = async () => {
  productNoForm.value.productNo = ''
  productNoFormRef.value?.resetFields()
  modifyProductNoDialog.value = true
}
const submitProductNoForm = async () => {
  productNoFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return
    const loading = ElLoading.service({
      fullscreen: true,
      text: '操作中...',
      background: 'rgba(0, 0, 0, 0.3)',
    })
    const idList = selections.value.map((el: WarehouseWarning) => Number(el.id))
    await updateProductNoApi({
      idList: idList,
      productNo: productNoForm.value.productNo,
    })
      .then(() => {
        modifyProductNoDialog.value = false
        ElMessage.success('修改成功')
        getData()
      })
      .finally(() => {
        loading.close()
      })
  })
}

/** 修改自定义SKU */
const customSkuForm = ref({
  customSku: '',
})
const customSkuRules = {
  customSku: [
    { required: true, message: '自定义SKU不能为空', trigger: 'change' },
  ],
}
const customSkuFormRef = ref()
const modifyCustomSku = async () => {
  customSkuForm.value.customSku = selections.value[0].customSku || ''
  customSkuFormRef.value?.resetFields()
  modifyCustomSkuDialog.value = true
}
const submitCustomSkuForm = async () => {
  customSkuFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return
    const loading = ElLoading.service({
      fullscreen: true,
      text: '操作中...',
      background: 'rgba(0, 0, 0, 0.3)',
    })
    const idList = selections.value.map((el: WarehouseWarning) => Number(el.id))
    updateCustomSkuApi({
      idList: idList,
      customSku: customSkuForm.value.customSku,
    })
      .then(() => {
        modifyCustomSkuDialog.value = false
        ElMessage.success('修改成功')
        getData()
      })
      .finally(() => {
        loading.close()
      })
  })
}

const showPrintDialog = ref(false)
const exportLoading = ref(false)
const clickItem = (row: WarehouseWarning) => {
  if (!row) return
  getDetail(row.id)
}

async function getData() {
  const res = await getWarehouseInventoryInfo({
    ...pagination.value,
    ...searchForm.value,
  })
  const sortedRecords = res.data.records.sort((a, b) => {
    const aUsable =
      Number(
        (a as WarehouseWarning & { usableInventory?: number | string })
          .usableInventory,
      ) || 0
    const bUsable =
      Number(
        (b as WarehouseWarning & { usableInventory?: number | string })
          .usableInventory,
      ) || 0
    const aIsLow = aUsable < 100
    const bIsLow = bUsable < 100
    if (aIsLow && !bIsLow) return -1
    if (!aIsLow && bIsLow) return 1
    return 0
  })
  leftData.value = sortedRecords
  pagination.value.total = res.data.total
  if (leftData.value.length) {
    getDetail(leftData.value[0].id)
  }
}

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

// async function exportData() {
//   if (!selections.value.length) {
//     return ElMessage.warning('请选择数据')
//   }
//   exportLoading.value = true
//   const ids: number[] = []
//   selections.value.forEach((el) => {
//     if (el.id) ids.push(Number(el.id))
//   })
//   try {
//     const res = await exportWarehouseInfo({
//       ...searchForm.value,
//       idList: ids,
//     })
//     window.open(filePath + res.message, '_blank')
//     exportLoading.value = false
//   } catch (e) {
//     exportLoading.value = false
//   }
// }
const exportVisible = ref(false)
const exportForm = ref({
  resource: '',
})
const exportData = () => {
  exportVisible.value = true
}
const submitExportForm = async () => {
  if (exportForm.value.resource === '') {
    return ElMessage.error('请选择导出类型')
  }
  exportLoading.value = true
  let purchaseIds: number[] = []
  let exportTotal: number | undefined = undefined
  const params: AnyObject = {}
  const resourceType = Number(exportForm.value.resource)
  if (resourceType === 0) {
    purchaseIds = leftData.value.map((el: WarehouseWarning) => Number(el.id))
  } else if (resourceType === 1) {
    purchaseIds = selections.value.map((el: WarehouseWarning) => Number(el.id))
  } else if (resourceType === 2) {
    purchaseIds = []
    exportTotal = pagination.value.total
  }
  params.idList = purchaseIds
  if (exportTotal !== undefined) {
    params.total = exportTotal
  }
  try {
    const res = await exportWarehouseInfo({
      ...params,
      ...searchForm.value,
    })
    window.open(filePath + res.message, '_blank')
    exportVisible.value = false
    exportLoading.value = false
  } catch (e) {
    exportVisible.value = false
    exportLoading.value = false
  }
}
async function printProductTag() {
  if (!selections.value.length) {
    return ElMessage.warning('请选择数据')
  }
  showPrintDialog.value = true
  selections.value.forEach((el) => {
    el.number = ''
  })
}

const getDetail = async (id: number | string | undefined) => {
  const { data } = await factoryLogWarehouseLog(id)
  logList.value = data
}
const handleSelectionChange = (data: WarehouseWarning[]) => {
  selections.value = JSON.parse(JSON.stringify(data))
}
const handleSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize
  getData()
}
const handleCurrentChange = (currentPage: number) => {
  pagination.value.currentPage = currentPage
  getData()
}

const getWarehouse = async () => {
  const { data } = await warehouseInfoGetAll()
  warehouseList.value = data
}

const getRowClassName = (row: { row: WarehouseWarning }) => {
  const rowData = row.row as WarehouseWarning & {
    usableInventory?: number | string
  }
  const usableInventory = Number(rowData.usableInventory) || 0
  if (usableInventory < inventoryLowerLimit.value) {
    return 'low-inventory-row'
  }
  return ''
}

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

useEnterKeyTrigger({
  formRef: searchFormRef,
  btnRef: searchBtnRef,

  callback: (event: KeyboardEvent) => {
    console.log('回车键被按下', event)
    getData()
  },
})
const inventoryLowerLimit = ref<number>(100)
const getInventoryLowerLimit = async () => {
  try {
    const res = await getInventoryLowerLimitApi()
    if (res.code !== 200) {
      return
    }
    inventoryLowerLimit.value = res.data
  } catch (error) {
    console.log(error)
  }
}
onMounted(async () => {
  getData()
  getWarehouse()
  getInventoryLowerLimit()
})
</script>

<template>
  <split-div>
    <template #top>
      <el-dialog v-model="showPrintDialog" title="打印参数设置">
        <el-table height="400px" :data="selections" 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="locationCode"
            label="库位编码"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="productNo"
            label="款号 "
          ></el-table-column>
          <el-table-column align="center" prop="number" label="打印数量">
            <template #default="{ row }">
              <el-input
                v-model="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>
      <el-card>
        <el-form
          class="search-form"
          inline
          :model="searchForm"
          ref="searchFormRef"
        >
          <el-form-item label="仓库">
            <el-select
              v-model="searchForm.warehouseId"
              clearable
              filterable
              placeholder="请输入仓库"
              style="width: 140px"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="库存SKU">
            <el-input
              v-model="searchForm.warehouseSku"
              style="width: 140px"
              placeholder="请输入库存SKU"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input
              v-model="searchForm.skuName"
              style="width: 140px"
              placeholder="请输入商品名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="款号">
            <el-input
              v-model="searchForm.productNo"
              style="width: 140px"
              placeholder="请输入款号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="库存数">
            <el-input
              v-model="searchForm.inventoryStart"
              style="width: 80px; margin-right: 5px"
              placeholder=""
              clearable
            ></el-input>
            -
            <el-input
              v-model="searchForm.inventoryEnd"
              style="width: 80px; margin-left: 5px"
              placeholder=""
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="可用数">
            <el-input
              v-model="searchForm.usableInventoryStart"
              style="width: 80px; margin-right: 5px"
              placeholder=""
              clearable
            ></el-input>
            -
            <el-input
              v-model="searchForm.usableInventoryEnd"
              style="width: 80px; margin-left: 5px"
              placeholder=""
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="占用数">
            <el-input
              v-model="searchForm.occupyInventoryStart"
              style="width: 80px; margin-right: 5px"
              placeholder=""
              clearable
            ></el-input>
            -
            <el-input
              v-model="searchForm.occupyInventoryEnd"
              style="width: 80px; margin-left: 5px"
              placeholder=""
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item style="margin-top: 5px">
            <el-button type="primary" @click="getData" ref="searchBtnRef"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item style="margin-top: 5px">
            <el-button type="primary" @click="printProductTag"
              >打印库存SKU标签</el-button
            >
          </el-form-item>
          <el-form-item style="margin-top: 5px">
            <el-button
              :loading="exportLoading"
              type="success"
              @click="exportData"
              >导出</el-button
            >
          </el-form-item>
          <el-form-item style="margin-top: 5px">
            <el-button
              type="warning"
              :disabled="!isSameWarehouse"
              @click="modifyStorageLocation"
              >修改库位</el-button
            >
          </el-form-item>
          <el-form-item style="margin-top: 5px">
            <el-button
              type="warning"
              :disabled="!selections.length"
              @click="modifyProductNo"
              >修改款号
            </el-button>
          </el-form-item>
          <el-form-item style="margin-top: 5px">
            <el-button
              type="warning"
              :disabled="selections.length !== 1"
              @click="modifyCustomSku"
              >修改自定义sku</el-button
            >
          </el-form-item>
        </el-form>
      </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">
                <el-table
                  highlight-current-row
                  height="100%"
                  :data="leftData"
                  border
                  :row-class-name="getRowClassName"
                  @current-change="clickItem"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column align="center" fixed type="selection" />
                  <el-table-column
                    align="center"
                    fixed="left"
                    type="index"
                    label="序号"
                    width="60"
                  />
                  <el-table-column
                    align="center"
                    prop="warehouseName"
                    label="图片"
                    width="80"
                  >
                    <template #default="scope">
                      <el-image
                        :preview-teleported="true"
                        style="width: 40px"
                        :src="scope.row.image"
                        :preview-src-list="[scope.row.image]"
                      ></el-image>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="warehouseName"
                    label="仓库名称"
                    width="140"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="locationCode"
                    label="库位"
                    width="100"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="warehouseSku"
                    label="库存SKU"
                    min-width="180"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="customSku"
                    label="自定义SKU"
                    min-width="180"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="skuName"
                    label="商品名称"
                    min-width="230"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="productNo"
                    label="款号"
                    width="140"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="unit"
                    label="单位"
                    width="60"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="currencyName"
                    label="币种"
                    width="80"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="price"
                    label="商品成本价"
                    width="140"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="usableInventory"
                    label="可用数量"
                    width="90"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="inventory"
                    label="库存数量"
                    width="90"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="occupyInventory"
                    label="占用数量"
                    width="90"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="freezeInventory"
                    label="冻结数量"
                    width="90"
                  ></el-table-column>
                </el-table>
              </div>
              <div class="pagination">
                <el-pagination
                  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="库存操作明细">
            <ul
              style="
                display: flex;
                flex-direction: column;
                color: #333;
                font-size: 13px;
                height: 100%;
                overflow: auto;
                white-space: pre;
              "
            >
              <li v-for="(item, index) in logList" :key="index">
                {{ item.createTime + ' ' + item.description }}
              </li>
            </ul>
          </el-tab-pane>
        </el-tabs>
      </div>
    </template>
  </split-div>

  <!-- 导出 -->
  <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">
          <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>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exportVisible = false">取消</el-button>
        <el-button type="primary" @click="submitExportForm">确认</el-button>
      </span>
    </template>
  </ElDialog>

  <!-- 修改库位 -->
  <ElDialog
    v-model="modifyLocationDialog"
    title="修改库位"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form :model="locationForm" label-width="80px">
      <el-form-item label="选择库位" prop="warehouseId">
        <el-select
          v-model="locationForm.warehouseId"
          clearable
          filterable
          placeholder="请选择库位"
        >
          <el-option
            v-for="item in LocationList"
            :key="item.id"
            :label="item.locationCode"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="modifyLocationDialog = false">取消</el-button>
        <el-button type="primary" @click="submitLocationForm">确认</el-button>
      </span>
    </template>
  </ElDialog>

  <!-- 修改款号  -->
  <ElDialog
    v-model="modifyProductNoDialog"
    title="修改款号"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="productNoFormRef"
      :model="productNoForm"
      :rules="productNoRules"
      label-width="80px"
      @submit.prevent
    >
      <el-form-item label="款号" prop="productNo">
        <el-input
          v-model="productNoForm.productNo"
          style="width: 100%"
          placeholder="请输入款号"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="modifyProductNoDialog = false">取消</el-button>
        <el-button type="primary" @click="submitProductNoForm">确认</el-button>
      </span>
    </template>
  </ElDialog>

  <!-- 修改自定义sku -->
  <ElDialog
    v-model="modifyCustomSkuDialog"
    title="修改自定义sku"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="customSkuFormRef"
      :model="customSkuForm"
      :rules="customSkuRules"
      label-width="100px"
      @submit.prevent
    >
      <el-form-item label="自定义sku" prop="customSku">
        <el-input
          v-model="customSkuForm.customSku"
          style="width: 100%"
          placeholder="请输入自定义sku"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="modifyCustomSkuDialog = false">取消</el-button>
        <el-button type="primary" @click="submitCustomSkuForm">确认</el-button>
      </span>
    </template>
  </ElDialog>
</template>

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

.el-card {
  ::v-deep(.el-card__body) {
    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-top: 10px;
      justify-content: center;
    }

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

::v-deep(.el-table) {
  .low-inventory-row {
    &:hover {
      background-color: #f56c6c !important;
      color: #fff !important;
    }

    td {
      background-color: #f56c6c !important;
      color: #fff !important;
    }

    &:hover td {
      background-color: #f56c6c !important;
      color: #fff !important;
    }
  }
}

.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>
