<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from "vue";
import { message } from "@/utils/message";
import {
  getLayerTemplateById,
  createLayerTemplate,
  updateLayerTemplate
} from "@/api/layer-template";
import type { FloorConfig, GoodsItem } from "@/api/layer-template";
import type { FormInstance, FormRules } from "element-plus";

/**
 * 表单数据类型
 */
interface FormData {
  /** 模板名称 */
  templateName: string;
  /** 设备类型: 1-静态柜(单门), 2-动态柜(双门) */
  deviceType: number;
  /** 模版类型: LAYER-层模版, CABINET-柜模版 */
  templateType: string;
  /** 设备层数 */
  shelfNum: number;
  /** 左门楼层配置 */
  leftFloors: FloorConfig[];
  /** 右门楼层配置 */
  rightFloors: FloorConfig[];
}

const emit = defineEmits<{
  (e: "success"): void;
}>();

// 对话框可见状态
const visible = ref(false);
// 对话框标题
const title = ref("新增设备模版");
// 是否为编辑模式
const isEdit = computed(() => title.value === "修改");
// 编辑时的记录ID
const editId = ref<number | null>(null);
// 编辑时的设备ID
const editDeviceId = ref<string>("");

// 表单引用
const formRef = ref<FormInstance>();
// 当前选中的层 Tab
const activeFloorTab = ref("left-1");
// 右门当前选中的层 Tab
const activeRightFloorTab = ref("right-1");

// 表单数据
const form = reactive<FormData>({
  templateName: "",
  deviceType: 1,
  templateType: "LAYER",
  shelfNum: 5,
  leftFloors: [],
  rightFloors: []
});

// 表单校验规则
const rules = computed<FormRules>(() => ({
  templateName: [
    {
      required: true,
      message: "请输入模板名称",
      trigger: "blur"
    },
    {
      min: 2,
      max: 50,
      message: "模板名称长度在2到50个字符之间",
      trigger: "blur"
    }
  ],
  shelfNum: [
    {
      required: true,
      message: "请输入设备层数",
      trigger: "blur"
    }
  ]
}));

/**
 * 是否为双门柜
 */
const isDoubleDoor = computed(() => form.deviceType === 2);

/**
 * 重置表单数据
 */
function resetForm() {
  form.templateName = "";
  form.deviceType = 1;
  form.templateType = "LAYER";
  form.shelfNum = 5;
  form.leftFloors = [];
  form.rightFloors = [];
  editId.value = null;
  editDeviceId.value = "";
  activeFloorTab.value = "left-1";
  activeRightFloorTab.value = "right-1";
  nextTick(() => {
    formRef.value?.clearValidate();
  });
}

/**
 * 根据 shelfNum 初始化层数据
 * 当用户修改层数时，自动调整层数据
 */
function initFloorsByShelfNum() {
  const num = form.shelfNum || 0;

  // 调整左门层数
  while (form.leftFloors.length < num) {
    form.leftFloors.push({
      floor: form.leftFloors.length + 1,
      goods: []
    });
  }
  while (form.leftFloors.length > num) {
    form.leftFloors.pop();
  }

  // 调整右门层数
  if (isDoubleDoor.value) {
    while (form.rightFloors.length < num) {
      form.rightFloors.push({
        floor: form.rightFloors.length + 1,
        goods: []
      });
    }
    while (form.rightFloors.length > num) {
      form.rightFloors.pop();
    }
  } else {
    form.rightFloors = [];
  }

  // 更新默认 Tab
  if (form.leftFloors.length > 0) {
    activeFloorTab.value = `left-${form.leftFloors[0].floor}`;
  }
  if (form.rightFloors.length > 0) {
    activeRightFloorTab.value = `right-${form.rightFloors[0].floor}`;
  }
}

/**
 * 监听 shelfNum 变化，自动调整层数据
 */
watch(
  () => form.shelfNum,
  () => {
    if (form.shelfNum > 0 && form.shelfNum <= 20) {
      initFloorsByShelfNum();
    }
  }
);

/**
 * 监听设备类型变化
 */
watch(
  () => form.deviceType,
  () => {
    initFloorsByShelfNum();
  }
);

