import { max, sortBy } from 'lodash'
import http from '../../../api/fastposter'

export function uniqueId(len = 8, radix) {
    let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    let uuid = [], i;
    radix = radix || chars.length;
    if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
        let r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }
    return uuid.join('');
}

const template = {
    name: '未命名',
    id: 0,
    w: 750,
    h: 1333,
    use: 'bgUrl',
    bgc: '#fafbfc',
    bgUrl: '',
    type: 'jpeg',
    quality: 80,
    scale: 0.5,
    key: uniqueId(),
    items: []
}

const state = {
    p: {...template}
}

const getters = {
    w() {
        return state.p.w;
    },
    h() {
        return state.p.h;
    },
    ai() {
        let ai = state.p.items.filter(a => a.active);
        return ai.length >= 1 ? ai[0] : undefined;
    },
    maxZ() {
        return state.p.items.length >= 1 ? max(state.p.items.map(a => a.z)) : 1;
    },
    scale() {
        return state.p.scale
    }
}

const actions = {
    createPoster({commit}) {
        let poster = JSON.parse(JSON.stringify(template));
        commit('loadPoster', poster);
    },
    savePoster() {
        return new Promise((resolve) => {
            let p = state.p;
            let params = {
                ...p
            }
            if (p.id === 0) {
                http.savePoster(params, r => {
                    if (r.code === 0 && r.data.poster) {
                        p.id = r.data.poster.id;
                        // p.code = r.data.poster.code
                        p.uuid = r.data.poster.uuid
                    }
                    resolve(r)
                })
            } else {
                http.updatePoster(params, r => {
                    resolve(r)
                })
            }
        });
    },


    loadPoster({commit}, id) {
        return new Promise((resolve) => {
            http.loadPoster(id, r => {
                let poster = r.data.poster
                let p = JSON.parse(poster.json)
                p.id = id
                p.uuid = poster.uuid
                commit('loadPoster', p)
                // 加载字体
                p.items.filter(item => item.fn !== '').forEach(item => http.loadfont(item.fn))
                resolve(r)
            })
        });
    },

    getPoster({commit}, id) {
        return new Promise((resolve) => {
            http.loadPoster(id, r => {
                let poster = r.data.poster
                let p = JSON.parse(poster.json)
                p.id = poster.id
                resolve(p)
            })
        });
    },

    copyPoster({commit}, id) {
        return new Promise((resolve) => {
            http.copyPoster(id, r => {
                resolve(r)
            })
        });
    },

    removePoster({commit}, id) {
        return new Promise((resolve) => {
            http.removePoster(id, r => {
                resolve(r)
            })
        });
    },
    previewPoster() {
        return new Promise((resolve) => {
            let params = state.p;
            http.previewPoster(params, r => {
                resolve(r)
            })
        });
    },

    shrink({commit}) {
        commit('changeScale', -0.1)
    },
    magnify({commit}) {
        commit('changeScale', 0.1)
    },
    isTextEdit({ commit },bool) {
      commit('isTextEdit', bool)
    },
  
}
const mutations = {

    changeScale(state, num) {
        if (state.p.scale <= 0.35) {
            num = num / 10
        }
        if ((state.p.scale <= 0.05 && num < 0) || (state.p.scale >= 3 && num > 0)) {
            console.warn('已到极致缩放比: ', state.p.scale);
            return;
        }
        let scale = state.p.scale + num
        if (scale === 0.36) {
            scale = 0.4
        }
        state.p.scale = Number(scale.toFixed(2));    // 强制截取
    },
    loadPoster(state, poster) {
        let z = 0
        poster.items.forEach(a => {
            a.active = false
            // 处理默认值问题
            if (typeof a.lock === 'undefined') {
                a.lock = false;
            }
            if (typeof a.angle === 'undefined') {
                a.angle = 0;
            }
            if (typeof a.aspectRatio === 'undefined') {
                a.aspectRatio = false;
            }
            if (typeof a.vs === 'undefined') {
              a.vs = 0
            }
            if (typeof a.bool === 'undefined') {
              a.bool = false
            }
      
            // 文本对齐方式 align
            if (a.t === 'text') {
                if (typeof a.a === 'undefined') {
                    a.a = 'left'
                }
                if (typeof a.wrap === 'undefined') {
                    a.wrap = true
                }
                if (typeof a.bius === 'undefined' || !a.bius) {
                    a.bius = ''
                }
              
                // 字间距
                if (typeof a.ls === 'undefined' || !a.ls) {
                    a.ls = 0
                }
            }
            a.z = ++z
        })
        // 处理历史数据
        if (typeof poster.editor !== 'undefined') {
            delete poster['editor']
        }
        if (typeof poster.use === 'undefined') {
            poster.use = poster.bgUrl ? 'bgUrl' : 'bgc';
        }
        if (typeof poster.key === 'undefined') {
            poster.key = uniqueId()
        }
        if (!poster.scale) {
            poster.scale = 0.5
        }
        state.p = poster
    },
    setActiveItemId(state, uuid) {
        state.p.items.filter(a => a.active && a.uuid !== uuid).forEach(a => a.active = false)
        state.p.items.filter(a => a.uuid === uuid).forEach(a => a.active = true)
    },
    setUnActiveItemId(state, uuid) {
        state.p.items.filter(a => a.uuid === uuid).forEach(a => a.active = false)
    },
    setUnActiveAllItem(state) {
        state.p.items.forEach(a => a.active = false)
    },
    addItem(state, item) {
        if (state.p.items.length >= 100) {
            console.warn('元素超过最数量: ', state.p.items.length)
            return;
        }
        this.commit('poster/setUnActiveAllItem')
        let z = state.p.items.length >= 1 ? getters.maxZ() + 1 : 1;       // 计算最大层级

        // TODO: 计算元素位置，在编辑器中心点出现

        let t = {
            "t": item.t,
            "name": item.name,
            "uuid": uniqueId(),
            "x": item.x ? item.x : 100,
            "y": item.y ? item.y : 100,
            "w": item.w ? item.w : 200,
            "h": item.h ? item.h : 200,
            "z": z,
            "angle": item.angle ? item.angle : 0,
            "s": item.s ? item.s : 30,
            "c": item.c ? item.c : "#000000",
            "bgc": item.bgc ? item.bgc : "",
            "v": item.v,
            "vs": item.vs ? item.vs : 0,
            "vd": item.vd ? item.vd : "",
            "fn": item.fn ? item.fn : "",
            "st": item.st ? item.st : 0,
            "active": true,
            "lock": false,
            "aspectRatio": false,
            'bool':false,
        };
        if (typeof item.p !== 'undefined') {
            t['p'] = item.p
        }

        if (item.t === 'qrcode' || item.t === 'avatar' || item.t === 'image') {
            t.aspectRatio = true
        }

        if (item.t === 'text') {
            t.a = item.a ? item.a : 'left'
            t.fn = item.fn ? item.fn : '01/0d44d315557a4a25.woff'
            t.wrap = true
            t.bius = item.bius ? item.bius : ''
            t.ls = item.ls ? item.ls : 0
        }
        state.p.items.push(t);
    },

    removeActiveItem(state) {
        let items = state.p.items.filter(a => !a.active);
        let z = 0
        items.forEach(item => {
            item.z = ++z
        })
        state.p.items = items
    },

    copyActiveItem(state, activeItem) {
        let t = JSON.parse(JSON.stringify(activeItem));
        // t.x += 20;
        t.y += 20;
        this.commit('poster/addItem', t)
    },
    changeActiveItem(state, activeItem) {
      for (let i = 0; i < state.p.items.length; i++) {
        if (state.p.items[i].active) {
          state.p.items[i].x =Math.round(activeItem.x / state.p.scale) 
          state.p.items[i].y = Math.round(activeItem.y / state.p.scale)
          state.p.items[i].w = Math.round(activeItem.width / state.p.scale)
          state.p.items[i].h = Math.round(activeItem.height / state.p.scale)
          state.p.items[i].angle = activeItem.rotate
          if (state.p.items[i].t === 'text'&&activeItem.s) {
            state.p.items[i].s = activeItem.s
          }
          return
        }
      }
    },
    changePosterSize(state, {w, h}) {
        state.p.w = w;
        state.p.h = h;
    },

    top(state, item) {
        let t = getters.maxZ();
        state.p.items.filter(a => a.z > item.z).forEach(a => a.z--);
        item.z = t;
        state.p.items = sortBy(state.p.items, ['z']);
    },

    bottom(state, item) {
        state.p.items.filter(a => a.z < item.z).forEach(a => a.z++);
        item.z = 1;
        state.p.items = sortBy(state.p.items, ['z']);
    },

    up(state, item) {
        let t = getters.maxZ();
        if (item.z === t) {
            return
        }
        state.p.items.filter(a => a.z === item.z + 1).forEach(a => a.z--);
        item.z = item.z + 1;
        state.p.items = sortBy(state.p.items, ['z']);
    },

    down(state, item) {
        if (item.z <= 1) {
            return
        }
        state.p.items.filter(a => a.z === item.z - 1).forEach(a => a.z++);
        item.z = item.z - 1;
        state.p.items = sortBy(state.p.items, ['z']);
    },
    isTextEdit(state, bool) {
      state.p.items.forEach(a => {
        if (a.active) {
          a.bool = bool
        } else {
          a.bool = false
        }
      })
    },
  
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations,
}
