<template>
  <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑宝贝' : '添加宝贝'" width="600px" :close-on-click-modal="false"
    @close="handleClose">
    <div class="dialog-content">

      <!-- 表单区域 -->
      <el-form ref="editFormRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="头像" prop="avatar">
          <div class="preview-image">
            <img v-if="formData.avatar" :src="getEnvUrl(formData.avatar)" class="preview-img" />
            <div v-else class="no-preview">
              <el-icon>
                <Picture />
              </el-icon>
              <span>头像预览</span>
            </div>
          </div>

          <!-- 裁剪区域 -->
          <div class="cutter-container">
            <img-cutter ref="imgCutterRef" :img="formData.avatar ? getEnvUrl(formData.avatar) : ''" :cutWidth="400"
              :cutHeight="400" :rate="'1:1'" :fixedNumber="[1, 1]" :fixed="true" :fixedBox="true" :original="false"
              :autoCrop="true" :autoCropWidth="300" :autoCropHeight="300" :centerBox="true" :showChooseBtn="true"
              :boxWidth="300" :boxHeight="300" @cutDown="handleCut" class="img-cutter-wrapper">
              <template #cut>
                <div style="padding: 20px; text-align: center;">
                  <el-button type="primary" size="small" @click="handleCropClick">确认裁剪</el-button>
                </div>
              </template>
              <template #placeholder>
                <div class="avatar-uploader">
                  <el-icon class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                  <span class="upload-text">点击上传头像</span>
                </div>
              </template>
            </img-cutter>
          </div>
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名" clearable />
        </el-form-item>

        <el-form-item label="小名" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入小名" clearable />
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="formData.sex">
            <el-radio :value="1">男</el-radio>
            <el-radio :value="2">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="出生日期" prop="birth">
          <el-date-picker v-model="formData.birth" type="date" placeholder="选择出生日期" style="width: 100%"
            format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>

        <el-form-item label="身高" prop="height">
          <el-input v-model="formData.height" :min="0" :max="200" :precision="1" :step="0.5" controls-position="right"
            style="width: 100%">
            <template #append>CM</template>
          </el-input>
        </el-form-item>

        <el-form-item label="体重" prop="weight">
          <el-input v-model="formData.weight" :min="0" :max="50" :precision="2" :step="0.01" controls-position="right"
            style="width: 100%">
            <template #append>KG</template>
          </el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">确定</el-button>
    </template>

  </el-dialog>

  <!-- <ImgCutter :cutWidth="300" :cutHeight="300" :tool="true" V-on:cutDown="handleCut" /> -->
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { Plus, Picture } from '@element-plus/icons-vue';
// import { createBaby, editBaby } from '@/api/babyhealth';
// import { uploadAvatar } from '@/api/file';

import ImgCutter from 'vue-img-cutter';

// 定义 ImgCutter 实例类型
interface ImgCutterInstance {
  chooseImg: () => void;
  resetCrop: () => void;
  crop: () => void;
}

// 定义裁剪数据结构类型
interface CroppedData {
  blob: Blob;
  dataURL: string;
  file: File;
  fileName: string;
  index: number | null;
}

interface BabyFormData {
  id: number;
  name: string;
  nickname: string;
  sex: number;
  birth: string;
  height: number;
  weight: number;
  avatar: string;
  status: number;
}


const imgCutterRef = ref<ImgCutterInstance | null>(null);

// 处理裁剪按钮点击
const handleCropClick = () => {
  if (imgCutterRef.value) {
    (imgCutterRef.value as any).crop();
  }
};

const props = defineProps<{
  visible: boolean;
  editData?: BabyFormData;
}>();

const emit = defineEmits<{
  'update:visible': [value: boolean];
  success: [];
}>();

const dialogVisible = ref(false);
const loading = ref(false);
const editFormRef = ref<FormInstance>();
const cropDialogVisible = ref(false);
const croppingImage = ref('');
let selectedFile: File | null = null;
// 图片大小限制 (5MB)
const MAX_IMAGE_SIZE = 5 * 1024 * 1024;

// 支持的图片类型
const SUPPORTED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif'];