/**
 * 打开对话框
 */
async function open(dialogTitle?: string, row?: any) {
  title.value = dialogTitle || "新增设备模版";
  resetForm();
  visible.value = true;

  // 如果是编辑模式,回显数据
  if (row && row.id) {
    editId.value = row.id;
    editDeviceId.value = row.deviceId || "";
    await loadTemplateData(row.id);
  } else {
    // 新增模式，初始化默认层数据
    initFloorsByShelfNum();
  }
}

/**
 * 加载模版详情数据
 */
async function loadTemplateData(id: number) {
  try {
    const res = await getLayerTemplateById(id);
    const data = res.data;
    if (data) {
      form.templateName = data.templateName || "";
      form.deviceType = data.deviceType || 1;
      form.templateType = data.templateType || "LAYER";
      form.shelfNum = data.shelfNum || 5;

      // 解析左门层数据（JSON字符串 -> FloorConfig数组）
      if (data.leftFloors) {
        try {
          const parsed = typeof data.leftFloors === "string"
            ? JSON.parse(data.leftFloors)
            : data.leftFloors;
          if (Array.isArray(parsed)) {
            form.leftFloors = parsed.map((item: any) => ({
              floor: typeof item.floor === "string" ? parseInt(item.floor, 10) : (item.floor || 0),
              goods: Array.isArray(item.goods) ? item.goods : []
            }));
          }
        } catch (e) {
          console.error("解析左门层数据失败:", e);
          form.leftFloors = [];
        }
      }

      // 解析右门层数据
      if (data.rightFloors) {
        try {
          const parsed = typeof data.rightFloors === "string"
            ? JSON.parse(data.rightFloors)
            : data.rightFloors;
          if (Array.isArray(parsed)) {
            form.rightFloors = parsed.map((item: any) => ({
              floor: typeof item.floor === "string" ? parseInt(item.floor, 10) : (item.floor || 0),
              goods: Array.isArray(item.goods) ? item.goods : []
            }));
          }
        } catch (e) {
          console.error("解析右门层数据失败:", e);
          form.rightFloors = [];
        }
      }

      // 如果没有层数据但有 shelfNum，则初始化空层
      if (form.leftFloors.length === 0 && form.shelfNum > 0) {
        initFloorsByShelfNum();
      }

      // 设置默认 Tab
      if (form.leftFloors.length > 0) {
        activeFloorTab.value = `left-${form.leftFloors[0].floor}`;
      }
      if (form.rightFloors.length > 0) {
        activeRightFloorTab.value = `right-${form.rightFloors[0].floor}`;
      }
    }
  } catch (error) {
    console.error("加载模版数据失败:", error);
    message("加载模版数据失败", { type: "error" });
  }
}

/**
 * 删除某层中的商品
 */
function removeGoods(floorList: FloorConfig[], floorIndex: number, goodsIndex: number) {
  floorList[floorIndex].goods?.splice(goodsIndex, 1);
}

/**
 * 添加商品到某层（弹出输入框填写商品信息）
 */
function addGoods(floorList: FloorConfig[], floorIndex: number) {
  const floor = floorList[floorIndex];
  if (!floor.goods) {
    floor.goods = [];
  }
  floor.goods.push({
    key: "",
    label: "",
    stock: 0,
    c_price: "",
    pic: "",
    type: ""
  });
}

/**
 * 构造提交数据格式（匹配哈哈平台 postLayerTypeInfo 接口格式）
 */
function buildSubmitData() {
  // 构造哈哈平台所需的 products 结构
  const products: Record<string, any> = {};

  // 左门层数据
  products.left = form.leftFloors.map(f => ({
    floor: f.floor,
    goods: (f.goods || []).map(g => g.key).filter(k => k && k.trim() !== "")
  }));

  // 右门层数据（双门柜才有）
  if (isDoubleDoor.value && form.rightFloors.length > 0) {
    products.right = form.rightFloors.map(f => ({
      floor: f.floor,
      goods: (f.goods || []).map(g => g.key).filter(k => k && k.trim() !== "")
    }));
  }

  return {
    deviceId: editDeviceId.value,
    templateName: form.templateName.trim(),
    deviceType: form.deviceType,
    templateType: form.templateType,
    shelfNum: form.shelfNum,
    leftFloors: form.leftFloors,
    rightFloors: isDoubleDoor.value ? form.rightFloors : [],
    // 保存完整的 products JSON（用于推送到哈哈平台）
    productsJson: JSON.stringify(products)
  };
}

