<script setup lang="ts">
import { ref, watch, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { paymentMethodOptions, modeToPaymentMethodMap } from "@/utils/maps/payment";
import { addShop, updateShop, deleteShop, ShopDTO, UpdateShopCommand, AddShopCommand } from "@/api/shop/shop";
import { useWxStore } from "@/store/modules/wx";
import Upload from "@iconify-icons/ep/upload";
import { useSysConfigStoreHook } from "@/store/modules/sysConfig";
import { beforeImageUpload } from "@/utils/imageCompressor";
import ReQrcode from "@/components/ReQrcode";
import { copyTextToClipboard } from "@pureadmin/utils";
const { VITE_APP_BASE_API } = import.meta.env;

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  row: {
    type: Object as () => ShopDTO,
    default: () => ({})
  }
});

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

const wxStore = useWxStore();
const sysConfigStore = useSysConfigStoreHook();

const formRef = ref();
const deleteDialogVisible = ref(false);
const formData = ref<UpdateShopCommand>({
  corpid: wxStore.corpid,
  shopId: 0,
  shopName: "",
  belongType: undefined,
  mode: undefined,
  balanceEnable: undefined,
  coverImg: ""
});

const rules = {
  shopName: [{ required: true, message: "请输入地址名称", trigger: "blur" }],
  belongType: [{ required: true, message: "请选择商品模式", trigger: "change" }],
  mode: [{ required: true, message: "请选择运行模式", trigger: "change" }],
  balanceEnable: [{ required: true, message: "请选择借呗支付状态", trigger: "change" }],
  coverImg: [{ required: true, message: "请上传封面图", trigger: "change" }]
};



watch(
  () => props.visible,
  val => {
    if (val) {
      if (props.row?.shopId) {
        formData.value = {
          ...props.row,
          shopId: props.row.shopId,
          corpid: props.row.corpid,
          belongType: props.row.belongType,
          mode: props.row.mode,
          balanceEnable: props.row.balanceEnable,
          coverImg: props.row.coverImg || ""
        };
      } else {
        formData.value = {
          shopId: 0,
          shopName: "",
          corpid: wxStore.corpid,
          belongType: undefined,
          mode: undefined,
          balanceEnable: undefined,
          coverImg: ""
        };
      }
    }
  },
  { immediate: true }
);

const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    if (formData.value.shopId) {
      await updateShop(formData.value.shopId, formData.value);
      ElMessage.success("修改成功");
    } else {
      await addShop(formData.value);
      ElMessage.success("新增成功");
    }

    emit("update:visible", false);
    emit("refresh");
  } catch (error) {
    console.error(error);
  }
};

const handleClose = () => {
  emit("update:visible", false);
};

const handleAvatarSuccess = (response) => {
  formData.value.coverImg = response.data.url;
};

const beforeAvatarUpload = async (rawFile: File) => {
  const result = await beforeImageUpload(rawFile, {
    quality: 0.7,
    maxWidth: 980,
    maxHeight: 980
  });
  return result;
};

const currentPaymentMethods = computed(() => {
  if (typeof formData.value.mode !== 'number') return [];
  const methodValues = modeToPaymentMethodMap[formData.value.mode] || [];
  return methodValues.map(value => {
    const option = paymentMethodOptions.find(item => item.value === value);
    return option ? { label: option.label, type: option.type } : null;
  }).filter(Boolean);
});

const copyLink = () => {
  if (!formData.value.shopId) {
    ElMessage.warning("店铺ID不存在，无法复制链接");
    return;
  }
  const url = `${sysConfigStore.serverHost}/shop-api/api/shop/wechatAuth?shopId=${formData.value.shopId}`;
  const success = copyTextToClipboard(url);
  success ? ElMessage.success('链接复制成功') : ElMessage.error('复制失败，请手动复制');
};

const handleDelete = () => {
  deleteDialogVisible.value = true;
};

const confirmDelete = async () => {
  try {
    await deleteShop(formData.value.shopId.toString());
    ElMessage.success("删除成功");
    deleteDialogVisible.value = false;
    emit("update:visible", false);
    emit("refresh");
  } catch (error) {
    console.error(error);
    ElMessage.error("删除失败");
  }
};

