<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { updateCabinetCell, clearGoodsCells, resetCellById } from "@/api/cabinet/cabinet-cell";
import Confirm from "@iconify-icons/ep/check";
import type { FormRules } from 'element-plus';

export interface FormDTO {
  cellId?: number;
  cabinetId: number;
  mainboardId: number;
  cellNo: number;
  pinNo: number;
  cellType: number;
  availableStatus: number;
  usageStatus: number;
  stock: number;
  cellPrice?: number;
  password?: string;
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  row: {
    type: Object,
    default: null
  },
  mode: {
    type: Number,
    default: null
  }
});

const emit = defineEmits(["update:modelValue", "refresh"]);

const formRef = ref();
const formData = reactive<FormDTO>({
  cabinetId: null,
  mainboardId: null,
  cellNo: null,
  pinNo: null,
  cellType: 1,
  availableStatus: 1,
  usageStatus: 1,
  stock: 0,
  cellPrice: 0,
  password: ''
});

const rules = reactive<FormRules>({
  cabinetId: [
    { required: true, message: "柜体ID必填", trigger: "blur" },
    { type: 'number', message: '必须为数字类型' }
  ],
  mainboardId: [
    { required: true, message: "主板ID必填", trigger: "blur" },
    { type: 'number', message: '必须为数字类型' }
  ],
  cellNo: [
    { required: true, message: "单元格号必填", trigger: "blur" },
    { type: 'number', message: '必须为数字类型' }
  ],
  pinNo: [
    { required: true, message: "针脚号必填", trigger: "blur" },
    { type: 'number', message: '必须为数字类型' }
  ],
  cellType: [
    { required: true, message: "请选择单元格类型", trigger: "change" }
  ],
  availableStatus: [
    { required: true, message: "请选择可用状态", trigger: "change" }
  ],
  usageStatus: [
    { required: true, message: "请选择使用状态", trigger: "change" }
  ]
});

const handleConfirm = async () => {
  try {
    await formRef.value.validate();
    await updateCabinetCell(formData.cellId!, formData);
    ElMessage.success("修改成功");
    emit("refresh");
    closeDialog();
  } catch (error) {
    console.error("表单提交失败", error);
  }
};

const closeDialog = () => {
  formRef.value.resetFields();
  emit('update:modelValue', false);
};

const handleResetPassword = async () => {
  try {
    await resetCellById(props.row.cellId);
    formData.password = '';
    ElMessage.success('密码已重置');
    emit("refresh");
  } catch (error) {
    console.error('重置密码失败', error);
  }
};

async function handleClearGoods() {
  try {
    await ElMessageBox.confirm(
      `确认要下架${props.row.goodsName}吗？`,
      '警告',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    );
    await clearGoodsCells(props.row.cellId);
    ElMessage.success('商品下架成功');
    emit('refresh');
    closeDialog();
  } catch (error) {
    console.error('操作取消或失败', error);
  }
}

watch(() => props.row, (val) => {
  if (val) {
    Object.assign(formData, val);
  }
}, { immediate: true });
</script>

<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
    <el-form-item label="主板ID" prop="mainboardId">
      <el-input v-model.number="formData.mainboardId" placeholder="请输入主板ID" />
    </el-form-item>

    <el-form-item label="针脚号" prop="pinNo">
      <el-input v-model.number="formData.pinNo" placeholder="请输入针脚号" />
    </el-form-item>

    <el-form-item label="单元格类型" prop="cellType">
      <el-select v-model="formData.cellType" placeholder="请选择类型">
        <el-option label="小格" :value="1" />
        <el-option label="中格" :value="2" />
        <el-option label="大格" :value="3" />
        <el-option label="超大格" :value="4" />
      </el-select>
    </el-form-item>
    <el-form-item v-if="props.mode == 3" label="格口价格" class="price-input-item">
      <el-input v-model="formData.cellPrice" placeholder="请输入格口价格" style="width: 120px; margin-right: 10px;" />
      元
    </el-form-item>
    <el-form-item v-if="props.mode == 5" label="密码" prop="password">
      <el-input v-model="formData.password" placeholder="请输入密码（可选）" style="width: 200px;" />
      <el-button @click="handleResetPassword" type="text" size="small" style="margin-left: 10px;">
        清空
      </el-button>
    </el-form-item>

    <el-form-item v-if="props.row.goodsId" label="商品ID">
      <el-input :model-value="props.row.goodsId" disabled />
    </el-form-item>
    <el-form-item v-if="props.row.goodsId" label="商品名称">
      <el-input :model-value="props.row.goodsName" disabled />
    </el-form-item>
    <el-form-item v-if="props.row.goodsId" label="商品图片">
      <el-image :src="props.row.coverImg" style="width: 100px; height: 100px" fit="contain" />
    </el-form-item>
    <el-form-item v-if="props.row.goodsId" label="价格">
      <el-input :model-value="props.row.price" disabled />
    </el-form-item>
    <el-form-item v-if="props.row.goodsId" label="库存" prop="stock">
      <el-input-number v-model="formData.stock" :min="0" :max="1000" class="stock-input" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleConfirm" class="save-btn">
        保存修改
      </el-button>
      <el-button v-if="props.row.goodsId" type="danger" @click="handleClearGoods" class="clear-btn">
        下架商品
      </el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.save-btn,
.clear-btn {
  margin-right: 10px;
}

.price-input-item .el-input__wrapper {
  border-radius: 6px;
  border-color: #dcdfe6;
  box-shadow: 0 0 0 0 rgba(144, 147, 153, 0);
  transition: all 0.3s;
}

.price-input-item .el-input__wrapper:focus-within {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
</style>