<template>
  <div class="home-man-page">
    <!-- 固定顶部导航栏 -->
    <NavBar class="nav-bar" />
    <div class="images">
      <van-swipe class="swipe" :autoplay="2000" indicator-color="white">
        <van-swipe-item v-for="(image, index) in info.headImgs" :key="index">
          <img fill="contain" v-lazy="image.url" />
        </van-swipe-item>
      </van-swipe>

    </div>
    <div class="info">
      <div class="title">
        <div class="name" @click="showpop">{{ info.name }}</div>
        <div class="environment" @click="showEnvironmentPopup = true">
          <span>查看店内环境</span>
        </div>
      </div>
      <van-divider />
      <div class="worktime">
        <div>{{ info.status }} {{ info.worktime }}</div>
      </div>
      <van-divider />
      <div class="location">
        <div class="left">
          <span style="color: black; font-size: 15px;">{{ info.location }}</span>
          <br>
          <van-icon name="location-o" size="12" />
          <span>距您驾车或者打车8.0公里 需10分钟</span>
          <br>
          <van-icon name="guide-o" size="12" />
          <span>距离1号线微电园站1号口步行400米 需8分钟</span>
        </div>
        <div class="right">
          <van-icon name="wechat" size="25" @click="clickWechatAndPhone('wechat')" />
          <van-icon name="phone" size="25" @click="clickWechatAndPhone('phone')" />
        </div>
      </div>
    </div>
    <van-divider>新品展示</van-divider>
    <div class="new">
      <van-swipe class="swipe" :autoplay="2000" indicator-color="white">
        <van-swipe-item v-for="(image, index) in info.newPortfolioImgs" :key="index">
          <img fill="contain" v-lazy="image.url" />
        </van-swipe-item>
      </van-swipe>
    </div>



    <div style="height: 200px;"></div>


    <van-popup position="bottom" v-model="show" closeable :close-on-click-overlay="false">
      <van-form @submit="saveChangeInfo">
        <van-field name="headImgs" label="主页店图">
          <template #input>
            <van-uploader v-model="info.headImgs" :after-read="uploadHeadImgs" />
          </template>
        </van-field>
        <van-field v-model="info.name" name="name" label="店名" placeholder="店名"
          :rules="[{ required: true, message: '请填写店名' }]" />
        <van-field v-model="info.worktime" name="worktime" label="营业信息" placeholder="营业信息"
          :rules="[{ required: true, message: '请填写营业信息' }]" />
        <van-field readonly clickable label="营业状态" :value="info.status" placeholder="选择营业状态"
          @click="showPicker = true" />
        <van-popup v-model="showPicker" round position="bottom">
          <van-picker show-toolbar :columns="columns" @cancel="showPicker = false" @confirm="onPicker" />
        </van-popup>
        <van-field v-model="info.location" name="location" label="地址" placeholder="地址"
          :rules="[{ required: true, message: '请填写地址' }]" />
        <van-field v-model="info.wechat" name="wechat" label="微信" placeholder="微信"
          :rules="[{ required: true, message: '请填写微信' }]" />
        <van-field v-model="info.phone" name="phone" label="电话" placeholder="电话"
          :rules="[{ required: true, message: '请填写电话' }]" />

        <van-field name="locationImgs" label="指引图">
          <template #input>
            <van-uploader v-model="info.locationImgs" :after-read="uploadLocationImgs" />
          </template>
        </van-field>
        <van-field name="newPortfolioImgs" label="新品图">
          <template #input>
            <van-uploader v-model="info.newPortfolioImgs" :after-read="uploadnewPortfolioImgs" />
          </template>
        </van-field>
        <van-field name="environmentImgs" label="环境图">
          <template #input>
            <van-uploader v-model="info.environmentImgs" :after-read="uploadEnvironmentImgs" />
          </template>
        </van-field>
        <van-field name="publicityImg" label="广告图">
          <template #input>
            <van-uploader v-model="info.publicityImg" :after-read="uploadPublicityImg" :max-count="1" />
          </template>
        </van-field>
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit">提交</van-button>
        </div>
      </van-form>

    </van-popup>
    <van-popup v-model="showEnvironmentPopup" position="bottom" closeable style="height: 50vh;">
      <div class="environment-images">
        <van-swipe class="swipe" :autoplay="2000" indicator-color="white">
          <van-swipe-item v-for="(image, index) in info.environmentImgs" :key="index">
            <img fill="contain" v-lazy="image.url" />
          </van-swipe-item>
        </van-swipe>
      </div>
    </van-popup>

    <van-overlay :show="showpublicityImg" @click="show = false">
      <div class="wrapper" @click.stop>
        <div class="block">
          <img v-lazy="info.publicityImg.length > 0 ? info.publicityImg[0].url : ''" />
          <div class="coress">
            <van-icon name="add" @click="showpublicityImg = false" size="24" style="transform: rotate(45deg)"
              color="white" />
          </div>
        </div>
      </div>
    </van-overlay>


    <!-- 固定底部TabBar -->
    <ManTabBar class="tab-bar" />
  </div>
