import { GetAuditInfo, GetAuditStatus } from "../../api/audit";
import { GetAccountLogin, GetLogin } from "../../api/login";
import { OutLogin } from "../../api/user";
import $Socket from "../../utils/socket";
import Vue from "vue";
// import $cookies from '../../utils/vue-cookies'

const defaultState = () => {
  return {
    userInfo: uni.getStorageSync("userInfo") || {},
    uid: uni.getStorageSync("uid") || "",
    ukey: uni.getStorageSync("ukey") || "",
    auditStatusInfo: uni.getStorageSync("auditStatusInfo") || {
      approval_invalid_col: [],
      approval_status: -4,
      approval_remark: "",
      id: 0,
    },
    approvalStatus: uni.getStorageSync("approvalStatus"),
    socket: {},
    getMsg: {},
    imWeidu: {},
    dashboardInfo: uni.getStorageSync("accountDashboard") || {
      data: {},
      notice: {},
      order: {},
      product: {
        illegal_num: 0,
        normal_num: 0,
        off_num: 0,
        total_num: 0,
        verify_passed_off_num: 0,
        verify_refused_num: 0,
        verify_waiting_num: 0,
      },
      return: {
        fin_num: 0,
        review_num: 0,
        total_num: 0,
        un_fin_num: 0,
      },
      store_info: {
        store_id: "",
        wx_qrcode: "",
      },
    },
  };
};

const state = defaultState();

const getters = {};

const mutations = {
  GET_LOGIN(state, { userInfo, auditStatusInfo }) {
    state.userInfo = userInfo;
    state.auditStatusInfo = auditStatusInfo;
  },
  LOGIN_OUT(state) {
    state.userInfo = {};
    state.uid = "";
    state.ukey = "";
    state.auditStatusInfo = {
      approval_invalid_col: [],
      approval_status: -4,
      approval_remark: "",
      id: 0,
    };
    state.approvalStatus = "";
    state.socket = {};
    state.getMsg = {};
    state.imWeidu = {};
    state.dashboardInfo = {};
  },
  CONNECT_SOCKET(state, { socket }) {
    state.socket = socket;
  },
  GET_IM_MSG(state, { msg }) {
    state.getMsg = msg;
    var im = {};
    let _imWeiDu = uni.getStorageSync("imWeiDu");
    if (_imWeiDu) {
      im = _imWeiDu;
    }

    if (!im[msg.id]) {
      im[msg.id] = { weidu: 0 };
    }
    im[msg.id].weidu += 1;
    im.userId = state.userInfo.user_id;
    state.imWeidu = im;
    uni.setStorageSync("imWeiDu", im);
  },
  REMOVE_IM_KEY(state, imId) {
    Vue.delete(state.imWeidu, imId);
    let imWeiDu = uni.getStorageSync("imWeiDu");
    if (!imWeiDu && !imWeiDu[imId]) return;
    delete imWeiDu[imId];
    uni.setStorageSync("imWeiDu", imWeiDu);
  },
};

