import router from "../router";
import { wecomTicket } from "../api/indexAI";
declare let wx: any;
export const dateFormat = (fmt: string, x: Date | string) => {
  const date = typeof x === "string" ? new Date(x) : x;
  let ret;
  let opt: IAny = {
    "Y+": date.getFullYear().toString(), // 年
    "M+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "h+": date.getHours().toString(), // 时
    "m+": date.getMinutes().toString(), // 分
    "s+": date.getSeconds().toString() // 秒
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
      );
    }
  }
  return fmt;
};

export const RegAccount = /^[a-zA-Z0-9]{9,16}$/;

export const Dateformat = (t: string | Date, format: string) => {
  let fmt = format;
  let ret;
  const date = typeof t === "string" ? new Date(t) : t;
  const opt: IAny = {
    "Y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "H+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "S+": date.getSeconds().toString() // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
      );
    }
  }
  return fmt;
};

export const getWecomType = (agentFrom: string) => {
  // 用户来源  0随身邦 1好邦手 2服务商随身邦 3金牌店随身邦 4导购 5新零售客服
  switch (agentFrom) {
    case 'ssb'://经销商
      return 0;
    case 'hbs'://好邦手
      return 1;
    case 'stoneLikePaint'://服务商
      return 2;
    case 'goldShop'://金牌店
      return 3;
    case 'dg'://导购
      return 4;
    case 'xlskf'://新零售客服
      return 5;
    default:
      return 5; // 默认为5
  }
}

export const getWecomTypeName = (agentFrom: string) => {
  switch (agentFrom) {
    case 'ssb':
      return '经销商随身邦';
    case 'hbs':
      return '好邦手';
    case 'stoneLikePaint':
      return '服务商随身邦';
    case 'goldShop':
      return '金牌店随身邦';
    case 'dg':
      return '导购运营平台';
    case 'xlskf':
      return '新零售客服';
    default:
      return '新零售客服';
  }
}

export const getAgentFrom = (WecomType: unknown): string => {
  const typeNum = Number(WecomType);
  const typeMap = {
    0: 'ssb',          // 经销商
    1: 'hbs',          // 好邦手
    2: 'stoneLikePaint',// 服务商
    3: 'goldShop',     // 金牌店
    4: 'dg',           // 导购
    5: 'xlskf'         // 新零售客服
  };
  return typeMap[typeNum as keyof typeof typeMap] || 'xlskf';
};


export const toLBHome = () => {
  const loginMode = window.localStorage.getItem("loginMode")
  if (loginMode === 'wxidLogin') {
    let baseUrl: string = "";
    process.env.VUE_APP_BASE_API == "/api/"
      ? (baseUrl = process.env.VUE_APP_Target)
      : (baseUrl = process.env.VUE_APP_BASE_API);
    let agent = window.localStorage.getItem('agentFrom');
    let agentFromAI = window.localStorage.getItem('agentFromAI');
    let WecomType = sessionStorage.getItem("userWecomType");
    // 导购来源和无来源的点击小房子为退出应用，其他为返回到首页
    if (WecomType && WecomType == '4') {
      // console.log("----导购来源---")
      wx.invoke('closeWindow', {}, (res) => {
        if (res.err_msg === 'closeWindow:ok') {
          console.log("关闭应用成功")
        } else {
          console.log("关闭应用失败")
        }
      });
    } else if (agentFromAI && agentFromAI === 'dg' || (!agent && !WecomType)) {
      // console.log("----导购or无---")
      wx.invoke('closeWindow', {}, (res) => {
        if (res.err_msg === 'closeWindow:ok') {
          console.log("关闭应用成功")
        } else {
          console.log("关闭应用失败")
        }
      });
    } else {
      if (!agent && WecomType) {
        agent = getAgentFrom(parseInt(WecomType)) || 'ssb';
      }
      window.location.href = baseUrl.replace("wxportal-api/", "") + '?agent=' + agent;
    }
  } else {
    router.replace('/');
  }
}

export const toXiaoChengxu = (appid) => {
  let url = window.location.href.split("#")[0];
  const formData = new FormData();
  formData.append('url', url);
  formData.append('agent', '1');
  wecomTicket(formData).then(response => {
    if (response.StatusCode == 200) {
      let qiyeData = response.Data;
      wx.agentConfig({
        debug: false,
        corpid: qiyeData.appid,
        agentid: qiyeData.agentID,
        timestamp: qiyeData.timestamp,
        nonceStr: qiyeData.noncestr,
        signature: qiyeData.signature,
        jsApiList: ["launchMiniprogram"],
        success: function (res) {
          wx.invoke(
            "launchMiniprogram",
            {
              appid: appid, // 需跳转的小程序appid
              path: "" // 所需跳转的小程序内页面路径及参数。非必填
            },
            function (res) {
              if (res.err_msg == "launchMiniprogram:ok") {
                // 正常
                console.log("正常");
              } else {
                // 错误处理
              }
            }
          );
        },
        fail: function (res) {
          if (res.errMsg.indexOf("function not exist") > -1) {
            alert("版本过低请升级");
          }
        }
      });
    }
  });
}

