<script setup lang="ts">
import {
  factoryWarehouseInfo,
  warehouseInfo,
  warehouseInfoGetAll,
  updateLocationApi,
  LocationInfoGetAll,
  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'

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 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 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,
  })
  leftData.value = res.data.records
  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
}
getData()
getWarehouse()
</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">
          <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">查询</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>
      </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
                  @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="100"
                  >
                    <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="180"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="locationCode"
                    label="库位"
                    width="160"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="warehouseSku"
                    label="库存SKU"
                    width="180"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="skuName"
                    label="商品名称"
                    width="250"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="productNo"
                    label="款号"
                    width="150"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="unit"
                    label="单位"
                    width="80"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="price"
                    label="商品成本价（￥）"
                    width="160"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="usableInventory"
                    label="可用数量"
                    width="120"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="inventory"
                    label="库存数量"
                    width="120"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="occupyInventory"
                    label="占用数量"
                    width="120"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="freezeInventory"
                    label="冻结数量"
                    width="120"
                  ></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>
</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;
    }
  }
}

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