</template>

<script>
import NavBar from '@/components/NavBar.vue';
import ManTabBar from '@/components/ManTabBar.vue';
export default {
  name: 'HomeManPage',
  components: {
    ManTabBar,
    NavBar
  },
  props: {},
  data() {
    return {
      show: false,
      info: {
        id: 1,
        headImgs: [],
        guide: '距离1号线微电园站1号口步行400米 需8分钟',
        wechat: '',
        phone: '',
        newPortfolioImgs: [],
        locationImgs: [],
        environmentImgs: [

        ],
        publicityImg: [],
        status: ""
      },
      storageUrl: 'http://xiaowangnas.com:9000/yumiartnail',
      saveInfo: {
        id: 1,
        headImg: '',
        name: '',
        worktime: '',
        address: '',
        wechat: '',
        phone: '',
        locationImg: '',
        newPortfolioImg: '',
        environmentImg: '',
        publicityImg: '',
      },
      showPicker: false,
      columns: ['营业中', '休息中'],
      showEnvironmentPopup: false,
      showpublicityImg: true,
      textToCopy: '', // 要复制的文本
    };
  },
  watch: {},
  computed: {},
  methods: {
    async getInfo() {
      const res = await this.$axios.get('/mainInfo/getMainInfo');
      if (res.code == 200) {
        this.id = res.data.id;
        this.info.headImgs = this.convertToObjectArray(res.data.headImg.split('&&'));
        this.info.name = res.data.name;
        this.info.status = res.data.status == 0 ? '休息中' : '营业中';
        this.info.worktime = res.data.worktime;
        this.info.location = res.data.address;
        this.info.wechat = res.data.wechat;
        this.info.phone = res.data.phone;
        this.info.locationImgs = this.convertToObjectArray(res.data.locationImg.split('&&'));
        this.info.newPortfolioImgs = this.convertToObjectArray(res.data.newPortfolioImg.split('&&'));
        this.info.environmentImgs = this.convertToObjectArray(res.data.environmentImg.split('&&'));
        this.info.publicityImg = [{ url: this.storageUrl + res.data.publicityImg }];
      }
      if (this.info.publicityImg.length > 0) {
        this.showpublicityImg = true;
      } else {
        this.showpublicityImg = false;
      }
      console.log(this.info);

    },
    async saveChangeInfo() {
      this.show = false;
      this.saveInfo.id = this.info.id;
      this.saveInfo.headImg = this.convertUrlsToString(this.info.headImgs);
      this.saveInfo.name = this.info.name;
      this.saveInfo.worktime = this.info.worktime;
      this.saveInfo.address = this.info.location;
      this.saveInfo.wechat = this.info.wechat;
      this.saveInfo.phone = this.info.phone;
      this.saveInfo.locationImg = this.convertUrlsToString(this.info.locationImgs);
      this.saveInfo.newPortfolioImg = this.convertUrlsToString(this.info.newPortfolioImgs);
      this.saveInfo.environmentImg = this.convertUrlsToString(this.info.environmentImgs);
      this.saveInfo.publicityImg = this.info.publicityImg.length > 0 ? this.info.publicityImg[0].url.replace(this.storageUrl, '') : '';
      this.saveInfo.status = this.info.status == '营业中' ? 0 : 1;
      console.log(this.saveInfo);
      const res = await this.$axios.post('/mainInfo/updateMainInfo', this.saveInfo);
      console.log(res);
      if (res.code == 200) {
        this.$toast.success('修改成功');
      } else {
        this.$toast.fail('修改失败');
      }
    },
    showpop() {
      this.show = true;
    },
    uploadHeadImgs(file) {
      this.uploadImgs(file, 'headImgs')
    },
    uploadLocationImgs(file) {
      this.uploadImgs(file, 'locationImgs')
    },
    uploadnewPortfolioImgs(file) {
      this.uploadImgs(file, 'newPortfolioImgs')
    },
    uploadEnvironmentImgs(file) {
      this.uploadImgs(file, 'environmentImgs')
    },
    uploadPublicityImg(file) {
      this.uploadImgs(file, 'publicityImg')
    },
    //上传文件
    async uploadImgs(file, type) {
      try {
        const filePath = `${type}/${Date.now()}-${file.file.name}`;
        let result = await this.$fileService.uploadFile({
          bucketName: 'yumiartnail',
          filePath: filePath,
          file: file.file,

        });
        result = `${this.storageUrl}/${result}`;
        switch (type) {
          case 'headImgs':
            this.info.headImgs.pop();
            this.info.headImgs.push({ url: result });
            break;
          case 'locationImgs':
            this.info.locationImgs.pop();
            this.info.locationImgs.push({ url: result });
            break;
          case 'newPortfolioImgs':
            this.info.newPortfolioImgs.pop();
            this.info.newPortfolioImgs.push({ url: result });
            break;
          case 'environmentImgs':
            this.info.environmentImgs.pop();
            this.info.environmentImgs.push({ url: result });
            break;
          case 'publicityImg':
            this.info.publicityImg.pop();
            this.info.publicityImg.push({ url: result });
            break;
          default:
            break;
        }
        this.$toast.success('上传成功');
      } catch (error) {
        // this.uploadResult = `上传失败: ${error.message}`;
        this.$toast.fail('上传失败');
        console.error(error);
      } finally {
        this.uploading = false;
      }
    },
    convertToObjectArray(urls) {
      return urls.map(url => {
        if (!url) return { url: '' }; // 处理空字符串
        const modifiedUrl = this.storageUrl + url;
        return { url: modifiedUrl }
      });
    },
    convertUrlsToString(arr) {
      return arr.map(item => {
        let modifiedUrl = item.url.replace(this.storageUrl, '');
        return modifiedUrl;
      }).join('&&');
    },
    onPicker(value) {
      this.info.status = value == '营业中' ? 1 : 0;
      this.showPicker = false;
    },
    clickWechatAndPhone(type) {
      this.$dialog.confirm({
        title: type == 'wechat' ? '微信号' : '电话号码',
        message: type == 'wechat' ? this.info.wechat + '\n（点击一键复制后,可自动复制并跳转微信）' : this.info.phone,
        confirmButtonText: '一键复制',
      })
        .then(() => {
          this.textToCopy = type == 'wechat' ? this.info.wechat : this.info.phone;
          this.handleCopy(type);
        })
        .catch(() => {
          // on cancel
        });
    },
    async handleCopy(type) {
      try {
        // 首先检查是否支持navigator.clipboard
        if (navigator.clipboard) {
          // 请求剪贴板写入权限（适用于需要权限的浏览器）
          if ('permissions' in navigator) {
            const permissionStatus = await navigator.permissions.query({ name: 'clipboard-write' });
            if (permissionStatus.state === 'granted' || (permissionStatus.state === 'prompt' && await permissionStatus.request() === 'granted')) {
              await navigator.clipboard.writeText(this.textToCopy);
              this.$toast.success('已复制到剪贴板');
            } else {
              console.error('未获得剪贴板写入权限');
              this.$toast.fail('未获得剪贴板写入权限，请手动复制');
            }
          } else {
            // 如果不需要权限请求，直接复制
            await navigator.clipboard.writeText(this.textToCopy);
            this.$toast.success('已复制到剪贴板');
          }
        } else {
          // 如果不支持navigator.clipboard，尝试使用document.execCommand（旧方法，兼容性更好但有局限性）
          const textArea = document.createElement('textarea');
          textArea.value = this.textToCopy;
          document.body.appendChild(textArea);
          textArea.select();
          try {
            document.execCommand('copy');
            this.$toast.success('已复制到剪贴板');
          } catch (err) {
            console.error('复制失败:', err);
            this.$toast.fail('复制失败，请手动复制');
          }
          document.body.removeChild(textArea);
        }
        this.handleSpecialAction(type)
      } catch (err) {
        console.error('复制失败:', err);
        this.$toast.fail('复制失败，请手动复制');
      }
    },
    handleSpecialAction(type) {
      // 检查是否是微信环境
      const isWechatEnv = /MicroMessenger/i.test(navigator.userAgent);

      if (type === 'wechat') {
        // 微信跳转处理
        if (isWechatEnv) {
          this.$toast.fail('请在微信外部浏览器中打开以跳转微信');
          return;
        }

        try {
          // 尝试打开微信
          const wechatLink = 'weixin://';
          const startTime = Date.now();

          // 创建隐藏的iframe尝试打开协议，解决部分浏览器直接跳转失败问题
          const iframe = document.createElement('iframe');
          iframe.style.display = 'none';
          iframe.src = wechatLink;
          document.body.appendChild(iframe);

          // 检查是否成功打开
          setTimeout(() => {
            document.body.removeChild(iframe);
            if (Date.now() - startTime < 1000) {
              this.$toast.fail('未检测到微信客户端，请手动打开微信');
            } else {
              this.$toast.info('正在打开微信...');
            }
          }, 800);
        } catch (error) {
          this.$toast.fail('打开微信失败，请手动操作');
          console.error('微信跳转错误:', error);
        }
      } else if (type === 'phone') {
        // 电话号码处理
        if (!this.info?.phone) {
          this.$toast.fail('电话号码不存在');
          return;
        }

        // 标准化电话号码格式
        const phoneNumber = this.info.phone.replace(/\s/g, '');
        if (!/^\d{11}$/.test(phoneNumber)) {
          this.$toast.fail('请检查电话号码格式');
          return;
        }

        try {
          // 检查是否在支持电话功能的环境
          if (/Android|iPhone/i.test(navigator.userAgent)) {
            // 移动设备直接调用拨号
            window.location.href = `tel:${phoneNumber}`;
            this.$toast.info(`正在拨打 ${phoneNumber}...`);
          } else {
            // 桌面设备提示
            this.$toast.info(`电话号码: ${phoneNumber}\n请在手机上使用此功能`);
          }
        } catch (error) {
          this.$toast.fail('拨打电话失败，请手动拨号');
          console.error('拨打电话错误:', error);
        }
      }
    }
  },
  created() { },
  mounted() {
    this.getInfo();
  }
};
</script>
<style lang="less" scoped>
// 变量定义
@base-bg: #f9fafb;
@card-bg: white;
@text-primary: #1f2937;
@text-secondary: #6b7280;
@accent-color: #3b82f6;
@accent-dark: #2563eb;
@danger-color: #ef4444;
@gray-light: #d1d5db;
@shadow-base: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
@shadow-active: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);

