import Vue from 'vue';
import Vuex from 'vuex';
import { getConfig } from '../api/setting.js';
import { getUsbPrint } from '../api/shop.js';
import { getLodop } from "../common/LodopFuncs.js";

Vue.use(Vuex);

const state = {
  userInfo: JSON.parse(localStorage.getItem('userInfo')) || null,
  usbPrinter: JSON.parse(localStorage.getItem('usbPrinter')) || [],
  firstLogin: true
}

const actions = {
  getUserInfo(context) {
    getConfig().then(res => {
      if (res.code === 200) {
        context.commit('SET_USERINFO', res.data)
      } else {
        this.$message({
          type: 'error',
          message: res.msg
        })
      }
    })
  },
  getUsbPrint(context) {
    console.log('context', context.state.firstLogin);
    getUsbPrint().then(res => {
      if (res.code === 200) {
        let dataList = res.data
        setTimeout(() => {
          let data = []
          try {
            LODOP = getLodop('', '', context.state.firstLogin);
            let printerCount = LODOP.GET_PRINTER_COUNT();
            if (!printerCount) { return }
            let printerList = [];
            let list = ['OneNote for Windows 10','OneNote (Desktop)','Microsoft XPS Document Writer','Microsoft Print to PDF','Fax','导出为WPS PDF']
            for (let index = 0; index < printerCount; index++) {
              let deviceName = LODOP.GET_PRINTER_NAME(index)
              if(list.includes(deviceName))continue
              printerList.push({ deviceName:  deviceName});
            }
            data = printerList.map((v) => {
              let obj = dataList.find((ele) => {
                return ele.deviceName === v.deviceName;
              });
              if (obj) {
                v = obj;
              } else {
                v.openOrderPrint = 0;
                v.openOrderCancelPrint = 0;
                v.printCustomerCount = 1;
                v.printMerchantCount = 1;
                v.printKitchenCount = 1;
                v.width = 58;
              }
              return v;
            });
          } catch (error) {
            console.log(error);
          }
          context.commit('SET_USBPRINTER', data)
        }, 500);
      } else {
        this.$message({
          type: 'error',
          message: res.msg
        })
      }
    })
  }
}

const mutations = {
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
    // 防止页面刷新，导致Vuex重启
    localStorage.setItem('userInfo', JSON.stringify(userInfo));
  },
  SET_USBPRINTER: (state, usbPrinter) => {
    state.usbPrinter = usbPrinter
    state.firstLogin = false
    // 防止页面刷新，导致Vuex重启
    localStorage.setItem('usbPrinter', JSON.stringify(usbPrinter));
  },
  setFirstLogin: (state, firstLogin) => {
    state.firstLogin = firstLogin
  }
}

const getters = {
  userInfo: (state) => {
    return state.userInfo
  },
  usbPrinter: (state) => {
    return state.usbPrinter
  },
}

const store = new Vuex.Store({
  actions,
  mutations,
  state,
  getters
})

export default store;
