import moment from "moment/moment";
import {ProductOptionService} from "../common/api";
import {ProductService} from "../common/api";
import {
    PRODUCT_CREATE,
    PRODUCT_LIST,
    PRODUCT_LIST_ALL,
    PRODUCT_DETAIL,
    PRODUCT_GET_OPTION,
    PRODUCT_CREATE_OPTION,
    PRODUCT_UPDATE_OPTION,
    PRODUCT_DELETE_OPTION,
    PRODUCT_UPDATE,
    PRODUCT_DELETE_IMAGE,
    PRODUCT_UPDATE_IMAGE,
    PRODUCT_DELETE,
    PRODUCT_ADD_IMAGE,
    PRODUCT_UPDATE_OPTION_FROM_LIST,
    PRODUCT_DELETE_LIST,
    API,
    PRODUCT_PUSH_TO_COLLECTION,
} from "./action_type";

import {
    SET_ERROR,
    SET_PRODUCT,
    SET_PRODUCT_ALL,
    SET_PRODUCT_DETAIL,
    SET_PRODUCT_OPTION,
    CLEAR_PRODUCT_DETAIL,
    START_LOADING,
    STOP_LOADING
} from "./mutation_type";
import trapFocusMixin from "vue-loading-overlay/src/js/trapFocusMixin";
import {use} from "element-ui/src/locale";

const state = {
    products: {},
    productOptions: {
        location: [],
        category: [],
        style: [],
        color: [],
        tag: [],
    },
    product: null,
    productAll: null,
};

const startLoading = function (commit) {
    commit(START_LOADING);
};

const stopLoading = function (commit) {
    commit(STOP_LOADING);
};

const getters = {
    products: state => {
        if (state.products) {
            return state.products;
        }

    },

    product: state => {
        if (state.product) {
            if(state.product.userOptions){

                state.product.userOptions.forEach(userOption=>{
                    if(userOption.values){
                        // let tmpValue = [];
                        // // userOption.values.forEach(value=>{
                        // //     tmpValue.push({text:value.name});
                        // // });
                        // userOption.values = tmpValue;
                    }
                });
            }
            return state.product;
        }
    },

    productOptions: state => {
        if (state.productOptions) {
            return state.productOptions;
        }
        return null;
    },

    productOptionsOriginal: state => {
        if (state.productOptions) {
            return state.productOptions;
        }
        return null;
    }
};