// 获取微信API授权信息
export const getWxconfig = () => {
  if(window.localStorage.getItem('agentFromAI') !== 'xlskf'){
    return;
  }
  // const jsApiList = [ 'downloadFile', 'saveImageToPhotosAlbum', 'closeWindow', 'hideMenuItems'];
  let url = window.location.href.split("#")[0];
  const formData = new FormData();
  formData.append('url', url);
  formData.append('agent', '1');
  wecomTicket(formData).then(response => {
    if (response.StatusCode == 200) {
      let qiyeData = response.Data;
      wx.agentConfig({
        debug: false,
        corpid: qiyeData.appid,
        agentid: qiyeData.agentID,
        timestamp: qiyeData.timestamp,
        nonceStr: qiyeData.noncestr,
        signature: qiyeData.signature,
        jsApiList: ["hideMenuItems"],
        success: function (res) {
          wx.hideMenuItems({
            menuList: [
              "menuItem:share:wechat",
              "menuItem:openWithBrowser",
              "menuItem:share:email",         // 通过邮件转发
              "menuItem:copyUrl",
              "menuItem:share:wechat_friend",
              "menuItem:share:timeline",
              "menuItem:share:appMessage",
              "menuItem:openWithSafari"
            ],
            success: () => {
              // console.log('菜单隐藏成功');
            },
            fail: (err) => {
              // console.log('菜单隐藏失败：', err);
            }
          });
        }
      });
    }
  });
}
// 获取微信API授权信息
export const getWxconfigNew = () => {
  return new Promise((resolve, reject) => {
    let url = window.location.href.split("#")[0];
    const formData = new FormData();
    formData.append('url', url);
    formData.append('agent', '1');
    wecomTicket(formData).then(response => {
      if (response.StatusCode == 200) {
        let qiyeData = response.Data;
        wx.agentConfig({
          debug: false,
          corpid: qiyeData.appid,
          agentid: qiyeData.agentID,
          timestamp: qiyeData.timestamp,
          nonceStr: qiyeData.noncestr,
          signature: qiyeData.signature,
          jsApiList: ["chooseImage", "getLocalImgData", "previewImage"],
          success: function (res) { }
        });
        wx.ready(() => {
          console.log('企业微信SDK初始化成功');
          resolve(true); 
        });
        wx.error((err) => {
          console.error('SDK初始化失败：', err);
          reject(err); 
        });
      } else {
        reject(new Error('获取微信配置参数失败'));
      }
    }).catch(err => {
      console.error('请求wecomTicket接口失败：', err);
      reject(err);
    });
  });
};

/**
 * 企业微信H5 环境+缓存双重校验工具
 * 校验规则：1.必须是企微APP/客户端环境  
 * 校验失败自动跳转 /error 页面，无返回值
 */
export const checkWxWorkEnvAndUserCache = () => {
  try {
    const currentHost = window.location.hostname;
    const isLocalDev = currentHost === 'localhost' || currentHost.startsWith('192.168.101');
    if (isLocalDev) {
      return;
    }
    const userAgent = window.navigator.userAgent.toLowerCase();
    const isWxWorkEnv = userAgent.includes('wxwork');
    // console.log("userAgent", userAgent)
    // console.log("isWxWorkEnv", isWxWorkEnv)
    if (!isWxWorkEnv) {
      console.error('校验失败：当前环境非企业微信APP/客户端');
      sessionStorage.setItem("errorMsgTit", "请在企微客户端打开链接")
      router.replace(`/error`);
      return;
    }
  } catch (error) {
    console.error('环境校验异常：', error);
    sessionStorage.setItem("errorMsgTit", "环境异常")
    router.replace(`/error`)
  }
}

export const checkAndSaveUserWecomType = () => {
  // 已存在则直接返回，避免重复赋值
  if (sessionStorage.getItem('userWecomType')) return;
  const { WecomType } = router.currentRoute.query;
  const originWecomType = String(WecomType);
  const validWecomTypes = new Set(['0', '1', '2', '3', '4', '5']);
  const userWecomType = validWecomTypes.has(originWecomType) ? originWecomType : '5';
  sessionStorage.setItem('userWecomType', userWecomType);
};