/**
 * 提交表单
 */
async function handleSubmit() {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    // 至少需要一层配置
    if (form.leftFloors.length === 0) {
      message("请至少配置一个楼层", { type: "warning" });
      return;
    }

    const submitData = buildSubmitData();
    let res;

    if (isEdit.value && editId.value) {
      res = await updateLayerTemplate(editId.value, submitData);
    } else {
      res = await createLayerTemplate(submitData);
    }

    if (res.code === 200 || res.code === 0) {
      message(
        `${isEdit.value ? "修改" : "新增"}设备模版成功`,
        { type: "success" }
      );
      visible.value = false;
      emit("success");
    } else {
      message(res.message || "操作失败", { type: "error" });
    }
  } catch (error: any) {
    if (error !== false) {
      console.error("提交表单失败:", error);
      message("提交失败，请检查输入", { type: "error" });
    }
  }
}

/**
 * 关闭对话框
 */
function handleClose() {
  visible.value = false;
  resetForm();
}

// 暴露方法给父组件调用
defineExpose({
  open
});
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="900px"
    destroy-on-close
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="template-form"
    >
      <!-- 基本信息 -->
      <el-divider content-position="left">基本信息</el-divider>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="模板名称" prop="templateName">
            <el-input
              v-model="form.templateName"
              placeholder="请输入模板名称"
              clearable
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备层数" prop="shelfNum">
            <el-input-number
              v-model="form.shelfNum"
              :min="1"
              :max="20"
              :step="1"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备类型">
            <el-radio-group v-model="form.deviceType">
              <el-radio :value="1">单门柜</el-radio>
              <el-radio :value="2">双门柜</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模版类型">
            <el-radio-group v-model="form.templateType">
              <el-radio value="LAYER">层模版</el-radio>
              <el-radio value="CABINET">柜模版</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 商品模板 - 左门 -->
      <el-divider content-position="left">
        商品模板 {{ isDoubleDoor ? "- 左门" : "" }}
      </el-divider>

      <el-tabs v-model="activeFloorTab" type="border-card">
        <el-tab-pane
          v-for="(floor, fIndex) in form.leftFloors"
          :key="'left-' + floor.floor"
          :label="'第' + floor.floor + '层'"
          :name="'left-' + floor.floor"
        >
          <div class="floor-toolbar">
            <el-button
              type="primary"
              size="small"
              plain
              @click="addGoods(form.leftFloors, fIndex)"
            >
              + 添加商品
            </el-button>
          </div>
          <el-table
            :data="floor.goods || []"
            border
            size="small"
            style="width: 100%"
            empty-text="暂无商品，请点击添加商品"
          >
            <el-table-column label="商品图片" width="80" align="center">
              <template #default="{ row }">
                <el-image
                  v-if="row.pic"
                  :src="row.pic"
                  :preview-src-list="[row.pic]"
                  fit="cover"
                  style="width: 50px; height: 50px; border-radius: 4px"
                  preview-teleported
                />
                <span v-else class="text-gray-400 text-xs">无图片</span>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" min-width="160">
              <template #default="{ row }">
                <el-input
                  v-if="!row.label || row._editing"
                  v-model="row.label"
                  size="small"
                  placeholder="请输入商品名称"
                />
                <span v-else>{{ row.label }}</span>
              </template>
            </el-table-column>
            <el-table-column label="商品编码" min-width="120">
              <template #default="{ row }">
                <el-input
                  v-if="!row.key || row._editing"
                  v-model="row.key"
                  size="small"
                  placeholder="商品code"
                />
                <span v-else class="text-gray-500">{{ row.key }}</span>
              </template>
            </el-table-column>
            <el-table-column label="商品售价" width="100" align="right">
              <template #default="{ row }">
                <span>{{ row.c_price || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="优惠价" width="120">
              <template #default="{ row }">
                <el-input
                  v-model="row.dis_price"
                  size="small"
                  placeholder="优惠价"
                  clearable
                  style="width: 90px"
                />
              </template>
            </el-table-column>
            <el-table-column label="标准库存" width="100">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.stock"
                  size="small"
                  :min="0"
                  :max="9999"
                  controls-position="right"
                  style="width: 80px"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center" fixed="right">
              <template #default="{ $index }">
                <el-button
                  type="danger"
                  size="small"
                  link
                  @click="removeGoods(form.leftFloors, fIndex, $index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 商品模板 - 右门（仅双门柜显示） -->
      <template v-if="isDoubleDoor">
        <el-divider content-position="left">商品模板 - 右门</el-divider>

        <el-tabs v-model="activeRightFloorTab" type="border-card">
          <el-tab-pane
            v-for="(floor, fIndex) in form.rightFloors"
            :key="'right-' + floor.floor"
            :label="'第' + floor.floor + '层'"
            :name="'right-' + floor.floor"
          >
            <div class="floor-toolbar">
              <el-button
                type="primary"
                size="small"
                plain
                @click="addGoods(form.rightFloors, fIndex)"
              >
                + 添加商品
              </el-button>
            </div>
            <el-table
              :data="floor.goods || []"
              border
              size="small"
              style="width: 100%"
              empty-text="暂无商品，请点击添加商品"
            >
              <el-table-column label="商品图片" width="80" align="center">
                <template #default="{ row }">
                  <el-image
                    v-if="row.pic"
                    :src="row.pic"
                    :preview-src-list="[row.pic]"
                    fit="cover"
                    style="width: 50px; height: 50px; border-radius: 4px"
                    preview-teleported
                  />
                  <span v-else class="text-gray-400 text-xs">无图片</span>
                </template>
              </el-table-column>
              <el-table-column label="商品名称" min-width="160">
                <template #default="{ row }">
                  <el-input
                    v-if="!row.label || row._editing"
                    v-model="row.label"
                    size="small"
                    placeholder="请输入商品名称"
                  />
                  <span v-else>{{ row.label }}</span>
                </template>
              </el-table-column>
              <el-table-column label="商品编码" min-width="120">
                <template #default="{ row }">
                  <el-input
                    v-if="!row.key || row._editing"
                    v-model="row.key"
                    size="small"
                    placeholder="商品code"
                  />
                  <span v-else class="text-gray-500">{{ row.key }}</span>
                </template>
              </el-table-column>
              <el-table-column label="商品售价" width="100" align="right">
                <template #default="{ row }">
                  <span>{{ row.c_price || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="优惠价" width="120">
                <template #default="{ row }">
                  <el-input
                    v-model="row.dis_price"
                    size="small"
                    placeholder="优惠价"
                    clearable
                    style="width: 90px"
                  />
                </template>
              </el-table-column>
              <el-table-column label="标准库存" width="100">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.stock"
                    size="small"
                    :min="0"
                    :max="9999"
                    controls-position="right"
                    style="width: 80px"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" align="center" fixed="right">
                <template #default="{ $index }">
                  <el-button
                    type="danger"
                    size="small"
                    link
                    @click="removeGoods(form.rightFloors, fIndex, $index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>

      <!-- 适用设备信息（仅编辑模式显示） -->
      <template v-if="isEdit && editDeviceId">
        <el-divider content-position="left">适用设备</el-divider>
        <div class="device-info">
          <el-tag type="info" size="large">
            设备ID: {{ editDeviceId }}
          </el-tag>
        </div>
      </template>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.template-form {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;

  .floor-toolbar {
    margin-bottom: 12px;
    display: flex;
    justify-content: flex-end;
  }

  .device-info {
    display: flex;
    gap: 8px;
    align-items: center;
    flex-wrap: wrap;
  }

  :deep(.el-divider__text) {
    font-size: 15px;
    font-weight: 600;
    color: var(--el-color-primary);
  }

  :deep(.el-tabs__item) {
    font-size: 13px;
  }

  :deep(.el-table) {
    font-size: 13px;
  }

  :deep(.el-image) {
    cursor: pointer;
  }
}
</style>
