import { Toast } from "@antmjs/vantui";
import Taro from "@tarojs/taro";
import { getCurrentInstance } from "@tarojs/taro";
import { appId, type } from "../../config";

// 数据库环境
// const db: any = Taro.cloud.database({
//   env: "cloud1-5g5xrgza12a0dd6d",
// });

interface Typeint {
  env?: any;
  id?: any;
  keyValue?: any;
  tableName: any;
  objData?: any;
  okFun: any;
}

// 获取params参数
export const getparams = () => {
  let $instance: any = getCurrentInstance();
  return $instance?.router?.params;
};

// 添加数据
export const addTable: any = ({ env, tableName, objData, okFun }: Typeint) => {
  // 数据库环境
  const db: any = Taro.cloud.database({
    env: env,
  });

  let nowtable: any = db?.collection(tableName);
  nowtable?.add({
    // data 字段表示需新增的 JSON 数据
    data: objData,
    success: (res: any) => {
      okFun(res);
    },
    fail: (err: any) => {
      console.log("err", err);
    },
  });
};

// 获取指定集合数据表 (keyValue指定条件)
export const getTable: any = ({
  env,
  tableName,
  keyValue = {},
  okFun,
}: Typeint) => {
  // 数据库环境
  const db: any = Taro.cloud.database({
    env: env,
  });

  let nowtable: any = db?.collection(tableName);
  if (Object.keys(keyValue)?.length > 0) {
    nowtable?.where(keyValue).get({
      success: (res: any) => {
        okFun(res);
      },
    });
  } else {
    nowtable?.get({
      success: (res: any) => {
        okFun(res);
      },
    });
  }
};

// 获取指定id数据数据
export const getTableid: any = ({
  env,
  tableName,
  id,
  keyValue = {},
  okFun,
}: Typeint) => {
  // 数据库环境
  const db: any = Taro.cloud.database({
    env: env,
  });

  let nowtable: any = db?.collection(tableName);

  if (Object.keys(keyValue)?.length > 0) {
    nowtable
      ?.doc(id)
      .where(keyValue)
      .get({
        success: (res: any) => {
          okFun(res);
        },
        fail: (err: any) => {
          console.log("err", err);
        },
      });
  } else {
    nowtable?.doc(id)?.get({
      success: (res: any) => {
        okFun(res);
      },
      fail: (err: any) => {
        console.log("err", err);
      },
    });
  }
};

// 更新数据
export const updateTableid: any = ({
  env,
  tableName,
  objData,
  id,
  okFun,
}: Typeint) => {
  // 数据库环境
  const db: any = Taro.cloud.database({
    env: env,
  });
  let nowtable: any = db?.collection(tableName);
  nowtable.doc(id).update({
    // nowtable.doc(id).set({
    // data 传入需要局部更新的数据
    data: objData,
    success: (res: any) => {
      okFun(res);
    },
    fail: (err: any) => {
      console.log("err", err);
    },
  });
};

// 删除数据
export const deleteTableid: any = ({ env, tableName, id, okFun }: Typeint) => {
  // 数据库环境
  const db: any = Taro.cloud.database({
    env: env,
  });
  let nowtable: any = db?.collection(tableName);
  nowtable.doc(id).remove({
    success: (res: any) => {
      okFun(res);
    },
  });
};

export const isLogin = () => {
  let isin = false;
  // 检查登录态,获取openid
  Taro.checkSession({
    success: function (res: any) {
      //session_key 未过期，并且在本生命周期一直有效
      console.log("res----", res);
      isin = true;
      // 获取用户openid
    },
    fail: function (err: any) {
      isin = false;
      console.log("err", err);
      // session_key 已经失效，需要重新执行登录流程
      Taro.login({
        success: function (res: any) {
          if (res?.code) {
            isin = true;
          } else {
            isin = false;
          }
        },
      });
    },
  });

  console.log("isin---", isin);
  return isin;
};

// 获取用户openid
export const getOpenid = async () => {
  Taro.cloud.callFunction({
    name: "getOpenid",
    complete: async (res: any) => {
      console.log("callFunction test result: ", res);
      let openid = res?.result?.event?.userInfo?.openId;
    },
  });
};

export const phoneLogin = async () => {
  return new Promise((resolve, reject) => {
    // 数据库环境
    const db: any = Taro.cloud.database({});
    const _ = db.command;
    let openId = "";
    Taro.cloud.callFunction({
      name: "getOpenid",
      complete: async (res: any) => {
        console.log("callFunction test result: ", res);
        openId = res?.result?.event?.userInfo?.openId;
        console.log("openId--", openId);
        // 判断数据库userinfo是否存在openid
        getTable({
          tableName: "userInfo",
          // 指定条件, 有openid相等的数据
          keyValue: { openId: _.eq(openId) },
          // keyValue: { _openId: openId },

          okFun: (res: any) => {
            console.log("res", res);
            let data = res?.data ?? [];
            if (data?.length === 0) {
              //保存openid
              addTable({
                tableName: "userInfo",
                objData: {
                  openId: openId,
                },
                okFun: (res: any) => {},
              });
            } else {
              //查看是否存在手机号
              if (data?.[0]?.authInfo?.[0]?.telNumber) {
                resolve(true);
                return true;
              } else {
                if (type === "people") {
                  // resolve(true)
                  // return true;
                  resolve(false);
                  return false;
                } else {
                  resolve(false);
                  return false;
                }
              }
            }
          },
        });
      },
    });
  });

  // 不存在-未登录
};

export const cloudcall = async (obj: any, number = 0) => {
  const that: any = {};

  that.cloud = new Taro.cloud.Cloud({
    resourceAppid: appId, // 微信云托管环境所属账号，服务商appid、公众号或小程序appid
    resourceEnv: "prod-4go74loxa6ac34a8", // 微信云托管的环境ID
  });
  await that?.cloud.init(); // init过程是异步的，需要等待 init 完成才可以发起调用

  try {
    const result = await that.cloud.callContainer({
      path: obj.path, // 填入业务自定义路径和参数，根目录，就是 /
      method: obj.method || "GET", // 按照自己的业务开发，选择对应的方法
      // dataType:'text', // 如果返回的不是 json 格式，需要添加此项
      header: {
        "X-WX-SERVICE": "fastapiweb", // xxx中填入服务名称（微信云托管 - 服务管理 - 服务列表 - 服务名称）
        // 其他 header 参数
      },
      // 其余参数同 wx.request
    });
    console.log(`微信云托管调用结果${result.errMsg} | callid:${result.callID}`);
    return result.data; // 业务数据在 data 中
  } catch (e) {
    const error = e.toString();
    // 如果错误信息为未初始化，则等待300ms再次尝试，因为 init 过程是异步的
    if (error.indexOf("Cloud API isn't enabled") != -1 && number < 3) {
      return new Promise((resolve) => {
        setTimeout(function () {
          resolve(that.call(obj, number + 1));
        }, 300);
      });
    } else {
      throw new Error(`微信云托管调用失败${error}`);
    }
  }
};
