import Cookies from 'js-cookie'
import { Notification } from 'element-ui'
import { getCustomerType, getTravelAgencyType, getSystemConfigList } from '@/api/systemConfig'
import { getPayChannel } from '@/api/payChannel.js'
import { getSaleChannelList } from '@/api/order'
import { getAccountList, getSelf } from '@/api/systemSetting/account'
import { getTicketCategory, getTicketTypeList, getScenic } from '@/api/ticketType'
import { apiGetTravelAgencyList } from '@/api/travelAgency'
import { getBatchConfigList } from '@/api/batch'
import { getTermList } from '@/api/termManage'

const Store = require('electron-store')
const localStore = new Store()

const colorPalette = [
  '#C1232B', '#27727B', '#dcb309', '#E87C25', '#B5C334',
  '#FE8463', '#9BCA63', '#FAD860', '#F3A43B', '#60C0DD',
  '#8731e2', '#7bab05', '#f79007', '#F0805A', '#26C0C0'
]

const app = {
  state: {
    diffTime: 0,
    scaleRate: 1,
    editorElement: null, // 正在编辑的打印对象
    localConfig: null,
    appStatus: {
      status: 1,
      process: 0
    },
    account: {},
    client: null,
    sellerDevice: null,
    sidebar: {
      opened: !+Cookies.get('sidebarStatus'),
      withoutAnimation: false
    },
    device: 'desktop',
    language: Cookies.get('language') || 'zh',
    currentTicket: null,
    printList: [],
    printOrder: null,
    batchList: [], // 场次列表
    performList: [], // 节目列表
    smallTicketTemplate: null,
    smallTicketTemplateList: [],
    printTemplate: null,
    printTemplateList: [],
    payChannelOptions: [],
    payChannelList: [],
    termList: [],
    ticketCategory: [
      {
        id: 'ticket',
        name: '景区门票'
      },
      {
        id: 'member',
        name: '年卡次卡'
      // },
      // {
      //   id: 'batch',
      //   name: '场次售票'
      }
    ],
    ticketTypeList: [],
    customerType: [],
    saleChannel: [],
    systemConfig: [],
    agencyList: [],
    scenicList: [],
    scenicColor: {},
    accountList: [],
    terminalNO: localStore.get('termId'),
    customLogo: require(`imgs/${process.env.VUE_APP_LOGO || 'logo'}.png`),
    faceModelIsReady: false // 人脸模型已预热完成
  },
  mutations: {
    SET_FACE_MODEL_READY (state, val) {
      state.faceModelIsReady = val
    },
    SET_TERMAINAL_NO (state, data) {
      state.terminalNO = data
    },
    SET_SYSTEM_CONFIG (state, data) {
      state.systemConfig = data
    },
    SET_BATCH_LIST (state, data) {
      state.batchList = data
    },
    SET_PERFORM_LIST (state, data) {
      state.performList = data
    },
    SET_SALE_CHANNEL (state, data) {
      state.saleChannel = data
    },
    SET_MY_ACCOUNT (state, data) {
      state.myAccount = data
    },
    SET_ACCOUNT_LIST (state, data) {
      state.accountList = data || []
    },
    SET_TERM_LIST (state, data) {
      state.termList = data
    },
    SET_CUSTOM_LOGO (state, data) {
      state.customLogo = data
    },
    SET_SELLER_DEVICE (state, data) {
      state.sellerDevice = data
    },
    SET_TICKET_CATEGORY (state, data) {
      state.ticketCategory = data
    },
    SET_TICKET_TYPE_LIST (state, data) {
      state.ticketTypeList = data
    },
    SET_PAY_CHANNEL (state, { data, list }) {
      state.payChannelList = list
      state.payChannelOptions = data

      localStore.set('payChannelOptions', data)
    },
    SET_PRINT_LIST (state, data) {
      state.printList = state.printList.concat(data)
    },
    // 打印小票订单
    SET_PRINT_ORDER (state, data) {
      state.printOrder = data
    },
    PRINT_NEW (state, data) {
      state.printList.shift() // 移除已打印成功的门票
    },
    // 设置当前要打印的门票
    SET_CURRENT_TICKET (state, data) {
      state.currentTicket = data
    },
    // 设置与服务器的时间差
    SET_DIFF_TIME (state, data) {
      state.diffTime = new Date(data) - new Date()
    },
    SET_LOCAL_CONFIG (state, config) {
      state.localConfig = config
    },
    TOGGLE_SIDEBAR: state => {
      if (state.sidebar.opened) {
        Cookies.set('sidebarStatus', 1)
      } else {
        Cookies.set('sidebarStatus', 0)
      }
      state.sidebar.opened = !state.sidebar.opened
      state.sidebar.withoutAnimation = false
    },
    CLOSE_SIDEBAR: (state, withoutAnimation) => {
      Cookies.set('sidebarStatus', 1)
      state.sidebar.opened = false
      state.sidebar.withoutAnimation = withoutAnimation
    },
    TOGGLE_DEVICE: (state, device) => {
      state.device = device
    },
    SET_LANGUAGE: (state, language) => {
      state.language = language
      Cookies.set('language', language)
    },
    SHOW_ROOM: (state, room) => {
      state.dialogVisible = true
      state.globleRoom = room
    },
    HIDE_ROOM: (state) => {
      state.dialogVisible = false
    },
    SHOW_WXNOTIFY: (state) => {
      // if (state.wxNoify.visible) return
      console.log(Notification)
      state.wxNoify = Notification.info({
        iconClass: 'iconfont icon-auth',
        title: '提醒',
        dangerouslyUseHTMLString: true,
        customClass: 'authNotify',
        duration: 0,
        message: `有新的待授权用户需处理`,
        position: 'bottom-right'
      })
    },
    UPDATE_APP: (state, data) => {
      state.appStatus = data
    },
    SET_CUR_EDITOR_ELEMENT: (state, data) => {
      state.editorElement = data
    },
    SCALE_CANVAS: (state, data) => {
      state.scaleRate = data
    },
    SET_SMALL_TICKET_TEMPLATE: (state, data) => {
      state.smallTicketTemplate = data
    },
    SET_SMALL_TICKET_TEMPLATE_LIST: (state, data) => {
      state.smallTicketTemplateList = data
    },
    SET_PRINT_TEMPLATE: (state, data) => {
      state.printTemplate = data
    },
    SET_PRINT_TEMPLATE_LIST: (state, data) => {
      state.printTemplateList = data
    },
    SET_customerType: (state, data) => {
      state.customerType = data
    },
    SET_TRAVEL_AGENCY_TYPE: (state, data) => {
      state.travelAgencyType = data
    },
    SET_AGENCY_LIST: (state, data) => {
      state.agencyList = data
    },
    SET_SCENIC_LIST: (state, data) => {
      state.scenicList = data
    },
    SET_ACCOUNT: (state, data) => {
      state.account = data
    },
    SET_SCENIC_COLOR: (state, data) => {
      state.scenicColor = data
    }
  },
  actions: {
    getAccount ({ commit }) {
      getSelf().then(res => {
        commit('SET_ACCOUNT', res)
      })
    },
    getScenicList ({ commit }) {
      getScenic().then(res => {
        let scenicList = res?.data?.records || []

        let scenicColor = {}
        scenicList.forEach((s, i) => {
          scenicColor[s.id] = colorPalette[i % 15]
        })
        commit('SET_SCENIC_COLOR', scenicColor)
        commit('SET_SCENIC_LIST', scenicList)
      })
    },
    getBatchConfigList ({ commit }) {
      return getBatchConfigList({
        pageNum: 0,
        pageSize: -1
      }).then(res => {
        commit('SET_BATCH_LIST', res.data.records)
      })
    },
    getAgencyList ({ commit }) {
      return apiGetTravelAgencyList({
        pageNum: 0,
        pageSize: -1,
        keyWords6: 1
      }).then(res => {
        commit('SET_AGENCY_LIST', res.data.records)
      })
    },
    getSystemConfigList ({ commit }) {
      getSystemConfigList({}).then(res => {
        commit('SET_SYSTEM_CONFIG', res.data.records)
      })
    },
    getSaleChannel ({ commit }) {
      getSaleChannelList().then(res => {
        commit('SET_SALE_CHANNEL', res?.data)
      })
    },
    getMyAccount ({ commit, rootState }) {
      getAccountList({
        pageNum: 0,
        pageSize: -1
      }).then(res => {
        let target = res.data.records.find(i => i.nickName === rootState.user.name)
        commit('SET_ACCOUNT_LIST', res.data.records)
        commit('SET_MY_ACCOUNT', target)
      })
    },
    getTermDevices ({ commit }) {
      getTermList({
        pageNum: 0,
        pageSize: -1
      }).then(res => {
        commit('SET_TERM_LIST', res.data.records)
      })
    },
    getPayChannel ({ commit }) {
      return getPayChannel({
        pageNum: 0,
        pageSize: -1,
        keyWords1: '',
        type: ''
      }).then(res => {
        const target = res.data.records?.filter(i => i.status === 1).map(i => i.name)
        commit('SET_PAY_CHANNEL', { data: target, list: res.data.records?.filter(i => i.status === 1) })
      })
    },
    setCustomerType ({ commit }) {
      return getCustomerType().then(res => {
        commit('SET_customerType', res)
      })
    },
    setTravelAgencyType ({ commit }) {
      return getTravelAgencyType().then(res => {
        commit('SET_TRAVEL_AGENCY_TYPE', res)
      })
    },
    getTicketCategory ({ commit }) {
      return getTicketCategory().then(res => {
        commit('SET_TICKET_CATEGORY', res.data.records)
      })
    },
    getTicketTypeList ({ commit }) {
      return getTicketTypeList({
        pageNum: 0,
        pageSize: -1
      }).then(res => {
        commit('SET_TICKET_TYPE_LIST', res.data.records)
      })
    },
    setLocalConfig ({ commit }, data) {
      let configFile = require('path').join('C://', 'config.json')
      let fs = require('fs')
      fs.open(configFile, 'r', (err, data) => {
        if (err) {
          console.log(err)
          return
        }
        let configData = JSON.parse(fs.readFileSync(configFile))
        commit('SET_LOCAL_CONFIG', configData)
        console.log(configData)
      })
    },
    updateApp ({ commit }, data) {
      commit('UPDATE_APP', data)
    },
    toggleSideBar ({ commit }) {
      commit('TOGGLE_SIDEBAR')
    },
    closeSideBar ({ commit }, { withoutAnimation }) {
      commit('CLOSE_SIDEBAR', withoutAnimation)
    },
    toggleDevice ({ commit }, device) {
      commit('TOGGLE_DEVICE', device)
    },
    setLanguage ({ commit }, language) {
      commit('SET_LANGUAGE', language)
    },
    showRoom ({ commit }, room) {
      commit('SHOW_ROOM', room)
    },
    hideRoom ({ commit }) {
      commit('HIDE_ROOM')
    },
    scaleCanvas ({ commit }, data) {
      commit('SCALE_CANVAS', data)
    },
    setEditorElement ({ commit }, element) {
      commit('SET_CUR_EDITOR_ELEMENT', element)
    }
  }
}

export default app
