/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
/* eslint-disable */
import axios from 'axios'
import _ from 'lodash'
import MyData from '../../../assets/myData'
import MaritalStatus from '../../../assets/staticData/maritalStatus'

export default {
    namespaced: true,
    state: {
        resorts: [],
        regions: [],
        detailedRegion: [],
        seasons: [],
        resortBedrooms: [],
        maxSleep: [],
        bankedEntities: [],
        agencies: [],
        agents: [],
        timeshareFilter: '',
        maritalStatus: MaritalStatus,
        result: undefined,
        latestWeeks: [],
        sellItem: {
            referedByAgent: false,
            agentId: undefined,
            agencyId: undefined,
            otherResort: false,
            otherResortName: undefined,
            resort: undefined,
            resortCode: undefined,
            resortName: undefined,
            region: undefined,
            regionId: undefined,
            season: undefined,
            module: undefined,
            unitNumber: undefined,
            bedrooms: undefined,
            maxSleep: undefined,
            weekNumber: undefined,
            levyAmount: undefined,
            weekType: undefined,
            currentYearBanked: false,
            bankedWith: undefined,
            leviesPaidInFull: false,
            weekPlacedForRental: false,
            originalPurchasePrice: undefined,
            originalPurchaseDate: undefined,
            arrivalDate: undefined,
            departureDate: undefined,
            sellPrice: undefined,
            agentCommission: undefined,
            mandate: undefined,
            status: undefined,
            consent: true,
            owner: {
                address: {},
                bankingDetails: {},
            },
        },
    },
    mutations: {
        setUnitConfigurationList(state, list) {
            state.unitConfigurationList = list
        },
        filterStore(state, input) {
            state.timeshareFilter = input
        },
        setAgency(state, jstimesharetype) {
            state.agencies = jstimesharetype
        },
        setAgent(state, jstimesharetype) {
            state.agents = jstimesharetype
        },
        setSeason(state, jstimesharetype) {
            state.seasons = jstimesharetype
        },
        setResortBedrooms(state, jstimesharetype) {
            state.resortBedrooms = jstimesharetype
        },
        setMaxSleep(state, jstimesharetype) {
            state.maxSleep = jstimesharetype
        },
        setBankedEntities(state, jstimesharetype) {
            state.bankedEntities = jstimesharetype
        },
        addResort(state, jstimesharetype) {
            state.resorts = jstimesharetype
        },
        addRegion(state, jstimesharetype) {
            state.regions = jstimesharetype
        },
        addDetailedRegion(state, jstimesharetype) {
            state.detailedRegion.push(jstimesharetype)
        },
        changeResort(state, resort) {
            for (const reg in state.detailedRegion) {
                const region = state.detailedRegion[reg]
                if (
                    _.find(region.children, (x) => x.resortCode === resort.resortCode)
                ) {
                    state.regionId = reg
                    break
                }
            }
            state.sellItem.resortCode = resort.resortCode
            state.sellItem.resortName = resort.resortName
        },
        displayResult(state) {
            state.result = 'Week has been added ^-^'
        },
        setWeekDetail(state, week) {
            state.sellItem = week
        },
        agentUpdate(state, agent) {
            var index
            var count = 0
            state.agents.forEach((item) => {
                if (item.id === agent.id) {
                    index = count
                }
                count++
            })
            Object.assign(state.agents[index], agent)
        },
        getLatestWeeks(state, data) {
            state.latestWeeks = data
        },
    },
    getters: {
        getRegionCode(state) {
            return (value) => {
                const reg = state.detailedRegion.find((region) =>
                    region.children.some((resort) => resort.resortCode === value),
                )
                if (reg && reg.region) {
                    return reg.region.regionCode
                }
                return ''
            }
        },
        getResortName(state) {
            return (value) => {
                const res = state.resorts.find((resort) => resort.resortCode === value)
                if (res) {
                    return res.resortName
                }
            }
        },
        getLatestWeeks: (state) => state.latestWeeks,
    },
    actions: {
        initTimeshare({ commit, dispatch }, timeshareId) {
            commit('setResortBedrooms', MyData.resortBedrooms)
            commit('setMaxSleep', MyData.maxBedrooms)
            commit('setBankedEntities', MyData.bankedEntities)
            dispatch('getSeasons')
            dispatch('getAgents')
            dispatch('getAgencies')
            dispatch('getResorts')
            dispatch('getRegions')
            if (timeshareId && timeshareId !== 0) {
                dispatch('getWeekDetail', timeshareId)
            }
        },
        updateFilter({ commit }, input) {
            commit('filterStore', input)
        },
        getWeekDetail({ commit }, timeshareId) {
            axios
                .get(`api/timeshareweek/${timeshareId}`)
                .then((result) => {
                    commit('setWeekDetail', result.data)
                })
                .catch(console.error)
        },
        getSeasons({ commit }) {
            axios
                .get('/api/season')
                .then((result) => commit('setSeason', result.data))
                .catch(console.error)
        },
        getAgencies({ commit }) {
            axios
                .get('/api/agency')
                .then((result) => commit('setAgency', result.data))
                .catch(console.error)
        },
        getAgents({ commit }) {
            axios
                .get('/api/agent')
                .then((result) => commit('setAgent', result.data))
                .catch(console.error)
        },
        getResorts({ commit }) {
            axios
                .get(
                    'https://www.tradeunipoint.com/unibackend/seam/resource/rest/products/resorts/list?disabled=true',
                )
                .then((result) => {
                    commit('addResort', result.data)
                        //console.log(result.data)
                })
                .catch(console.error)
        },
        getRegions({ dispatch, commit }) {
            axios
                .get(
                    'https://www.tradeunipoint.com/unibackend/seam/resource/rest/products/regions/list/ZA',
                )
                .then((result) => {
                    commit('addRegion', result.data)
                    dispatch('getDetailedRegion', result.data)
                })
                .catch(console.error)
        },
        getDetailedRegion({ commit }, data) {
            if (data) {
                for (const r in Object.keys(data)) {
                    const region = data[r]
                    if (region !== undefined) {
                        axios
                            .get(
                                `https://www.tradeunipoint.com/unibackend/seam/resource/rest/products/resorts/${region.regionCode}?disabled=true`,
                            )
                            .then((result) =>
                                commit('addDetailedRegion', {
                                    region,
                                    children: result.data,
                                }),
                            )
                            .catch(console.error)
                    }
                }
            }
        },
        async retrieveLatestWeeks({ commit }) {
            await axios.get('/api/timeshareWeek/GetLatest').then((result) => {
                commit('getLatestWeeks', result.data)
            })
        },
        onResortChange({ commit }, resort) {
            commit('changeResort', resort)
        },
        async saveWeek({ commit }, week) {
            return await new Promise((resolve, reject) => {
                axios
                    .post('/api/timeshareweek', week)
                    .then((result) => {
                        commit('setWeekDetail', result.data)
                        resolve(result.data)
                    })
                    .catch((error) => {
                        if (error.response) {
                            reject(error.response)
                        }
                    })
            })

            // axios
            //   .post('/api/timeshareweek', week)
            //   .then(result => commit('displayResult'))
            //   .catch(console.error);
        },
        getBlankWeek({ commit }) {
            axios
                .get('/api/timeshareweek/gettemplate')
                .then((result) => commit('setWeekDetail', result.data))
                .catch(console.error)
        },
        async updateAgent({ commit }, agent) {
            await axios
                .put('/api/agent', agent)
                .then((result) => {
                    commit('agentUpdate', result.data)
                })
                .catch((ex) => {
                    console.log(ex)
                })
        },
    },
}