<template>
  <div class="app-container">
    <div class="btn_wraps">
      <div class="btn" :class="{ active: tableActive == item.autoKey }" v-for="item in tableData" :key="item.autoKey"
        @click="selectItemChange(item.autoKey)">
        {{ item.name }}
      </div>
    </div>
    <div class="form">
      <div class="preview_wrap">
        <div class="phone_wrap">
          <!-- 首页背景 -->
          <div class="index_bg" v-if="tableActive == 'index_bg'">
            <!-- 多图轮播 -->
            <el-carousel height="500px"
              v-if="isJsonArrayString(selectItem.value) && JSON.parse(selectItem.value).length > 0">
              <el-carousel-item v-for="(item, idx) in JSON.parse(selectItem.value)" :key="idx">
                <img class="bg" :src="item" />
              </el-carousel-item>
            </el-carousel>
            <!-- 单图渲染 -->
            <img class="bg" v-else-if="selectItem.value" :src="selectItem.value" alt="" />
            <!-- 空状态提示 -->
            <div class="empty-tip" v-else>暂无图片，请上传</div>

            <div class="menu_wrap">
              <div class="menu_wrap_div">
                <div class="left">
                  <div class="icon_wrap">
                    <SvgIcon style="margin-right: 0" color="rgb(0,0,0)" size="30" iconClass="Coffee"></SvgIcon>
                  </div>
                  <div class="info">
                    <div class="t1">点餐</div>
                    <div class="t2">在线点不排队</div>
                  </div>
                </div>
                <div class="right">
                  <div class="btn">
                    <SvgIcon style="margin-right: 0" size="30" color="rgb(0,0,0)" iconClass="postcard"></SvgIcon>
                    <div class="info">
                      <div class="t1">会员</div>
                      <div class="t2">入会享权益</div>
                    </div>
                  </div>
                  <div class="btn">
                    <SvgIcon style="margin-right: 0" color="rgb(0,0,0)" size="30" iconClass="wallet"></SvgIcon>
                    <div class="info">
                      <div class="t1">充值</div>
                      <div class="t2">充值享更多优惠</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 个人中心背景 -->
          <div class="my_bg" v-if="tableActive == 'my_bg'">
            <img class="bg" :src="selectItem.value" v-if="selectItem.value" />
            <div class="empty-tip my-empty-tip" v-else>暂无图片，请上传</div>
            <div class="content">
              <div class="item" style="display: flex">
                <div class="left">
                  <div class="avatar">
                    <i class="icon el-icon-s-custom"></i>
                  </div>
                  <span>微信用户</span>
                </div>
                <div class="ewm">
                  <i class="icon el-icon-menu"></i>
                </div>
              </div>
              <div class="item">
                <div class="title" style="padding-bottom: 10px">我的资产</div>
                <div class="flex">
                  <div class="btn">
                    <i class="icon el-icon-s-finance"></i>
                    <span class="name">储值</span>
                    <span class="num">**</span>
                  </div>
                  <div class="btn">
                    <i class="icon el-icon-s-ticket"></i>
                    <span class="name">优惠券</span>
                    <span class="num">**</span>
                  </div>
                </div>
              </div>
              <div class="item">
                <div class="title" style="padding-bottom: 10px">我的功能</div>
                <div class="row">
                  <div class="left">
                    <i class="icon el-icon-s-ticket"></i>
                    <div class="label">我的优惠券</div>
                  </div>
                  <i class="arrow el-icon-arrow-right"></i>
                </div>
                <div class="row">
                  <div class="left">
                    <i class="icon el-icon-s-order"></i>
                    <div class="label">我的订单</div>
                  </div>
                  <i class="arrow el-icon-arrow-right"></i>
                </div>
                <div class="row">
                  <div class="left">
                    <i class="icon el-icon-user-solid"></i>
                    <div class="label">个人资料</div>
                  </div>
                  <i class="arrow el-icon-arrow-right"></i>
                </div>
                <div class="row">
                  <div class="left">
                    <i class="icon el-icon-s-management"></i>
                    <div class="label">我的会员卡</div>
                  </div>
                  <i class="arrow el-icon-arrow-right"></i>
                </div>
              </div>
            </div>
          </div>

          <!-- 会员背景 -->
          <div class="member_bg" v-if="tableActive == 'member_bg'">
            <div class="card_wrap">
              <div class="card">
                <img class="bg" :src="selectItem.value" v-if="selectItem.value" />
                <div class="empty-tip member-empty-tip" v-else>暂无图片，请上传</div>
                <div class="content">
                  <div class="ewm">
                    <i class="icon el-icon-menu"></i>
                  </div>
                  <div class="title">{{ shopName }}会员卡 Lv.1</div>
                  <div class="tips">
                    <span>欢迎加入本店会员</span>
                    <span>查看特权</span>
                  </div>
                  <div class="btm">
                    <div class="item">
                      <span>0.00</span>
                      <span>储值</span>
                    </div>
                    <div class="item">
                      <span>0</span>
                      <span>积分</span>
                    </div>
                    <div class="item">
                      <span>0</span>
                      <span>优惠券</span>
                    </div>
                    <div class="item">
                      <span>0</span>
                      <span>权益卡</span>
                    </div>
                  </div>
                </div>
              </div>
              <div class="info_wrap">
                <div class="avatar">
                  <i class="icon el-icon-user"></i>
                </div>
                <div class="info">
                  <div class="t1">感谢你2天陪伴</div>
                  <div class="t2">
                    您今天的幸运词：
                    <span>林波微步</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 商品列表背景 -->
          <div class="shopinfo_bg" v-if="tableActive == 'shopinfo_bg'">
            <!-- 多图轮播 -->
            <el-carousel height="120px"
              v-if="isJsonArrayString(selectItem.value) && JSON.parse(selectItem.value).length > 0">
              <el-carousel-item v-for="(item, idx) in JSON.parse(selectItem.value)" :key="idx">
                <img class="bg" :src="item" />
              </el-carousel-item>
            </el-carousel>
            <!-- 单图渲染 -->
            <img class="bg" v-else-if="selectItem.value" :src="selectItem.value" alt="" />
            <!-- 空状态提示 -->
            <div class="empty-tip shopinfo-empty-tip" v-else>暂无图片，请上传</div>

            <div class="shop_name">{{ shopName }}</div>
            <img class="content" src="@/assets/images/shop_editor_bg.png" alt="" />
          </div>

          <!-- 小票logo -->
          <div class="ticket_wrap" v-if="tableActive == 'ticket_logo'">
            <img class="logo" :src="selectItem.value" v-if="selectItem.value" />
            <div class="empty-tip ticket-empty-tip" v-else>暂无图片，请上传</div>
            <img class="ewm" src="@/assets/images/1024.png" />
            <div class="row">
              <span class="num">123</span>
              <span>座位号：#A9</span>
            </div>
            <div class="row">甜橙马黛茶</div>
            <div class="row">
              <span class="sku">加珍珠、加糖</span>
            </div>
            <div class="row">
              <span class="b">2020-10-24 13:14:52</span>
            </div>
            <div class="row">
              <span class="sku">建议尽快享用，风味更佳</span>
            </div>
          </div>
        </div>
      </div>

      <div class="editor_wrap">
        <div class="header" style="padding-bottom: 20px">
          <div class="t1">{{ selectItem.name }}</div>
          <div class="t2">注：点击图片更换</div>
        </div>
        <div class="form_item">
          <!-- 多图上传 -->
          <div class="upload_wrap" style="display: flex; flex-direction: column; gap: 28px"
            v-if="selectItem.autoKey == 'index_bg' || selectItem.autoKey == 'shopinfo_bg'">
            <MultiImageUpload v-model="imgList" @uploadStart="uploading = true" @uploadAllSuccess="MultiOnSuccess" />
          </div>
          <!-- 单图上传 -->
          <div v-else style="display: flex;">
            <SingleImageUpload v-model="selectItem.value" @onSuccess="onSuccess">
              <img v-if="selectItem.value" :src="selectItem.value" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </SingleImageUpload>
          </div>
          <div class="model_wapra">
            <!-- 个人中心模板图 -->
            <template v-if="selectItem.autoKey == 'my_bg'">
              <div class="title">个人中心模板图</div>
              <div class="user-bg-list" v-if="userBgList.length > 0">
                <img v-for="(url, index) in userBgList" :key="index" :src="url" @click="selectUserBg(url)"
                  class="user-bg-item" />
              </div>
            </template>
            <!-- VIP背景模板图 -->
            <template v-else-if="selectItem.autoKey == 'member_bg'">
              <div class="title">会员卡背景模板图</div>
              <div class="user-bg-list" v-if="vipBgList.length > 0">
                <img v-for="(url, index) in vipBgList" :key="index" :src="url" @click="selectVipBg(url)"
                  class="user-bg-item" />
              </div>
            </template>
          </div>
          <div>
            <el-button type="primary" size="large" @click="doSubmit" :loading="uploading" loading-text="图片上传中...">
              确认修改
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage } from "element-plus";
import shopExtendApi from "@/api/account/shopExtend";
// 确保SvgIcon组件已正确引入
import SvgIcon from "@/components/SvgIcon/index.vue";

