import { message } from 'antd'
import * as service from '../services/index'
import URLS from '../constants/url'

export default {
    namespace: 'dashboard',
    state: {
        list: [],
        filterLabel: '',
        groupList: [],
        currentGroup: [{
            code: 'all',
            label: '全部分组'
        }],
        groupDirty: false,
        
    },
    reducers: {
        list(state, action) {
            let list = action.list;
            return Object.assign({}, state, {list});
        },
        setFilterLabel(state, action) {
            let { label } = action;
            return Object.assign({}, state, {filterLabel: label});
        }
    },
    effects: {
        *fetchList(action, {select, call, put}) {
            try {
                const dashboard = yield select(state => state.present.dashboard);
                if(!action.mandatory && dashboard.list.length > 0) {
                    return;
                }
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_LIST
                });
                if(!res.err && res.data.code > 0) {
                    const resData = res.data.data;
                    let list = resData.map(d => {
                        let items = d.bdConfiguration ? JSON.parse(d.bdConfiguration) : [];
                        return {
                            code:  d.id+'',
                            name: d.bdName,
                            items: items,
                            description: d.bdNote || '',
                            thumbnail: d.thumbnail,
                            creator: d.createBy,
                            createTime: d.createDate,
                        }
                    })
                    console.log('请求看板列表', list);
                    yield put({ type: 'list', list: list });
                }else {
                    message.error('请求看板列表失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(e);
                message.error('请求看板列表失败')
            }
        },
        *remoteDetail(action, { select, call, put }) {
            const code = action.code;
            if(!code){
                return
            }
            try {
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_DETAIL,
                    body: code
                });
                console.log('解析看板数据', code, res);
                if(!res.err && res.data.code > 0) {
                    const resData = res.data.data;
                    let items = resData.bdConfiguration ? JSON.parse(resData.bdConfiguration) : [];

                    let data = {
                        code:  resData.id+'',
                        name: resData.bdName,
                        items: items,
                        description: resData.bdNote || '',
                        thumbnail: resData.thumbnail,
                        creator: resData.createBy,
                        createTime: resData.createDate,
                    }

                    let fields = [];
                    for(let key in data) {
                        fields.push({
                            name: key,
                            value: data[key]
                        })
                    }
                    yield put({ type: 'dashboardDesigner/silentSetFields', fields: fields });
                }else {
                    message.error('解析看板错误: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                console.log(e);
                message.error('解析看板错误');
            }
        },
        *remoteAdd(action, { select, call, put }) {
            try {
                const dashboardDesigner = yield select(state => state.present.dashboardDesigner);
                const { name, items, thumbnail } = dashboardDesigner;
                let body = {
                    bdName: name,
                    bdNote: '',
                    bdConfiguration: JSON.stringify(items),
                    thumbnail: thumbnail,
                    createBy: 'zhuth'
                }
                console.log('新增看板', body);
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_ADD,
                    body: body
                });
                console.log('新增看板', body, res);
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'fetchList', mandatory: true });
                    message.success('保存成功');
                }else {
                    message.error('保存失败: ' + (res.err || res.data.msg));
                } 
            }catch(e) {
                console.log(e);
                message.error('保存失败');
            }
        },
        *remoteQucikAdd(action, { select, call, put }) {
            try {
                const dashboardDesigner = yield select(state => state.present.dashboardDesigner);
                const { name, items } = dashboardDesigner;
                let body = {
                    bdName: name,
                    bdNote: '',
                    bdConfiguration: JSON.stringify(items),
                    thumbnail: '',
                    createBy: 'zhuth'
                }
                console.log('快速新增看板', body);
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_ADD,
                    body: body
                });
                console.log('快速新增看板', body, res);
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'fetchList', mandatory: true });
                    yield put({ type: 'main/redirect', path: '/dashboard/' + res.data.data });
                }else {
                    message.error('保存失败: ' + (res.err || res.data.msg));
                } 
            }catch(e) {
                console.log(e);
                message.error('保存失败');
            }
        },
        *remoteModify(action, { select, call, put }) {
            try {
                const dashboardDesigner = yield select(state => state.present.dashboardDesigner);
                const { code, name, items, thumbnail } = dashboardDesigner;
                let body = {
                    id: code,
                    bdName: name,
                    bdNote: '',
                    bdConfiguration: JSON.stringify(items),
                    thumbnail: thumbnail,
                    createBy: 'zhuth'
                }
                console.log('修改看板', body);
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_UPDATE,
                    body: body
                });
                console.log('修改看板', body, res);
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'fetchList', mandatory: true });
                    yield put({ type: 'dashboardDesigner/silentSetField', name: 'dirty', value: false });
                    message.success('保存成功');
                }else {
                    message.error('保存失败: ' + (res.err || res.data.msg));
                } 
            }catch(e) {
                console.log(e);
                message.error('保存失败');
            }
        },
        *remoteDelete(action, { select, call, put }) {
            const dashboard = yield select(state => state.present.dashboard);
            const code = action.code;
            let list = dashboard.list;
            try {
                const res = yield call(service.fetch, {
                    url: URLS.DASHBOARD_DELETE,
                    body: [code]
                });
                console.log('删除看板', [code], res);
                if(!res.err && res.data.code > 0) {
                    for(let i = 0; i < list.length; i++) {
                        if(list[i].code === code) {
                            list.splice(i, 1);
                            break;
                        }
                    }
                    yield put({ type: 'list', list: list });
                    message.success('删除成功');
                }else {
                    message.error('删除失败: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                console.log(e);
                message.error('删除失败');
            }
        },
        *transfer(action, { put, call, select }) {
            const { userCode, dashboardCode } = action;
            const body = {
                userId: userCode,
                id: dashboardCode
            };
            try {
                // const res = yield call(service.fetch, {
                //     url: URLS.DASHBOARD_TRANSFER,
                //     body
                // });
                // console.log('看板移交', body, res);
                const res = {data:{code:1}};
                if(!res.err && res.data.code > 0) {
                    const dashboard = yield select(state => state.present.dashboard);
                    const list = dashboard.list;
                    for(let i = 0; i < list.length; i++) {
                        if(list[i].code === dashboardCode) {
                            list.splice(i, 1);
                            break;
                        }
                    }
                    yield put({ type: 'list', list });
                    message.success('移交成功');
                }else {
                    console.log(body, res.err || res.data.msg);
                    message.error('移交失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(body, e);
                message.error('移交失败');
            }
        }
    },
    subscriptions: {
        setup({ dispatch, history}) {
            return history.listen(({pathname}) => {}
        )}
    }
}