const actions = {
  async GetAccountLogin({ dispatch }, params) {
    // #ifdef APP-PLUS

    const platform = uni.getSystemInfoSync().platform;
    var push_clientid = "";
    var osType = "";

    push_clientid = await getPushClientId();

    if (platform == "android") {
      osType = 1;
    } else {
      osType = 2;
    }

    params.cid = push_clientid;
    params.osType = osType;

    // #endif

    params.cid = "ae9c4517a4ae17ea33570839a0f5fdba";
    params.osType = 1;

    const res = await GetAccountLogin(params);

    console.log(res);

    if (res && res.status == 200) {
      let mobile = "";

      mobile = res.data.user_mobile.startsWith("+86")
        ? res.data.user_mobile.replace("+86", "")
        : res.data.user_mobile;

      const userInfo = res.data;

      uni.setStorageSync("uid", res.data.user_id);
      uni.setStorageSync("ukey", res.data.key);
      uni.setStorageSync("userInfo", res.data);

      await dispatch("checkAccountIsPass", {
        mobile: mobile,
        userInfo: userInfo,
      });

      await dispatch("connectSocket", res.data);
    }
  },
  async GetLogin({ dispatch }, params) {
    // #ifdef APP-PLUS

    const platform = uni.getSystemInfoSync().platform;
    var push_clientid = "";
    var osType = "";

    push_clientid = await getPushClientId();

    if (platform == "android") {
      osType = 1;
    } else {
      osType = 2;
    }

    params.cid = push_clientid;
    params.osType = osType;

    // #endif

    console.log("登录时的params", params);

    const res = await GetLogin(params);

    if (res && res.status == 200) {
      let mobile = "";

      mobile = res.data.user_mobile.startsWith("+86")
        ? res.data.user_mobile.replace("+86", "")
        : res.data.user_mobile;

      const userInfo = res.data;

      uni.setStorageSync("uid", res.data.user_id);
      uni.setStorageSync("ukey", res.data.key);
      uni.setStorageSync("userInfo", res.data);

      await dispatch("checkAccountIsPass", {
        mobile: mobile,
        userInfo: userInfo,
      });

      await dispatch("connectSocket", res.data);
    }
  },
  async LoginOut({ commit }, isTokenExpires) {
    if (isTokenExpires) {
      await OutLogin();

      uni.removeStorageSync("ukey");
      uni.removeStorageSync("uid");
      uni.removeStorageSync("accountDashboard");
      uni.removeStorageSync("approvalStatus");
      uni.removeStorageSync("auditInfo");
      uni.removeStorageSync("auditId");
      uni.removeStorageSync("contractDownloadUrl");
      uni.removeStorageSync("pdfjs.history");
      uni.removeStorageSync("userInfo");
      uni.removeStorageSync("typeItem");
      uni.removeStorageSync("locationItem");
      uni.removeStorageSync("district_data");
      uni.removeStorageSync("auditItem");

      commit("LOGIN_OUT");

      uni.redirectTo({
        url: "/pages/login/login",
      });
      return;
    }

    uni.showModal({
      title: "退出登录",
      content: `您是否要退出登录？`,
      success: async (res) => {
        if (res.confirm) {
          await OutLogin();
          uni.removeStorageSync("ukey");
          uni.removeStorageSync("uid");
          uni.removeStorageSync("accountDashboard");
          uni.removeStorageSync("approvalStatus");
          uni.removeStorageSync("auditInfo");
          uni.removeStorageSync("auditId");
          uni.removeStorageSync("contractDownloadUrl");
          uni.removeStorageSync("pdfjs.history");
          uni.removeStorageSync("userInfo");

          commit("LOGIN_OUT");

          uni.redirectTo({
            url: "/pages/login/login",
          });
        } else if (res.cancel) {
        }
      },
    });
  },
  async checkAccountIsPass({ commit }, { mobile, userInfo }) {
    let res = await GetAuditStatus({ mobile: mobile });
    if (res && res.status == 200) {
      const auditStatusInfo = res.data;
      commit("GET_LOGIN", { userInfo, auditStatusInfo });
      const lastIM = uni.getStorageSync("imWeiDu");
      if (lastIM) {
        if (lastIM.userId != userInfo.user_id) {
          uni.removeStorageSync("imWeiDu");
        }
      }

      let {
        approval_status,
        store_status,
        has_ec_signed,
        has_apply_mer,
        has_apply_split,
        has_apply_receiver,
        has_bind_receiver,
      } = res.data;

      //2-未通过；3-待审核；4-未申请过；5-已提交审核; 21 拉卡拉审核未通过
      if ([2, 3, 5, 21].includes(approval_status)) {
        uni.navigateTo({
          url: "/pages/audit/checkAudit",
        });
        return;
      }

      if (approval_status == 4) {
        uni.navigateTo({
          url: "/pages/audit/shop1",
        });
        return;
      }

      // 1.
      // 合同签署待办
      // 触发条件：approval_status=5 且 has_ec_signed=2 且 lkl_ec_result_url 非空
      // 页面显示：
      // 操作按钮：签署合同（跳转至拉卡拉签约页）
      // 提示信息："您的入驻材料已通过审核，请于 24 小时内完成合同签署（超时需重新提交），以便继续完成入驻流程"

      // 2.
      // 合同签署结果
      // 成功状态：approval_status=5 且 has_ec_signed=1 且 has_apply_mer=2
      // 提示信息："合同签署完成，商家信息正在提交审核，请耐心等待"
      // 失败状态：approval_status=21||2 且 has_ec_signed=2
      // 操作按钮：联系管理员（IM）
      // 提示信息："合同签署异常，请联系客服协助处理"

      // 3.
      // 商家进件审核结果
      // 成功状态：approval_status=5 且 has_apply_mer=1 且 store_status=2
      // 操作按钮：创建店铺
      // 提示信息："商家资质审核通过，系统正在初始化店铺，请稍后操作"
      // 失败状态：approval_status=21||2 且 has_apply_mer=2 且 has_ec_signed=1
      // 操作按钮：联系管理员（IM）
      // 提示信息："商家进件审核未通过，请联系客服获取详情"

      // 4.
      // 店铺创建结果
      // 成功状态：approval_status=5 且 has_apply_mer=1 且 store_status=1 且 has_apply_split=2
      // 提示信息："店铺创建成功，系统正在处理分账业务申请"
      // 失败状态：approval_status=21/2 且 has_apply_mer=1 且 store_status=2
      // 操作按钮：联系管理员（IM）
      // 提示信息："店铺初始化失败，请联系客服处理"

      // 5.
      // 分账业务申请结果
      // 成功状态：approval_status=5 且 store_status=1 且 has_apply_split=1 且 has_bind_receiver=2
      // 提示信息："分账业务申请已通过，系统正在处理接收方绑定"
      // 失败状态：approval_status=21||2 且 has_apply_split=2 且 store_status=1
      // 操作按钮：联系管理员（IM）
      // 提示信息："分账业务审核未通过，请联系客服获取详情"

      // 6.
      // 分账接收方绑定结果
      // 成功状态：approval_status=1||5 且 has_apply_split=1 且 has_bind_receiver=1
      // 提示信息："分账接收方绑定成功，入驻流程即将完成"
      // 失败状态：approval_status=21||2 且 has_bind_receiver=2 且 has_apply_split=1
      // 操作按钮：联系管理员（IM）
      // 提示信息："分账接收方审核未通过，请联系客服处理"

      // 7.
      // 入驻完成
      // 触发条件：approval_status=1 且 has_ec_signed=1 且 has_apply_mer=1 且 store_status=1 且 has_apply_split=1 且 has_bind_receiver=1
      // 提示信息："恭喜您，入驻流程已全部完成！"

      if (
        store_status == 2 ||
        has_ec_signed == 2 ||
        has_apply_mer == 2 ||
        has_apply_split == 2 ||
        has_apply_receiver == 2 ||
        (has_bind_receiver == 2 && approval_status == 1)
      ) {
        uni.navigateTo({
          url: "/pages/audit/checkAudit",
        });
        return;
      }

      //  store_status int   '店铺创建状态：1-已启用（入驻已审批，合同已生成）；2-未启用',
      if (
        approval_status == 1 &&
        store_status == 1 &&
        has_ec_signed == 1 &&
        has_apply_mer == 1 &&
        has_apply_split == 1 &&
        has_ec_signed == 1 &&
        has_apply_receiver == 1 &&
        has_bind_receiver == 1
      ) {
        let result = await GetAuditInfo({ mobile: mobile });

        uni.setStorageSync(
          "contractDownloadUrl",
          result.data.contract_download_url
        );
        uni.setStorageSync("auditId", result.data.id);
        uni.setStorageSync("auditInfo", result.data);

        uni.switchTab({
          url: "/pages/order/order",
        });
        return;
      }
    }
  },
  connectSocket({ commit }, userInfo) {
    if (!userInfo) return;
    var socket = new $Socket({
      url: userInfo.im.node_site_url,
      maxInterValCount: 5,
      interValTime: 20000,
      onClose: (res) => {
        console.log("sockrt关闭");
      },
      onOpen: (res) => {
        console.log("sockrt连接成功");
      },
      onMsg: (res) => {
        console.log("onMsg", res);
        if (res) {
          let msg = JSON.parse(res.data);
          commit("GET_IM_MSG", { msg });
        }
      },
    });
    socket.connectserver(userInfo.im);

    commit("CONNECT_SOCKET", { socket });
  },
};

function getPushClientId() {
  return new Promise((resolve, reject) => {
    uni.getPushClientId({
      success: (res) => {
        resolve(res.cid);
      },
      fail(err) {
        reject(err);
      },
    });
  });
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
