<template>
  <div class="user-page flex-column card h-100 overflow-hidden">
    <div class="flex-column h-100 overflow-hidden">
      <div class="header-filter-form">
        <el-form ref="searchFormRef" inline :model="searchForm">
          <el-form-item label="分拣口">
            <el-select
              v-model="searchForm.sortingArea"
              clearable
              style="width: 160px"
              placeholder="请选择分拣口"
            >
              <el-option
                v-for="item in sortingList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分拣口说明">
            <el-input
              v-model="searchForm.sortingRemark"
              placeholder="请输入分拣口说明"
              clearable
              style="width: 220px"
            />
          </el-form-item>
          <el-form-item>
            <el-button ref="searchBtnRef" type="primary" @click="search"
              >查询</el-button
            >
            <el-button type="success" @click="createWarehouse">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="user-content flex-1 flex-column overflow-hidden">
        <div class="user-list flex-1 overflow-hidden">
          <div v-loading="loading" class="table-container">
            <TableView :paginated-data="tableData" :columns="columns">
              <template #operation="{ row }">
                <el-button type="primary" link @click="updateSorting(row)">
                  编辑
                </el-button>
                <el-button type="danger" link @click="handleBatchDelete(row)">
                  删除
                </el-button>
              </template>
            </TableView>
          </div>
        </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>
    </div>
    <CreateSortingRuleDialog
      ref="createDialogRef"
      :logistics-methods-list="logisticsMethodsList"
      @success="search"
    />
  </div>
</template>
<script setup lang="ts">
import { Ilogistics, IsortingInfo } from '@/types/api/logistics'
import {
  getsortingConfigListApi,
  deleteSortingApi,
  getSortingPortAreaListApi,
} from '@/api/logistics'
import { allErpCodeListApi } from '@/api/podCnOrder'
import { ref } from 'vue'
import CreateSortingRuleDialog from './components/CreateSortingRuleDialog.vue'
import { useEnterKeyTrigger } from '@/utils/hooks/useEnterKeyTrigger.ts'
import TableView from '@/components/TableView.vue'
import type { CustomColumn } from '@/types/table'
import usePageList from '@/utils/hooks/usePageList'
import { ElMessage, ElMessageBox } from 'element-plus'

const columns: CustomColumn<IsortingInfo>[] = [
  {
    key: 'sortNo',
    prop: 'sortNo',
    label: '序号',
    width: 100,
    align: 'center',
  },
  {
    key: 'conditionsText',
    prop: 'conditionsText',
    label: '分拣口规则',
    minWidth: 250,
    align: 'left',
  },
  {
    key: 'sortingAreaName',
    prop: 'sortingAreaName',
    label: '分拣口',
    width: 100,
    align: 'center',
  },
  {
    key: 'sortingRemark',
    prop: 'sortingRemark',
    label: '分拣口说明',
    minWidth: 200,
    align: 'left',
  },
  {
    key: 'operation',
    label: '操作',
    width: 130,
    align: 'center',
    slot: 'operation',
  },
]
const searchForm = ref({
  sortingArea: null,
  sortingRemark: '',
})
const createDialogRef = ref<InstanceType<typeof CreateSortingRuleDialog>>()
const {
  loading,
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) =>
    getsortingConfigListApi(
      {
        ...searchForm.value,
      },
      page,
      pageSize,
    ).then((res) => res.data),
})
const logisticsMethodsList = ref<Ilogistics[]>([])
const getlogisticsMethods = async () => {
  const res = await allErpCodeListApi()
  logisticsMethodsList.value = res.data || []
  logisticsMethodsList.value = [
    ...logisticsMethodsList.value,
    {
      code: 'JOMALL_FACTORY',
      basicsName: '九猫统筹物流',
    },
  ]
}

interface SortingOption {
  label: string
  value: number
}
const sortingList = ref<SortingOption[]>([])
const getSortingList = async () => {
  const res = await getSortingPortAreaListApi()
  sortingList.value = (res.data || []).map((item) => ({
    label: item.desc,
    value: item.code,
  }))
}

const handleBatchDelete = async (row: IsortingInfo | null) => {
  if (!row?.id) {
    return ElMessage.warning('请选择要删除的数据')
  }
  await ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  await deleteSortingApi({ id: row.id })
  ElMessage.success('删除成功')
  search()
}
const createWarehouse = () => {
  createDialogRef.value?.open()
}
const updateSorting = (item: IsortingInfo) => {
  if (!item) return
  createDialogRef.value?.open(item)
}

onMounted(async () => {
  await Promise.all([getSortingList(), getlogisticsMethods()])
})

const searchFormRef = ref()
const searchBtnRef = ref()
useEnterKeyTrigger({
  formRef: searchFormRef,
  btnRef: searchBtnRef,
  callback: () => {
    search()
  },
})
</script>
<style scoped lang="scss">
.user-list {
  .table-container {
    height: 100%;
    overflow: hidden;
  }
}

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

  .right-table {
    flex: 1;
    margin-left: 10px;
    flex-shrink: 0;
  }

  .left-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;
    }
  }
}
</style>
