<template>
  <div class="page card h-100 flex-gap-10 overflow-hidden flex">
    <div class="search-form flex flex-column w-100 flex-1 overflow-hidden">
      <el-form :model="searchForm" inline>
        <el-form-item label="仓库">
          <el-select
            v-model="searchForm.warehouseId"
            placeholder="请选择仓库"
            style="width: 180px"
            filterable
            @change="handleWarehouseChange"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <ElFormItem>
          <ElButton type="primary" @click="() => search()"> 查询 </ElButton>
        </ElFormItem>
      </el-form>
      <div class="picking-sort-info flex flex-align-center">
        <el-switch
          v-model="isEnableSorting"
          size="large"
          class="mr-10"
          :before-change="updateConfig"
        />
        <div class="text-xs">配货分拣</div>
        <el-divider direction="vertical" />

        <div v-if="!isEnableSorting" class="info">
          关闭时，直接使用配货打单功能配货
        </div>
        <div v-else class="info">
          开启时，支持设置分拣规则，根据分拣规则分配配货区，使用配货分拣功能配货。
        </div>
      </div>
      <div v-if="isEnableSorting" class="sorting-content mt-10 w-100">
        <el-button type="success" @click="addArea()">新增</el-button>
        <div
          v-loading="loading"
          element-loading-text="加载中..."
          class="table-container"
        >
          <TableView :paginated-data="sortingList" :columns="columns">
            <template #conditions="{ row }">
              <div v-if="row.areaCode === 'AREA_0'">默认分拣口</div>
              <div v-else 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>
                  <el-popover
                    v-if="item.conditionType === 'order_category'"
                    placement="bottom"
                    :width="'auto'"
                    trigger="click"
                  >
                    <el-cascader-panel
                      class="category-cascader-panel-readonly"
                      :model-value="getCategoryCascaderValue(item)"
                      :options="categoryList"
                      :props="{
                        label: 'name',
                        value: 'id',
                        children: 'children',
                        multiple: true,
                        emitPath: true,
                        checkOnClickNode: false,
                        checkOnClickLeaf: false,
                        showPrefix: false,
                      }"
                    />
                    <template #reference>
                      <el-button
                        type="primary"
                        link
                        class="category-detail-btn"
                      >
                        详情
                      </el-button>
                    </template>
                  </el-popover>
                </div>
              </div>
            </template>
            <template #autoPrint="{ row }">
              {{ row.autoPrint ? '开启' : '关闭' }}
            </template>
            <template #operation="{ row }">
              <el-button type="primary" link @click="addArea(row)">
                编辑
              </el-button>
              <el-button
                v-if="row.areaCode !== 'AREA_0'"
                type="danger"
                link
                @click="deleteArea(row.id)"
              >
                删除
              </el-button>
              <!-- <el-button type="success" link @click="viewLog(row.id)">
                查看日志
              </el-button> -->
            </template>
          </TableView>
        </div>
      </div>
    </div>
    <AddAreaDialog
      v-if="addAreaDialogVisible"
      v-model="addAreaDialogVisible"
      :is-edit="isEdit"
      :is-disabled="isDisabled"
      :edit-data="editData"
      :warehouse-id="searchForm.warehouseId"
      :warehouse-name="searchForm.warehouseName"
      :category-list="categoryList"
      :picking-rule-list="pickingRuleList"
      :operator-list="operatorList"
      @submit="getSortingRuleList"
    />
    <el-dialog
      v-model="logVisible"
      title="操作日志"
      width="1000px"
      :close-on-click-modal="false"
    >
      <LogList :log-list="logList" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { loadWarehouseListApi } from '@/api/common'
import type { WarehouseListData } from '@/types'
import type {
  LogListData,
  OperatorList,
  SortingList,
  SortingRuleCondition,
  SortingRuleDetail,
} from '@/types/api/order'
import type { CustomColumn } from '@/types/table'
import {
  getSortingRuleListApi,
  deleteAreaApi,
  getConfigApi,
  updateConfighApi,
  getAreaInfoApi,
  getCategoryListApi,
  getConditionTypeListApi,
  getOperatorListApi,
} from '@/api/order'
import TableView from '@/components/TableView.vue'
import LogList from '@/components/LogList.vue'
import AddAreaDialog from './components/addDialog.vue'

