<template>
  <div class="page card h-100 flex-gap-10 overflow-hidden flex">
    <div class="status-container">
      <div
        class="status-item"
        :class="{ 'is-active': currentStatus === 'sharedInventory' }"
        @click="handleStatusClick('sharedInventory')"
      >
        <span>共享库存设置</span>
      </div>
    </div>

    <div class="content-container flex-1 flex-column overflow-hidden">
      <div class="search-form">
        <ElForm ref="searchFormRef" :model="searchForm" inline>
          <ElFormItem label="创建时间">
            <ElDatePicker
              v-model="dateRange"
              :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="库存SPU">
            <ElInput
              v-model="searchForm.warehouseSpu"
              clearable
              placeholder="库存SKU"
              style="width: 140px"
            />
          </ElFormItem>
          <ElFormItem label="库存组名称">
            <ElInput
              v-model="searchForm.groupName"
              clearable
              placeholder="库存组名称"
              style="width: 140px"
            />
          </ElFormItem>
          <ElFormItem label="状态"
            ><ElSelect
              v-model="searchForm.status"
              placeholder="请选择"
              style="width: 140px"
              clearable
            >
              <ElOption label="启用" :value="1" />
              <ElOption label="禁用" :value="0" />
            </ElSelect>
          </ElFormItem>
          <ElFormItem>
            <ElButton @click="resetSearchForm">重置</ElButton>
          </ElFormItem>
          <ElFormItem>
            <ElButton type="primary" @click="search">查询</ElButton>
          </ElFormItem>
          <ElFormItem>
            <ElButton type="success" @click="() => handleEdit()">新增</ElButton>
          </ElFormItem>
          <ElFormItem>
            <ElButton type="danger" @click="handleDelete">删除</ElButton>
          </ElFormItem>
        </ElForm>
      </div>
      <div class="table-wrapper">
        <TableView
          serial-numberable
          :selectionable="true"
          :paginated-data="tableData"
          :columns="tableColumns"
          @selection-change="handleSelectionChange"
        />
      </div>
      <div class="table-pagination-bar">
        <div class="selected-count-text">
          已选择
          <strong style="color: red">{{ selectedRows.length }}</strong>
          条数据
        </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: 0 auto"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
  </div>
  <EditFormDialog
    ref="editFormRef"
    v-model:visible="editDialogVisible"
    :warehouse-list="warehouseList"
    @save-success="search"
  />
</template>
<script lang="ts" setup>
import {
  getWarehouseRuleSettingListApi,
  getWarehouseRuleSettingDetailApi,
  deleteSharedInventoryGroupApi,
} from '@/api/warehouse/warehouseRuleSetting'
import {
  SearchForm,
  WarehouseRuleSettingData,
} from '@/types/api/warehouse/warehouseRuleSetting'
import usePageList from '@/utils/hooks/usePageList'
import { useValue } from '@/utils/hooks/useValue'
import { ElDatePicker, ElFormItem } from 'element-plus'
import { useWarehouseRuleSettingTableColumns } from './hooks/useWarehouseRuleSettingTableColumns'
import EditFormDialog from './components/EditDialog.vue'
import { WarehouseListData } from '@/types'
import { loadWarehouseListApi } from '@/api/common.ts'
const [searchForm, resetSearchForm] = useValue<SearchForm>({
  createStartTime: '',
  createEndTime: '',
  warehouseSpu: '',
  groupName: '',
  status: 1,
})
const dateRange = ref([])
const currentStatus = ref('sharedInventory')
const editDialogVisible = ref(false)
const editFormRef = ref()
const warehouseList = ref<WarehouseListData[]>([])
const handleStatusClick = (status: string) => {
  currentStatus.value = status
}

const {
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList<WarehouseRuleSettingData>({
  query: (page, pageSize) =>
    getWarehouseRuleSettingListApi(
      {
        ...searchForm.value,
        createEndTime: dateRange.value && dateRange.value[1],
        createStartTime: dateRange.value && dateRange.value[0],
      },
      page,
      pageSize,
    ).then((res) => res.data),
})
const selectedRows = ref<WarehouseRuleSettingData[]>([])
const handleSelectionChange = (selection: WarehouseRuleSettingData[]) => {
  selectedRows.value = selection
}

const handleEdit = async (row?: WarehouseRuleSettingData) => {
  if (row) {
    // 调用接口，获取数据
    const loading = ElLoading.service({
      fullscreen: true,
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.3)',
    })
    try {
      const res = await getWarehouseRuleSettingDetailApi(row.id)
      if (res.code !== 200) return
      editFormRef.value.resetFields(res.data)
    } catch (error) {
      console.error(error)
    } finally {
      loading.close()
    }
  } else {
    await editFormRef.value.resetFields()
  }
  editDialogVisible.value = true
}
const getSharedSpuText = (rows: WarehouseRuleSettingData[]) =>
  [
    ...new Set(
      rows.flatMap((row) =>
        (row.skuList ?? [])
          .map((item) => item.warehouseSpu)
          .filter(Boolean),
      ),
    ),
  ].join(',')

const handleDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  const groupNames = selectedRows.value
    .map((item) => item.groupName)
    .join(',')
  const spuText = getSharedSpuText(selectedRows.value)
  try {
    await ElMessageBox.confirm(
      `<div>
        <div style="font-size: 16px; color: #303133; line-height: 24px; margin-bottom: 8px;">
          确定删除共享库存组${groupNames}吗?
        </div>
        <div style="font-size: 14px; color: #606266; line-height: 22px;">
          共享库存组SPU：${spuText || '-'}
        </div>
      </div>`,
      '',
      {
        type: 'warning',
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'delete-shared-inventory-group-box',
      },
    )
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await deleteSharedInventoryGroupApi(
      selectedRows.value.map((item) => item.id).join(','),
    )
    if (res.code !== 200) return
    ElMessage.success(res.message)
    search()
  } catch (error) {
    console.error(error)
  } finally {
    loading.close()
  }
}
const { columns: tableColumns } = useWarehouseRuleSettingTableColumns({
  onEdit: handleEdit,
})
const loadWarehouseList = async () => {
  const res = await loadWarehouseListApi()
  if (res.code !== 200) return
  warehouseList.value = res.data || []
}
onMounted(async () => {
  loadWarehouseList()
})
</script>
<style scoped lang="scss">
.status-container {
  width: 160px;
  .status-item {
    font-size: 14px;
    line-height: 30px;
    height: 30px;
    cursor: pointer;
    padding-left: 18px;
    &:hover {
      background-color: #f5f7fa;
    }
    &.is-active {
      background-color: #ecf5ff;
      color: #409eff;
      font-weight: 500;
    }
  }
}
.table-wrapper {
  flex: 1;
  overflow: hidden;
}
.table-pagination-bar {
  margin-top: 10px;
  display: flex;
  align-items: center;
}
.selected-count-text {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}
</style>
<style>
.delete-shared-inventory-group-box .el-message-box__title {
  display: none;
}

.delete-shared-inventory-group-box .el-message-box__header {
  padding-bottom: 0;
}

.delete-shared-inventory-group-box .el-message-box__message {
  word-break: break-all;
  line-height: 1.6;
  padding: 10px 0;
}
</style>