const cancelDelete = () => {
  deleteDialogVisible.value = false;
};
</script>

<template>
  <el-drawer :title="formData.shopId ? '编辑地址' : '新增地址'" :model-value="visible" @update:model-value="handleClose"
    size="600px" direction="rtl">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="地址ID" prop="shopId" v-if="formData.shopId">
        <el-input v-model="formData.shopId" :disabled="true" />
      </el-form-item>
      <el-form-item label="地址名称" prop="shopName">
        <el-input v-model="formData.shopName" placeholder="请输入地址名称" />
      </el-form-item>
      <el-form-item label="封面图" prop="coverImg">
        <el-upload class="avatar-uploader" :action="VITE_APP_BASE_API + '/file/upload'" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="formData.coverImg" :src="formData.coverImg" class="avatar" />
          <svg v-if="!formData.coverImg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 100" width="160"
            height="100" class="cabinet-image">
            <!-- 背景：浅灰色填充，模拟图片容器 -->
            <rect width="100%" height="100%" fill="#f8f8f8" rx="4" ry="4" /> <!-- 可选圆角，适配卡片风格 -->
            <!-- 图片图标：简化的“图片”符号（矩形+交叉线），直观关联“图片” -->
            <g stroke="#ccc" stroke-width="2" fill="none">
              <rect x="20" y="10" width="120" height="65" /> <!-- 图片框 -->
              <line x1="20" y1="10" x2="140" y2="75" /> <!-- 对角线1 -->
              <line x1="140" y1="10" x2="20" y2="75" /> <!-- 对角线2 -->
            </g>
            <!-- 说明文字：明确提示“未设置图片”，居中对齐 -->
            <text x="50%" y="92" font-size="12" fill="#888" text-anchor="middle" font-family="Arial, sans-serif">
              未设置图片
            </text>
          </svg>
        </el-upload>
      </el-form-item>
      <!-- <el-form-item label="商品模式" prop="belongType">
        <el-select v-model="formData.belongType" placeholder="请选择归属类型">
          <el-option label="借还模式" :value="0" />
          <el-option label="固资模式" :value="1" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="运行模式" prop="mode">
        <el-select v-model="formData.mode" placeholder="请选择运行模式">
          <el-option label="支付模式" :value="0" />
          <el-option label="审批模式" :value="1" />
          <el-option label="借还模式" :value="2" />
          <el-option label="会员模式" :value="3" />
          <el-option label="耗材模式" :value="4" />
          <el-option label="暂存模式" :value="5" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="借呗支付" prop="balanceEnable">
        <el-select v-model="formData.balanceEnable" placeholder="请选择借呗支付状态">
          <el-option label="正常使用" :value="1" />
          <el-option label="禁止使用" :value="0" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="支付方式">
        <el-tag v-for="method in currentPaymentMethods" :key="method.label" :type="method.type"
          style="margin-right: 5px;">
          {{ method.label }}
        </el-tag>
      </el-form-item>
      <el-form-item label="机柜数量">
        {{ props.row?.cabinetCount || 0 }}
      </el-form-item>
      <el-form-item label="二维码">
        <div class="flex flex-col items-center">
          <ReQrcode :text="`${sysConfigStore.serverHost}/shop-api/api/shop/wechatAuth?shopId=${formData.shopId}`"
            :options="{ width: 150 }" :width="150"/>
          <el-button type="primary" size="small" @click="copyLink" style="margin-left: 10px;">
            复制链接
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose" style="margin-right: 5px;">取消</el-button>
      <el-button 
        v-if="formData.shopId && (props.row?.cabinetCount || 0) === 0" 
        type="danger" 
        @click="handleDelete"
        style="margin-right: 5px;">
        删除
      </el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>

  <!-- 删除确认对话框 -->
  <el-dialog
    v-model="deleteDialogVisible"
    title="确认删除"
    width="400px"
    :close-on-click-modal="false">
    <span>确定要删除地址 "{{ formData.shopName }}" 吗？此操作不可恢复。</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelDelete">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定删除</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.cabinet-image {
  width: 100%;
  height: 100%;
  padding: 0;
  object-fit: contain;
  border-radius: 4px;
}

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