const columns: CustomColumn<SortingList>[] = [
  {
    key: 'sortNo',
    prop: 'sortNo',
    label: '序号',
    width: 80,
    align: 'center',
  },
  {
    key: 'id',
    prop: 'id',
    label: '配货区ID',
    width: 120,
    align: 'center',
  },
  {
    key: 'conditions',
    prop: 'conditions',
    label: '配货规则',
    minWidth: 250,
    align: 'left',
    slot: 'conditions',
    showOverflowTooltip: false,
  },
  {
    key: 'areaName',
    prop: 'areaName',
    label: '配货区',
    width: 100,
    align: 'center',
  },
  {
    key: 'areaDesc',
    prop: 'areaDesc',
    label: '配货区说明',
    minWidth: 200,
    align: 'left',
  },
  {
    key: 'autoPrint',
    prop: 'autoPrint',
    label: '自动打单',
    width: 100,
    align: 'center',
    slot: 'autoPrint',
  },
  {
    key: 'warehouseName',
    prop: 'warehouseName',
    label: '仓库',
    width: 180,
    align: 'center',
  },
  {
    key: 'operation',
    label: '操作',
    width: 140,
    align: 'center',
    slot: 'operation',
  },
]

const warehouseList = ref<WarehouseListData[]>([]) // 仓库列表
const sortingList = ref<SortingList[]>([]) // 规则列表
const categoryList = ref<OperatorList[]>([]) // 商品类目
const pickingRuleList = ref<OperatorList[]>([]) // 配货规则条件
const operatorList = ref<OperatorList[]>([]) // 配货规则操作符
const isEnableSorting = ref(false) // 是否开启配货分拣
const currentId = ref(0) // 当前操作id
const isEdit = ref(false) // 是否编辑
const isDisabled = ref(false) // 是否可编辑 (0号配货区禁止编辑)
const editData = ref<SortingRuleDetail>()
const addAreaDialogVisible = ref(false)
const logVisible = ref(false)
const logList = ref<LogListData[]>([])
const loading = ref(false)
const searchForm = ref({
  warehouseId: 0,
  warehouseName: '',
})

type CategoryNode = OperatorList & {
  id?: number | string
  name?: string
  children?: CategoryNode[]
}

// 获取节点下全部叶子 id
const getCategoryLeafIds = (node: CategoryNode): string[] => {
  if (!node.children?.length) return node.id != null ? [String(node.id)] : []
  return node.children.flatMap(getCategoryLeafIds)
}

// 格式化已选类目：某项下所有子项都被选中时，只展示该项路径
const formatSelectedCategories = (
  list: CategoryNode[],
  selectedIds: Set<string>,
  path: string[] = [],
): string[] => {
  const result: string[] = []
  for (const item of list) {
    const currentPath = [...path, item.name ?? '']
    const leafIds = getCategoryLeafIds(item)
    const allSelected =
      leafIds.length > 0 && leafIds.every((id) => selectedIds.has(id))

    if (allSelected) {
      result.push(currentPath.join('->'))
      continue
    }
    if (item.children?.length) {
      result.push(
        ...formatSelectedCategories(item.children, selectedIds, currentPath),
      )
    } else if (item.id != null && selectedIds.has(String(item.id))) {
      result.push(currentPath.join('->'))
    }
  }
  return result
}

// 根据叶子 id 查找类目完整路径（用于级联回显）
const findCategoryPath = (
  list: CategoryNode[],
  targetId: string | number,
  path: (string | number)[] = [],
): (string | number)[] | null => {
  for (const item of list) {
    if (item.id == null) continue
    const currentPath = [...path, item.id]
    if (String(item.id) === String(targetId)) return currentPath
    if (item.children?.length) {
      const found = findCategoryPath(item.children, targetId, currentPath)
      if (found) return found
    }
  }
  return null
}

// 将条件值转为级联回显路径
const getCategoryCascaderValue = (item: SortingRuleCondition) => {
  const ids = String(item.conditionValue ?? '')
    .split(',')
    .filter(Boolean)
  return ids
    .map((id) => {
      const num = Number(id)
      return findCategoryPath(
        categoryList.value as CategoryNode[],
        Number.isNaN(num) ? id : num,
      )
    })
    .filter((path): path is (string | number)[] => !!path)
}

// 配货规则展示文案
const formatConditionText = (item: SortingRuleCondition) => {
  // 配货规则条件
  const typeDesc =
    pickingRuleList.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_category': {
      const selectedIds = new Set(
        String(item.conditionValue ?? '')
          .split(',')
          .filter(Boolean),
      )
      valueText = formatSelectedCategories(
        categoryList.value as CategoryNode[],
        selectedIds,
      ).join('、')
      break
    }
    case 'order_platform':
      valueText = String(item.conditionValue ?? '')
        .split(',')
        .filter(Boolean)
        .join('、')
      break
    default:
      valueText = String(item.conditionValue ?? '')
      break
  }
  return `${typeDesc}${operatorDesc} ${valueText}`
}

