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

const defaultState = () => {
  return {
    userInfo: uni.getStorageSync('userInfo') || {
      user_mobile: '',
    },
    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'),
  };
};

const state = defaultState();

const getters = {};

const mutations = {
  GET_LOGIN(state, { userInfo, auditStatusInfo }) {
    state.userInfo = userInfo;
    state.auditStatusInfo = auditStatusInfo;
  },
  LOGIN_OUT(state) {
    state.ukey = '';
    state.uid = '';
    state.auditStatusInfo = {
      approval_invalid_col: [],
      approval_status: -4,
      approval_remark: '',
      id: 0,
    };
  },
};

const actions = {
  async GetAccountLogin({ commit }, params) {
    const res = await GetAccountLogin(params);

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

      let isContain = res.data.user_mobile.indexOf('86');

      if (isContain != -1 && res.data.user_mobile.length > 11) {
        mobile = res.data.user_mobile.slice(2);
      } else {
        mobile = res.data.user_mobile;
      }

      const result = await GetAuditStatus({ mobile: mobile });

      const userInfo = res.data;
      const auditStatusInfo = result.data;

      commit('GET_LOGIN', { userInfo, auditStatusInfo });

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

      // #ifdef H5
      $cookies.set('uid', res.data.user_id);
      $cookies.set('ukey', res.data.key);
      // #endif

      // 如果是管理员 或者 通过的商家直接登录
      if (res.data.user_is_admin == 1 || result.data.signed_status == 2) {
        uni.switchTab({
          url: '/pages/order/order',
        });
        return;
      }

      if ([1, 2, 3].includes(result.data.approval_status)) {
        uni.navigateTo({
          url: '/pages/audit/checkAudit',
        });
        return;
      }

      let approval_invalid_col = JSON.parse(result.data.approval_invalid_col);

      if (
        result.data.approval_status == 4 ||
        approval_invalid_col.includes('all')
      ) {
        uni.navigateTo({
          url: '/pages/audit/shop1',
        });
      }
    }
  },

  async GetLogin({ commit }, params) {
    const res = await GetLogin(params);

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

      let isContain = res.data.user_mobile.indexOf('86');

      if (isContain != -1 && res.data.user_mobile.length > 11) {
        mobile = res.data.user_mobile.slice(2);
      } else {
        mobile = res.data.user_mobile;
      }

      const result = await GetAuditStatus({ mobile: mobile });

      if (result && result.status == 200) {
        res.data.merch_approval_status = result.data.approval_status;
      }

      const userInfo = res.data;
      const auditStatusInfo = result.data;

      commit('GET_LOGIN', { userInfo, auditStatusInfo });

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

      // // #ifdef H5
      // $cookies.set("uid", res.data.user_id);
      // $cookies.set("ukey", res.data.key);
      // // #endif

      // 如果是管理员 或者 通过的商家直接登录
      if (res.data.user_is_admin == 1 || result.data.signed_status == 2) {
        uni.switchTab({
          url: '/pages/order/order',
        });
        return;
      }

      if ([1, 2, 3].includes(result.data.approval_status)) {
        uni.navigateTo({
          url: '/pages/audit/checkAudit',
        });
        return;
      }

      let approval_invalid_col = JSON.parse(result.data.approval_invalid_col);

      if (
        result.data.approval_status == 4 ||
        approval_invalid_col.includes('all')
      ) {
        uni.navigateTo({
          url: '/pages/audit/shop1',
        });
      }
    }
  },
  LoginOut({ commit }) {
    uni.showModal({
      title: '退出登录',
      content: `您是否要退出登录？`,
      success: async (res) => {
        if (res.confirm) {
          let res = await OutLogin();
          if (res && res.status == 200) {
            uni.removeStorageSync('ukey');
            uni.removeStorageSync('uid');
            uni.removeStorageSync('accountDashboard');
            uni.removeStorageSync('approvalStatus');
            uni.removeStorageSync('approvalStatusInfo');
            uni.removeStorageSync('auditInfo');
            uni.removeStorageSync('contractDownloadUrl');
            uni.removeStorageSync('pdfjs.history');
            uni.removeStorageSync('userInfo');

            commit('LOGIN_OUT');

            setTimeout(() => {
              uni.redirectTo({
                url: '/pages/index/index',
              });
            }, 100);
          }
        } else if (res.cancel) {
        }
      },
    });
  },
  // async checkAccountIsPass(mobile) {
  //   let res = await GetAuditStatus({ mobile: mobile });
  //   if (res && res.status == 200) {
  //     let { approval_status, signed_status, store_status } = res.data;

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

  //     // 合同签署状态：
  //     // -1：预备数据阶段；0-等待签署；1-已部分签署；
  //     // 2 - 已完成（所有签署方完成签署）3 - 已撤销（发起方撤销签署任务）
  //     // 5 - 已过期（签署截止日到期后触发）7 - 已拒签（签署方拒绝签署）',
  //     if (signed_status != 2) {
  //       uni.navigateTo({
  //         url: '/pages/audit/checkAudit',
  //       });
  //       return;
  //     }

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

  //       uni.setStorageSync(
  //         'contractDownloadUrl',
  //         result.data.contract_download_url
  //       );
  //       uni.setStorageSync('auditId', result.data.id);

  //       uni.switchTab({
  //         url: '/pages/order/order',
  //       });
  //       return;
  //     }
  //   }
  // },
};

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