.home-man-page {
  width: 100vw;
  height: 100vh;
  overflow: auto;
max-width: 800px;
margin: 0 auto;
  .images {
    width: 100%;
    height: 35vh;
    overflow: hidden;
    min-height: 200px;
    max-height: 500px;

    .swipe {
      width: 100%;
      height: 100%;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .info {
    width: 100%;
    padding: 10px;

    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .name {
        font-size: 40px;
        color: @text-primary;
        font-weight: bold;
        cursor: pointer;
      }

      .environment {
        cursor: pointer;

        span {
          font-size: 12px;
          color: #525050;
        }
      }

    }

    .location {
      display: flex;

      .left {
        width: 70%;

        span {
          font-size: 12px;
          color: #a19e9e;
          margin-bottom: 10px;

        }
      }

      .right {
        width: 30%;
        display: flex;
        justify-content: space-evenly;
        align-items: center;
        color: #a19e9e;
      }


    }
  }

  .new {
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    width: 95%;
    height: 25vh;
    overflow: hidden;
    min-height: 200px;
    max-height: 500px;
    margin: auto;
    border-radius: 10px;

    .swipe {
      width: 100%;
      height: 100%;

      img {
        width: 100%;
        height: 100%;
      }
    }

  }

  .navigation {
    width: 100%;
  }

  .environment-images {
    width: 100%;
    overflow: hidden;
    max-height: 500px;

    .swipe {
      width: 100%;
      height: 100%;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    position: relative;
    width: 100%;

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

      img {
        width: 100%;
        object-fit: contain;
        border-radius: 10px;
      }

      .coress {
        padding-top: 20px;
      }
    }
  }



}
</style>