<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 #conditions="{ row }">
                <div class="conditions-text">
                  <div class="match-type">
                    {{
                      row.matchType === 1
                        ? '满足以下所有条件：'
                        : '满足以下任一条件：'
                    }}
                  </div>

                  <div
                    v-for="(item, index) in row.conditions || []"
                    :key="index"
                    class="condition-item"
                  >
                    <span
                      class="condition-text"
                      :title="formatConditionText(item)"
                    >
                      {{ index + 1 }}、 {{ formatConditionText(item) }}
                    </span>
                  </div>
                </div>
              </template>
              <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"
      :condition-type-list="conditionTypeList"
      :operator-list="operatorList"
      @success="search"
    />
  </div>
</template>
<script setup lang="ts">
import {
  Ilogistics,
  IsortingInfo,
  SortingPortCondition,
  SortingPortOptionItem,
} from '@/types/api/logistics'
import {
  getsortingConfigListApi,
  deleteSortingApi,
  getSortingPortAreaListApi,
  getSortPortConditionTypeListApi,
  getSortPortOperatorListApi,
} from '@/api/logistics'
import { allErpCodeListApi } from '@/api/podCnOrder'
import { onMounted, 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: 'conditions',
    prop: 'conditions',
    slot: 'conditions',
    label: '分拣口规则',
    minWidth: 250,
    align: 'left',
    showOverflowTooltip: false,
  },
  {
    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 conditionTypeList = ref<SortingPortOptionItem[]>([])
const operatorList = ref<SortingPortOptionItem[]>([])

const loadConditionTypeList = async () => {
  const res = await getSortPortConditionTypeListApi()
  if (res.code !== 200) return
  conditionTypeList.value = res.data
}

const loadOperatorList = async () => {
  const res = await getSortPortOperatorListApi()
  if (res.code !== 200) return
  operatorList.value = res.data
}

const formatConditionText = (item: SortingPortCondition) => {
  const typeDesc =
    conditionTypeList.value.find((r) => r.code === item.conditionType)?.desc ??
    item.conditionType
  const operatorDesc =
    operatorList.value.find((r) => r.code === item.operator)?.desc ??
    item.operator

  let valueText = ''
  switch (item.conditionType) {
    case 'order_platform':
      valueText = String(item.conditionValue ?? '')
        .split(',')
        .filter(Boolean)
        .join('、')
      break
    default:
      valueText = String(item.conditionValue ?? '')
        .split(',')
        .filter(Boolean)
        .map(
          (code) =>
            logisticsMethodsList.value.find((l) => l.code === code)
              ?.basicsName ?? code,
        )
        .join('、')
      break
  }
  return `${typeDesc}${operatorDesc} ${valueText}`
}

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(),
    loadConditionTypeList(),
    loadOperatorList(),
  ])
})

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%;
  }
}
.conditions-text {
  padding: 4px 0;
  line-height: 1.6;
  overflow: hidden;

  .match-type {
    color: #666;
    margin-bottom: 2px;
  }

  .condition-item {
    display: flex;
    align-items: center;
    color: #333;
    overflow: hidden;
    min-width: 0;

    .condition-text {
      flex: 1;
      min-width: 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .category-detail-btn {
      flex-shrink: 0;
      margin-left: 4px;
      padding: 0;
      height: auto;
    }
  }
}
.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>
