<script setup lang="ts">
import { ref, watch, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { paymentMethodOptions, modeToPaymentMethodMap } from "@/utils/maps/payment";
import { addShop, updateShop, 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 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 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 = (rawFile) => {
  if (!['image/jpeg', 'image/png'].includes(rawFile.type)) {
    ElMessage.error('封面图必须是 JPG/PNG 格式!');
    return false;
  }
  if (rawFile.size > 50 * 1024 * 1024) {
    ElMessage.error('封面图大小不能超过 50MB!');
    return false;
  }
  return true;
};

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('复制失败，请手动复制');
};
</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-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 type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</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;
}
</style>