export default {
  components: {
    SvgIcon,
  },
  data() {
    return {
      tableActive: "index_bg",
      tableData: [],
      selectItem: {},
      imageUrl: "",
      imgList: [],
      shopName: "",
      uploading: false,
      userBgList: [
        'https://cashier-oss.oss-cn-beijing.aliyuncs.com/upload/2/5c8673150d8e449ba035e3f65866b4ed.png',
        'https://cashier-oss.oss-cn-beijing.aliyuncs.com/upload/2/c442af63d29443c687b24d2a3abbf02b.png',
        'https://cashier-oss.oss-cn-beijing.aliyuncs.com/upload/2/1da89980fa0f4c7abffbcdacc2c3a059.png',
        'https://cashier-oss.oss-cn-beijing.aliyuncs.com/upload/2/16296e40f2634d0da0cf1ff377b2b848.png',
        'https://cashier-oss.oss-cn-beijing.aliyuncs.com/upload/2/f442c0d005b94664ac4b37f7fa19731b.png',
      ],
      vipBgList: [
        'https://cashier-oss.oss-cn-beijing.aliyuncs.com/upload/2/c2add99b9b21464889bc14823b97c40e.png',
        'https://cashier-oss.oss-cn-beijing.aliyuncs.com/upload/2/c0e65f576a1a485da7fac34658b87c24.png',
        'https://cashier-oss.oss-cn-beijing.aliyuncs.com/upload/2/629b8c12b8904140bf84df3a57b3c021.png',
        'https://cashier-oss.oss-cn-beijing.aliyuncs.com/upload/2/cd06e01ad7e848359cdca718f5a06231.png'
      ]
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    // 选择会员背景模板图
    selectVipBg(url) {
      this.selectItem.value = url;
      // this.doSubmit();
    },
    // 选择个人中心背景模板图
    selectUserBg(url) {
      this.selectItem.value = url;
      // this.doSubmit();
    },
    // 提交修改
    async doSubmit() {
      // 多图类型强制同步imgList到selectItem.value
      if (["index_bg", "shopinfo_bg"].includes(this.selectItem.autoKey)) {
        this.selectItem.value =
          this.imgList.length > 0 ? JSON.stringify(this.imgList) : "";
      }

      let data = {
        ...this.selectItem,
        autokey: this.selectItem.autoKey,
      };

      if (data.value === "") {
        ElMessage({
          message: "请上传图片",
          type: "warning",
        });
        return;
      }

      try {
        await shopExtendApi.edit(data);
        ElMessage({
          message: "编辑成功",
          type: "success", // 修复提示类型错误
        });
        this.getList();
      } catch (error) {
        ElMessage({
          message: "编辑失败：" + (error.message || "未知错误"),
          type: "error",
        });
      }
    },

    // 单图上传成功
    onSuccess(response) {
      this.doSubmit();
    },

    // 多图上传成功
    async MultiOnSuccess(response) {
      this.uploading = false;
      // 确保imgList有值再序列化
      this.selectItem.value =
        this.imgList.length > 0 ? JSON.stringify(this.imgList) : "";
      // 强制触发视图更新
      this.$forceUpdate();
      ElMessage({
        message: "图片上传成功",
        type: "success",
      });
    },

    /**
     * 判断字符串是否为合法的 JSON 数组
     * @param {string} str - 待判断的字符串
     * @returns {boolean} true=是JSON数组字符串 / false=普通字符串/其他
     */
    isJsonArrayString(str) {
      if (typeof str !== "string" || str.trim() === "") {
        return false;
      }
      try {
        const parsed = JSON.parse(str);
        return Array.isArray(parsed);
      } catch (e) {
        return false;
      }
    },

    // 切换类型
    selectItemChange(key) {
      this.tableActive = key;
      const targetItem = this.tableData.find((item) => item.autoKey === key) || {};
      // 深拷贝避免引用问题
      this.selectItem = { ...targetItem };

      // 多图类型特殊处理
      if (["index_bg", "shopinfo_bg"].includes(key)) {
        if (this.isJsonArrayString(targetItem.value)) {
          this.imgList = JSON.parse(targetItem.value);
        } else {
          // 非JSON数组时，若有单图值则转为数组，否则置空
          this.imgList = targetItem.value ? [targetItem.value] : [];
        }
        // 同步更新selectItem.value为JSON数组
        this.selectItem.value = JSON.stringify(this.imgList);
      } else {
        this.imgList = [];
        // 单图类型保留原有值
        this.selectItem.value = targetItem.value || "";
      }
    },

    // 获取装修数据
    async getList() {
      try {
        const res = await shopExtendApi.get({});
        this.tableData = res || [];
        // 确保有数据时再切换
        if (this.tableData.length > 0) {
          this.tableActive = this.tableActive || this.tableData[0].autoKey;
          this.selectItemChange(this.tableActive);
        }
        // 补充店铺名称（根据实际接口返回调整）
        this.shopName = "我的店铺";
      } catch (error) {
        console.error("获取装修数据失败：", error);
        ElMessage({
          message: "获取数据失败，请刷新重试",
          type: "error",
        });
      }
    },
  },
};
</script>

<style scoped lang="scss">
.btn_wraps {
  display: flex;
  $color: #40a9ff;
  gap: 30px;

  .btn {
    padding: 0 20px;
    height: 40px;
    border: 1px solid $color;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 0 0 4px #40a9ff29;
    color: $color;
    cursor: pointer;

    &.active {
      background-color: $color;
      color: #fff;
    }
  }
}

.form {
  display: flex;
  padding-top: 30px;

  .preview_wrap {
    width: 317px;

    .phone_wrap {
      width: 100%;
      background-color: #fff;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

      // 空状态通用样式
      .empty-tip {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;
        font-size: 14px;
        background-color: #f5f5f5;
      }

      // 首页空状态
      .index_bg .empty-tip {
        height: 500px;
      }

      // 商品列表空状态
      .shopinfo_bg .empty-tip {
        height: 120px;
      }

      // 个人中心空状态
      .my-empty-tip {
        height: 180px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;
        font-size: 14px;
        background-color: #f5f5f5;
      }

      // 会员背景空状态
      .member-empty-tip {
        height: 144px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;
        font-size: 14px;
        background-color: #f5f5f5;
      }

      // 小票logo空状态
      .ticket-empty-tip {
        height: 80px;
        width: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;
        font-size: 12px;
        background-color: #f5f5f5;
        border-radius: 4px;
      }

      .index_bg {
        padding-bottom: 50px;

        .bg {
          width: 100%;
          height: 500px;
          object-fit: cover;
          position: relative;
        }

        .info {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding-top: 10px;

          .t1 {
            font-size: 14px;
          }

          .t2 {
            font-size: 10px;
            color: #999;
          }
        }

        .menu_wrap {
          padding: 0 20px;
          margin-top: -50px;
          position: relative;

          .menu_wrap_div {
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            display: flex;
            padding: 20px 10px;
            border-radius: 10px;
            background-color: #fff;

            .left {
              flex: 1;
              display: flex;
              flex-direction: column;

              .icon_wrap {
                display: flex;
                justify-content: center;

                .icon {
                  font-size: 34px;
                }
              }
            }

            .right {
              flex: 1;
              display: flex;
              flex-direction: column;
              border-left: 1px solid #ddd;
              padding-left: 20px;

              .btn {
                flex: 1;
                display: flex;
                align-items: center;

                &:last-child {
                  margin-top: 6px;
                }

                .icon {
                  font-size: 30px;
                }

                .info {
                  flex: 1;
                  padding-top: 0;
                }
              }
            }
          }
        }
      }

      .my_bg {
        background-color: #f5f5f5;
        height: 100%;
        padding-bottom: 50px;

        .bg {
          width: 100%;
          height: 180px;
          object-fit: cover;
          position: relative;
        }

        .content {
          padding: 0 10px;
          margin-top: -40px;
          position: relative;

          .item {
            padding: 10px;
            align-items: center;
            justify-content: space-between;
            background-color: #fff;
            border-radius: 10px;
            margin-bottom: 10px;

            .left {
              display: flex;
              align-items: center;

              .avatar {
                width: 50px;
                height: 50px;
                background-color: #efefef;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 50%;

                .icon {
                  font-size: 24px;
                  color: #ddd;
                }
              }

              span {
                margin-left: 10px;
              }
            }

            .ewm {
              width: 30px;
              height: 30px;
              border-radius: 50%;
              background-color: #e3ad7f;
              display: flex;
              align-items: center;
              justify-content: center;

              .icon {
                font-size: 20px;
                color: #fff;
              }
            }

            .flex {
              display: flex;

              .btn {
                flex: 1;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                gap: 5px;

                .icon {
                  font-size: 28px;
                }

                .name {
                  font-size: 14px;
                }

                .num {
                  color: #e3ad7f;
                }
              }
            }

            .row {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 10px 0;

              .left {
                display: flex;
                align-items: center;

                .icon {
                  font-size: 20px;
                }

                .label {
                  font-size: 14px;
                  margin-left: 10px;
                }
              }

              .arrow {
                font-size: 14px;
                color: #999;
              }
            }
          }
        }
      }

      .member_bg {
        height: 100%;
        background-color: #f5f5f5;
        padding: 10px;
        padding-bottom: 400px;

        .card_wrap {
          background-color: #fff;
          border-radius: 10px;
          overflow: hidden;

          .card {
            height: 144px;
            position: relative;

            .bg {
              width: 100%;
              height: 100%;
              position: absolute;
              top: 0;
              left: 0;
              object-fit: cover;
              border-radius: 0 0 10px 10px;
            }

            .content {
              width: 100%;
              height: 100%;
              position: absolute;
              top: 0;
              left: 0;
              background-color: rgba(0, 0, 0, 0.3);
              border-radius: 0 0 10px 10px;
              color: #fff;
              padding: 20px;
              font-size: 14px;

              .ewm {
                width: 30px;
                height: 30px;
                border-radius: 50%;
                background-color: #000;
                display: flex;
                align-items: center;
                justify-content: center;
                position: absolute;
                top: 15px;
                right: 20px;

                .icon {
                  font-size: 16px;
                  color: #fff;
                }
              }

              .title {
                font-size: 16px;
              }

              .tips {
                display: flex;
                justify-content: space-between;
                margin-top: 10px;
                color: inherit;
              }

              .btm {
                width: 100%;
                display: flex;
                position: absolute;
                bottom: 20px;
                left: 0;

                .item {
                  flex: 1;
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  justify-content: center;
                }
              }
            }
          }

          .info_wrap {
            padding: 10px;
            display: flex;
            align-items: center;
            gap: 10px;

            .avatar {
              width: 40px;
              height: 40px;
              border-radius: 50%;
              background-color: #f5f5f5;
              display: flex;
              align-items: center;
              justify-content: center;

              .icon {
                font-size: 20px;
                color: #999;
              }
            }

            .info {
              .t1 {
                font-size: 14px;
                color: #333;
              }

              .t2 {
                font-size: 12px;
                color: #999;
                margin-top: 4px;
              }
            }
          }
        }
      }

      .shopinfo_bg {
        .bg {
          width: 100%;
          height: 120px;
          object-fit: cover;
        }

        .shop_name {
          padding: 10px;
          font-size: 16px;
          color: #333;
          font-weight: 500;
        }

        .content {
          width: 100%;
          height: auto;
        }
      }

      .ticket_wrap {
        padding: 10px;

        .logo {
          width: 80px;
          height: 80px;
          object-fit: contain;
          margin-bottom: 10px;
          border-radius: 4px;
        }

        .ewm {
          width: 80px;
          height: 80px;
          object-fit: contain;
          margin-bottom: 10px;
        }

        .row {
          font-size: 12px;
          color: #666;
          margin-bottom: 4px;

          .num {
            font-size: 14px;
            color: #333;
            font-weight: 500;
            margin-right: 10px;
          }

          .sku {
            color: #999;
          }

          .b {
            font-weight: 500;
            color: #333;
          }
        }
      }
    }
  }

  .editor_wrap {
    flex: 1;
    padding-left: 40px;

    .form_item {
      display: flex;
      flex-direction: column;
      gap: 30px;

      .model_wapra {
        .title {
          font-size: 16px;
          color: #333;
          margin-bottom: 10px;
        }
      }

      .user-bg-list {
        display: flex;
        gap: 10px;

        .user-bg-item {
          width: 120px;
          height: 80px;
          object-fit: cover;
          border-radius: 4px;
          cursor: pointer;
          border: 2px solid transparent;

          &:hover {
            border-color: #40a9ff;
          }
        }
      }

      .avatar-uploader {
        width: 200px;
        height: 200px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;

        .avatar-uploader-icon {
          font-size: 28px;
          color: #8c8c8c;
          width: 178px;
          height: 178px;
          line-height: 178px;
          text-align: center;
        }

        .avatar {
          width: 100%;
          height: 100%;
          display: block;
        }
      }
    }
  }
}
</style>