<template>
  <ElDialog
    v-model="dialogVisible"
    :title="editForm.id ? '编辑共享库存组' : '新增共享库存组'"
    width="800px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <ElForm ref="editFormRef" :model="editForm" label-width="100px">
      <div class="section-title">分组基础信息</div>
      <ElFormItem
        label="库存组名称"
        prop="warehouseGroupName"
        :rules="[
          { required: true, message: '请输入库存组名称', trigger: 'blur' },
        ]"
      >
        <ElInput
          v-model="editForm.warehouseGroupName"
          clearable
          placeholder="请输入库存组名称"
          style="width: 100%"
        />
      </ElFormItem>
      <ElFormItem
        label="状态"
        prop="status"
        :rules="[{ required: true, message: '请选择状态', trigger: 'blur' }]"
      >
        <ElSwitch
          v-model="editForm.status"
          :active-value="1"
          :inactive-value="0"
          style="--el-switch-on-color: #42b983"
        />
      </ElFormItem>

      <div class="section-title">组内SPU清单</div>
      <div class="spu-search-bar">
        <ElInput
          v-model="spuSearchKeyword"
          clearable
          placeholder="请输入库存SPU"
          style="width: 200px"
          @keyup.enter="handleSearchSpu"
        />
        <ElButton type="primary" @click="handleSearchSpu">查询</ElButton>
      </div>
      <div class="spu-drag-tip">
        <el-icon style="color: #409eff; font-size: 16px"><Warning /></el-icon
        ><span>拖动SPU调整扣减顺序</span>
      </div>
      <div class="spu-table-wrapper">
        <TableView
          :paginated-data="editForm.spuList ?? []"
          :columns="spuTableColumns"
          row-key="warehouseSpu"
          size="small"
        >
          <template #sortNo="{ row, index }">
            <span
              class="drag-handle"
              draggable="true"
              @dragstart="handleDragStart(index)"
              @dragover.prevent
              @drop="handleDrop(index)"
            >
              {{ row.sortNo }}
            </span>
          </template>
          <template #spuImage="{ row }">
            <ImageView :src="row.spuImage" width="40px" height="40px" />
          </template>
          <template #operation="{ index }">
            <ElButton link type="danger" @click="handleRemoveSpu(index)">
              删除
            </ElButton>
          </template>
        </TableView>
      </div>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="handleCancel">取消</ElButton>
        <ElButton type="primary" :loading="saving" @click="handleSave">
          保存
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>
<script setup lang="ts">
import ImageView from '@/components/ImageView.vue'
import TableView from '@/components/TableView.vue'
import {
  EditForm,
  WarehouseRuleSpuItem,
} from '@/types/api/warehouse/warehouseRuleSetting'
import { Warning } from '@element-plus/icons-vue'
import { useWarehouseRuleSettingTableColumns } from '../hooks/useWarehouseRuleSettingTableColumns'

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'saved'): void
}>()
const props = defineProps<{
  visible: boolean
}>()
const dialogVisible = computed({
  get() {
    return props.visible
  },
  set(value: boolean) {
    emit('update:visible', value)
  },
})

const createDefaultForm = (): EditForm => ({
  id: undefined,
  warehouseGroupName: '',
  status: 1,
  spuList: [],
})

const editForm = ref<EditForm>(createDefaultForm())
const editFormRef = ref()
const spuSearchKeyword = ref('')
const saving = ref(false)
const dragIndex = ref<number | null>(null)

const { spuTableColumns } = useWarehouseRuleSettingTableColumns()
const resetFields = () => {
  editForm.value = createDefaultForm()
  spuSearchKeyword.value = ''
  dragIndex.value = null
  nextTick(() => {
    editFormRef.value?.clearValidate()
  })
}

const updateSortNo = (list: WarehouseRuleSpuItem[]) => {
  return list.map((item, index) => ({
    ...item,
    sortNo: index + 1,
  }))
}

const handleDragStart = (index: number) => {
  dragIndex.value = index
}

const handleDrop = (index: number) => {
  if (dragIndex.value === null || dragIndex.value === index) {
    return
  }
  const list = [...(editForm.value.spuList ?? [])]
  const [movedItem] = list.splice(dragIndex.value, 1)
  list.splice(index, 0, movedItem)
  editForm.value.spuList = updateSortNo(list)
  dragIndex.value = null
}

const handleSearchSpu = () => {
  // TODO: 调用接口查询库存SPU并添加到列表
}

const handleRemoveSpu = (index: number) => {
  const list = [...(editForm.value.spuList ?? [])]
  list.splice(index, 1)
  editForm.value.spuList = updateSortNo(list)
}

const handleCancel = () => {
  dialogVisible.value = false
}

const handleSave = async () => {
  const valid = await editFormRef.value?.validate().catch(() => false)
  if (!valid) {
    return
  }
  saving.value = true
  try {
    // TODO: 调用保存接口
    emit('saved')
    dialogVisible.value = false
  } finally {
    saving.value = false
  }
}

defineExpose({
  resetFields,
})
</script>
<style scoped lang="scss">
.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-left: 8px;
  border-left: 3px solid #409eff;

  & + .el-form-item {
    margin-top: 0;
  }

  &:not(:first-child) {
    margin-top: 8px;
  }
}

.spu-search-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.spu-drag-tip {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.spu-table-wrapper {
  height: 280px;
}

.drag-handle {
  display: inline-block;
  width: 100%;
  cursor: move;
  user-select: none;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style>