const actions = {
    async [PRODUCT_LIST_ALL]({dispatch, commit}) {
        const call = ProductService.listAll();
        const {result} = await dispatch(API, {call});
        commit(SET_PRODUCT_ALL, result);
    },

    async [PRODUCT_LIST]({commit,dispatch}, pageParameter) {
        const call =ProductService.list(pageParameter);
        const {result} = await dispatch(API,{call});
        commit(SET_PRODUCT, result);
    },

    async [PRODUCT_DETAIL]({commit}, id) {
        commit(CLEAR_PRODUCT_DETAIL);
        startLoading(commit);
        try {
            const {data} = await ProductService.detail(id);
            commit(SET_PRODUCT_DETAIL, data);
        } catch (e) {
            commit(SET_ERROR, e);
        }
        stopLoading(commit);
    },

    //상품 생성
    [PRODUCT_CREATE]({commit}, product) {
        return new Promise(async (resolve, reject) => {
            commit(START_LOADING);
            try {
                const {data} = await ProductService.create(product);
                resolve(data);
            } catch (e) {
                commit(SET_ERROR, e);
                reject(e);
            }
            commit(STOP_LOADING);
        });

    },

    async [PRODUCT_PUSH_TO_COLLECTION]({dispatch}, {productId, collectionIds}){
        console.log(productId);
        console.log(collectionIds);
        // const call = ProductService.pushCollection(productId,collectionIds);
        // return dispatch(API,{call});
    },

    async [PRODUCT_UPDATE]({commit}, product) {
        return new Promise((async (resolve, reject) => {
            startLoading(commit);
            try {
                await ProductService.update(product);
                resolve();
            } catch (e) {
                reject(e);
                commit(SET_ERROR, e);
            }
            stopLoading(commit);
        }))
    },

    async [PRODUCT_DELETE]({commit}, id) {
        return new Promise(async (resolve, reject) => {
            commit(START_LOADING);
            try {
                await ProductService.delete(id);
                resolve();
            } catch (e) {
                reject(e);
                commit(SET_ERROR, e);
            }
            commit(STOP_LOADING);
        });
    },

    [PRODUCT_UPDATE_OPTION_FROM_LIST]({commit, dispatch}, param) {
        return new Promise(async (resolve, reject) => {
            startLoading(commit);
            try {
                await ProductService.updateOptionFromList(param);
                resolve();
            } catch (e) {
                reject(e);
                commit(SET_ERROR, e);
            }
            stopLoading(commit);
        });
    },
    [PRODUCT_DELETE_LIST]({dispatch, commit}, productIds) {
        console.log("delete list");

        return new Promise(async (resolve, reject) => {
            try {
                const call = ProductService.deleteAll(productIds);
                const result = await dispatch(API, {call});
                resolve(result);
            } catch (e) {
                reject(e);
            }
        })
    },

    [PRODUCT_ADD_IMAGE]({commit, dispatch}, {product_id, url}) {
        return new Promise(async (resolve, reject) => {
            startLoading(commit);
            try {
                await ProductService.addImage(product_id, url);
                dispatch(PRODUCT_DETAIL, product_id);
                resolve();
            } catch (e) {
                commit(SET_ERROR, e);
                reject(e);
            }
            stopLoading(commit);
        });
    },

    async [PRODUCT_UPDATE_IMAGE]({commit}, {product_id, image_id, url}) {
        return new Promise(async (resolve, reject) => {
            startLoading(commit);
            try {
                const {result} = await ProductService.updateImage(product_id, image_id,
                    url);
                resolve(result);
            } catch (e) {
                commit(SET_ERROR, e);
                reject(e);
            }
            stopLoading(commit);
        })
    },

    async [PRODUCT_DELETE_IMAGE]({commit, dispatch}, {product_id, image_id}) {

        return new Promise(async (resolve, reject) => {
            startLoading(commit);
            try {
                const {result} = await ProductService.deleteImage(product_id, image_id);
                dispatch(PRODUCT_DETAIL, product_id);
                resolve(result);
            } catch (e) {
                commit(SET_ERROR, e);
                reject(e);
            }
            stopLoading(commit);
        })
    },

    /**
     *
     * 상품 옵션
     * CURD
     *
     */
    async [PRODUCT_GET_OPTION]({commit}) {
        return new Promise(async (resolve, reject) => {
            commit(START_LOADING);
            try {
                const {data} = await ProductOptionService.list();
                commit(SET_PRODUCT_OPTION, data);
                commit(STOP_LOADING);
                resolve(data);
            } catch (e) {
                commit(SET_ERROR, e);
                reject(e);
            }
            commit(STOP_LOADING);
        });

    },

    //C
    async [PRODUCT_CREATE_OPTION]({commit, dispatch}, data) {
        commit(START_LOADING);
        try {
            await ProductOptionService.created(data);
            await dispatch(PRODUCT_GET_OPTION);
        } catch (e) {
            commit(SET_ERROR, e);
        }
        commit(STOP_LOADING)
    },

    //U
    [PRODUCT_UPDATE_OPTION](context, option) {
        return new Promise((async (resolve, reject) => {
            context.commit(START_LOADING);
            try {
                await ProductOptionService.update(option);
                resolve("ok");
            } catch (e) {
                reject(e);
                context.commit(SET_ERROR, e);
            }
            context.commit(STOP_LOADING);
        }));

    },

    //D
    [PRODUCT_DELETE_OPTION]({commit, dispatch}, id) {
        return new Promise((async (resolve, reject) => {
            commit(START_LOADING);
            try {
                await ProductOptionService.delete(id);
                await dispatch(PRODUCT_GET_OPTION);
                resolve("ok");
            } catch (e) {
                reject(e);
                commit(SET_ERROR, e);
            }
            commit(STOP_LOADING);
        }));
    },

};

const mutations = {
        [SET_PRODUCT](state, products) {
            if (Array.isArray(products.content)) {
                products.content.forEach(item => {
                    item.createdAt = moment(item.createdAt).format('YYYY MM DD');
                });
            }



            state.products = products;
        },

        [SET_PRODUCT_ALL](state, productAll) {
          state.productAll = productAll;
        },

        [SET_PRODUCT_DETAIL](state, product) {
            product.userOptions.forEach(userOption=>{
                if(userOption.values){
                    const tmpValue = [];
                    userOption.values.forEach(value=>{
                        tmpValue.push({text:value.name});
                    });
                    userOption.values = tmpValue;
                }
            });
            state.product = product
        },

        [SET_PRODUCT_OPTION](state, options) {
            state.productOptions = options;
        },

        [CLEAR_PRODUCT_DETAIL](state) {
            state.product = null;
        }

    }
;

export default {
    state,
    getters,
    actions,
    mutations
}
