import {defineStore} from "pinia";
import storage from "@/utils/storage";
import platform from "@/utils/platform";
import {getSystemDeviceInfo} from "@/utils/getSystemDeviceInfo";
import {FileStorage} from "@/utils/fileStorage";
import {confirmModal, showToast} from "@/utils/app";
import * as dayjs from "@/utils/dayjs"
import {logs} from "@/utils/util";
import {calcStrHash} from "@/utils/machine/function";

const configUrl = '/storage/emulated/0/.TXZNMac.txt'
const fileStorage = new FileStorage()

export const useConfigStore = defineStore('config', {
  state: () => ({
    mac: null,
    mType: 7, // 7 BMI(默认)；8 肺活量；9 视力；
    mName: '',
    platform,
  }),
  getters: {},
  actions: {
    _init() {
      // this.platform = ()
      this.getMachineType()
      this.mType = 7
    },
    setMachineType(item) {
      storage.setKey('machineType', {
        name: item.name,
        type: item.type,
      })
    },
    getMachineType() {
      let info = storage.getKey('machineType')
      console.log('getMachineType', info)
      if (info) {
        this.mType = info.type
        this.mName = info.name
      }
    },

    async getMac() {
      return new Promise(async (resolve, reject) => {
        let config = await this.getConfig()
        console.log('config', config)
        let mac = config.mac ?? await this.createMac()
        console.log('config2', mac)
        if (mac) {
          resolve(mac)
        } else {
          reject(false)
        }
      })
    },

    async createMac() {
      let {imei} = await getSystemDeviceInfo()
      try {
        if (!imei) {
          // #ifdef APP-PLUS
          await confirmModal('无法获取设备imei，请联系管理员！', {
            showCancel: false,
          })
          plus.runtime.quit()
          // #endif
          // #ifdef H5
          showToast('无法获取设备imei，请联系管理员！')
          return false
          // #endif
        }
      } catch (e) {
        console.error('createMac 获取设备码失败')
        return false
      }
      let timestamp = dayjs().valueOf()
      let data = await this.getConfig()
      let a = calcStrHash(imei, 5)
      let b = calcStrHash(timestamp, 4)
      data.mac = `BMI${a}${b}`
      data.timestamp = timestamp
      data.imei = imei
      await this.getConfig(data)
      this.mac = data.mac
      return data.mac
    },


    async getConfig(data = false) {
      if (data) {
        fileStorage.storage(configUrl, (data || {}))
        return data
      }
      data = {}
      try {
        let info = await fileStorage.read(configUrl)
        if (info) data = info
      } catch (e) {
        fileStorage.storage(configUrl, {})
      }
      return data
    },

  }
})