// 获取商品类目
const getCategoryList = async () => {
  const res = await getCategoryListApi()
  if (res.code !== 200) return
  categoryList.value = res.data
}

// 获取配货规则条件
const getConditionTypeList = async () => {
  const res = await getConditionTypeListApi()
  if (res.code !== 200) return
  pickingRuleList.value = res.data
}

// 获取配货规则操作符
const getOperatorList = async () => {
  const res = await getOperatorListApi()
  if (res.code !== 200) return
  operatorList.value = res.data
}

// 加载仓库列表
const loadWarehouseList = async () => {
  try {
    const res = await loadWarehouseListApi()
    if (res.code !== 200) return
    warehouseList.value = res.data || []
    // 默认选中默认仓库
    searchForm.value.warehouseId =
      warehouseList.value.find((item) => item.defaulted === 1)?.id ?? 0
  } catch (e) {
    console.error(e)
  }
}

const handleWarehouseChange = (warehouseId: number) => {
  searchForm.value.warehouseId = warehouseId
  if (!isEnableSorting.value) return
  getSortingRuleList()
}

const search = () => {
  getSortingRuleList()
}

// 获取功能开关
const getFunctionSwitch = async () => {
  const res = await getConfigApi()
  if (res.code !== 200) return
  isEnableSorting.value = res.data.enable
  currentId.value = res.data.id
}

// 切换功能
const updateConfig = async () => {
  try {
    ElMessageBox.confirm('是否确定切换功能？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const res = await updateConfighApi({
        id: currentId.value,
        enable: !isEnableSorting.value,
      })
      if (res.code !== 200) return
      isEnableSorting.value = !isEnableSorting.value
      await getSortingRuleList()
    })
  } catch (e) {
    console.error(e)
  }
}

// 查询列表
const getSortingRuleList = async () => {
  loading.value = true
  const res = await getSortingRuleListApi({
    warehouseId: searchForm.value.warehouseId,
  })
  if (res.code !== 200) return
  sortingList.value = res.data.records
  loading.value = false
}

// 新增/编辑
const addArea = async (row?: SortingList) => {
  searchForm.value.warehouseName =
    warehouseList.value.find((item) => item.id === searchForm.value.warehouseId)
      ?.name ?? ''
  if (row) {
    isEdit.value = true
    isDisabled.value = row.areaCode === 'AREA_0'
    const res = await getAreaInfoApi(row.id)
    if (res.code !== 200) return
    editData.value = res.data
  } else {
    isDisabled.value = false
    isEdit.value = false
    editData.value = undefined
  }

  addAreaDialogVisible.value = true
}

// 删除配货区
const deleteArea = async (id: number) => {
  await ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      loading.value = true
      const res = await deleteAreaApi(id)
      if (res.code !== 200) return
      ElMessage.success('删除成功')
      await getSortingRuleList()
    })
    .finally(() => {
      loading.value = false
    })
}

// 查看日志
// const viewLog = async (id: number) => {
//   try {
//     const res = await getSortingLogApi(id)
//     logList.value = res.data
//     logVisible.value = true
//   } catch (e) {
//     console.error(e)
//   }
// }

onMounted(async () => {
  loading.value = true
  await Promise.all([
    loadWarehouseList(),
    getFunctionSwitch(),
    getCategoryList(),
    getConditionTypeList(),
    getOperatorList(),
  ])
  await getSortingRuleList()
  loading.value = false
})
</script>

<style scoped lang="scss">
.search-form {
  min-height: 0;
}

.picking-sort-info {
  font-size: 14px;
  color: #555;
  font-weight: 500;
  .info {
    font-size: 12px;
    color: #999;
  }
}

.sorting-content {
  flex: 1;
  min-height: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  align-items: flex-start;

  .table-container {
    width: 100%;
    flex: 1;
    min-height: 0;
    overflow: hidden;
    margin-top: 10px;
  }
}

.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;
    }
  }
}
</style>
<style lang="scss">
// 详情面板只读：可展开，禁止勾选
.category-cascader-panel-readonly {
  .el-checkbox {
    pointer-events: none;
  }
}
</style>