// 处理裁剪完成
const handleCut = async (data: CroppedData) => {
  try {
    // 创建FormData
    const uploadFormData = new FormData();
    uploadFormData.append('file', data.file);
    uploadFormData.append('cate', 'baby_avatar');

    // 上传裁剪后的图片
    const response = await uploadAvatar(uploadFormData);

    if (response.code === 200 || response.code === 201) {
      const avatarUrl = response.data.url || response.data.path || '';
      formData.avatar = avatarUrl;

      if (response.code === 201) {
        ElMessage.info("文件已存在，使用已有图片");
      } else {
        ElMessage.success("头像上传成功");
      }
    } else {
      ElMessage.error(response.msg || "上传失败");
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error("上传失败，请重试");
  } finally {
    // 清理
    croppingImage.value = '';
    selectedFile = null;
  }
};


const formData = reactive<BabyFormData>({
  id: 0,
  name: '',
  nickname: '',
  sex: 1,
  birth: '',
  height: 0,
  weight: 0,
  avatar: '',
  status: 1
});

const isEdit = ref(false);

const formRules: FormRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  birth: [{ required: true, message: '请选择出生日期', trigger: 'change' }]
};

// 拼接接口路径
const getEnvUrl = (path: string) => {
  const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
  return `${API_BASE_URL}${path}`;
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: 0,
    name: '',
    nickname: '',
    sex: 1,
    birth: '',
    height: 0,
    weight: 0,
    avatar: '',
    status: 1
  });
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

// 监听 visible 变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val;
});

// 监听 dialogVisible 变化
watch(dialogVisible, (val) => {
  emit('update:visible', val);
});

// 监听 editData 变化
watch(() => props.editData, (data) => {
  if (data) {
    isEdit.value = true;
    Object.assign(formData, data);
  } else {
    isEdit.value = false;
    resetForm();
  }
}, { immediate: true });


// 提交表单
const handleSubmit = async () => {
  if (!editFormRef.value) return;

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        let res;
        if (formData.id) {
          // 编辑
          const submitData: Record<string, any> = {};
          Object.keys(formData).forEach(key => {
            if (key !== 'id' && formData[key as keyof BabyFormData] !== undefined && formData[key as keyof BabyFormData] !== null) {
              submitData[key] = formData[key as keyof BabyFormData];
            }
          });
          res = await editBaby(formData.id, submitData);
        } else {
          // 新增
          const submitData = new FormData();
          Object.keys(formData).forEach(key => {
            if (key !== 'id' && formData[key as keyof BabyFormData] !== undefined && formData[key as keyof BabyFormData] !== null) {
              submitData.append(key, String(formData[key as keyof BabyFormData]));
            }
          });
          res = await createBaby(submitData);
        }

        if (res.code === 200) {
          ElMessage.success(formData.id ? '编辑成功' : '添加成功');
          dialogVisible.value = false;
          resetForm();
          emit('success');
        } else {
          ElMessage.error(res.msg || (formData.id ? '编辑失败' : '添加失败'));
        }
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败');
      } finally {
        loading.value = false;
      }
    }
  });
};
</script>

<style lang="less" scoped>
.dialog-content {
  padding: 20px 10px;
}

.preview-image {
  width: 168px;
  height: 168px;
  border-radius: 8px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  border: 1px dashed var(--el-border-color);
  margin-right: 30px;

  .preview-img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }

  .no-preview {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: var(--el-text-color-secondary);

    .el-icon {
      font-size: 48px;
      margin-bottom: 8px;
      color: var(--el-text-color-placeholder);
    }

    span {
      font-size: 14px;
    }
  }
}

.avatar-section {
  margin-bottom: 24px;

  .cutter-container {
    max-width: 500px;
  }

  :deep(.avatar-uploader) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 200px;
    height: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: var(--el-fill-color-light);
    margin: 0 auto;

    &:hover {
      border-color: var(--el-color-primary);
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
    }

    .avatar-uploader-icon {
      font-size: 32px;
      color: var(--el-text-color-placeholder);
      margin-bottom: 8px;
    }

    .upload-text {
      color: var(--el-text-color-secondary);
      font-size: 14px;
    }
  }

  .img-cutter-wrapper {
    border: 1px solid #ddd;
    border-radius: 6px;
    overflow: hidden;
    width: 100%;

    :deep(.img-cutter) {
      width: 100%;
      margin: 0;
      max-width: none;

      .cut-btn {
        display: none;
      }

      .cut-box {
        width: 100% !important;
        height: 350px !important;
      }

      .cut-container {
        width: 100% !important;
        height: 350px !important;
      }

      .cut-preview-box {
        width: 100% !important;
        height: 100% !important;
      }
    }
  }
}
</style>
