<template>
  <div
    v-loading="loading"
    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 class="table-container">
          <TableView :paginated-data="sortingList" :columns="columns">
            <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"
      @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,
  SortingList,
  SortingRuleDetail,
} from '@/types/api/order'
import type { CustomColumn } from '@/types/table'
import {
  getSortingRuleListApi,
  deleteAreaApi,
  getConfigApi,
  updateConfighApi,
  getAreaInfoApi,
} 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: 'conditionsText',
    prop: 'conditionsText',
    label: '配货规则',
    minWidth: 250,
    align: 'left',
  },
  {
    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 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: '',
})

// 加载仓库列表
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) => {
  loading.value = true
  await ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await deleteAreaApi(id)
    if (res.code !== 200) return
    ElMessage.success('删除成功')
    await getSortingRuleList()
  })
  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 () => {
  await loadWarehouseList()
  await getFunctionSwitch()
  await getSortingRuleList()
})
</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;
  }
}
</style>
