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

function getBodyFilter(modelFilter) {
    let { name, label, operator, operatorLabel, type, value1, value2 } = modelFilter;
    let bodyFilter = {
        columnName: name,
        columnLabel: label,
        columnType: type,
        symbol: operator,
        symbolLabel: operatorLabel,
        value: value1
    };
    if(type === 'scale' && operator === 'between') {
        bodyFilter['value'] = value1 + ',' + value2;
    }else if(type === 'time') {
        // let v1 = dateFormat(new Date(value1),'yyyy-MM-dd hh:mm:ss');
        // let v2 = dateFormat(new Date(value2),'yyyy-MM-dd hh:mm:ss');

        let v1 = moment(value1).format('YYYY-MM-DD HH:mm:ss');
        let v2 = moment(value2).format('YYYY-MM-DD HH:mm:ss');

        if(operator === 'between') {
            bodyFilter['value'] = v1 + ',' + v2;
        }else {
            bodyFilter['value'] = v1;
        }
    }
    return bodyFilter;
}
function getModelFilter(resFilter) {
    let { columnName, columnLabel, columnType, symbol, symbolLabel, value } = resFilter;
    let modelFilter = {
        name: columnName,
        label: columnLabel,
        type: columnType,
        operator: symbol,
        operatorLabel: symbolLabel,
        value1: value
    };
    if(columnType === 'scale' && symbol === 'between') {
        modelFilter['value1'] = value.split(',')[0];
        modelFilter['value2'] = value.split(',')[1];
    }else if(columnType === 'time') {
        let value1 = value.split(',')[0];
        let value2 = value.split(',')[1];
        let v1 = moment(value1);
        let v2 = moment(value2);

        if(symbol === 'between') {
            modelFilter['value1'] = v1;
            modelFilter['value2'] = v2;
        }else {
            modelFilter['value'] = v1;
        }
    }
    return modelFilter;
}

export default {
    namespace: 'chartPolicy',
    state: {
        chartCode: null,
        columnData: [],
        list: [{
            code: '1',
                    enabled: true,
                    name: '开放策略1',
                    targets: [],
                    filters: []
        }]
    },
    reducers: {
        list(state, action) {
            const { list } = action;
            return { ...state, list };
        },
        modify(state, action) {
            const { policy } = action;
            let { list } = state;
            for(let i = 0; i < list.length; i++) {
                if(list[i].code === policy.code) {
                    list[i] = policy;
                    break;
                }
            }
            return { ...state, list };
        },
        setColumnData(state, action) {
            const { columnData } = action;
            return { ...state, columnData }
        }
    },
    effects: {
        *fetchList(action, { select, call, put }) {
            const body = action.chartCode;
            try {
                const res = yield call(service.fetch, {
                    url: URLS.CHART_POLICY_LIST,
                    body
                });
                console.log('请求图表策略列表', body, res);
                if(!res.err && res.data.code > 0) {
                    let list = (res.data.data && res.data.data.length > 0) ? res.data.data.sort((a, b) => new Date(a.createDate) - new Date(b.createDate)).map(d => ({
                        code: d.strategies.id,
                        enabled: d.strategies.isOpen+'' === '1',
                        name: d.strategies.name,
                        targets: d.userGroupName.map(g => ({
                            code: g.ID+'',
                            isGroup: true,
                            name: g.NAME
                        })).concat(d.userName.map(u => ({
                            code: u.ID+'',
                            isGroup: false,
                            name: u.NAME
                        }))),
                        filters: d.strategies.ruleStr ? JSON.parse(d.strategies.ruleStr).map(f => getModelFilter(f)) : [],
                    })) : [];
                    yield put({ type: 'list', list });
                }else {
                    message.error('请求图表策略列表失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(body, e);
                message.error('读取图表策略列表错误');
            }
        },
        *remoteAdd(action, { put, call, select }) {
            const chartPolicy = yield select(state => state.present.chartPolicy);
            const { chartCode } = action;
            const { policy } = action;
            const body = {
                type: 'chart',
                tarId: chartCode,
                name: policy.name,
                rule: policy.filters.map(f => getBodyFilter(f)),
                isOpen: policy.enabled ? '1' : '0',
                createBy: 'zhuth'
            };
            try {
                const res = yield call(service.fetch, {
                    url: URLS.CHART_POLICY_ADD,
                    body,
                });
                console.log('添加策略', body, res);
                if(!res.err && res.data.code > 0) {
                    let { list } = chartPolicy;
                    list.push({
                        code: res.data.data,
                        ...policy
                    });
                    yield put({ type: 'list', list });
                }else {
                    message.error('添加失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(body, e);
                message.error('添加失败');
            }
        },
        *remoteModify(action, { put, call, select }) {
            const { policy, chartCode } = action;
            console.log(chartCode);
            const body = {
                id: policy.code,
                type: 'chart',
                tarId: chartCode,
                name: policy.name,
                rule: policy.filters.map(f => getBodyFilter(f)),
                isOpen: policy.enabled ? '1' : '0',
                createBy: 'zhuth'
            };
            try {
                const res = yield call(service.fetch, {
                    url: URLS.CHART_POLICY_UPDATE,
                    body
                });
                console.log('修改图表策略', body, res);
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'modify', policy });
                }else {
                    message.error('修改失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(body, e);
                message.error('修改失败');
            }
        },
        *remoteDelete(action, { put, call, select }) {
            const chartPolicy = yield select(state => state.present.chartPolicy);
            const { code } = action;
            const body = [code];
            try {
                const res = yield call(service.fetch, {
                    url: URLS.CHART_POLICY_DELETE,
                    body
                });
                console.log('删除策略', body, res);
                if(!res.err && res.data.code > 0) {
                    let { list } = chartPolicy;
                    for(let i = 0; i < list.length; i++) {
                        if(list[i].code === code) {
                            list.splice(i, 1);
                            break;
                        }
                    }
                    yield put({ type: 'list', list });
                }else {
                    message.error('删除失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(body, e);
                message.error('删除失败');
            }
        },
        *remoteSetTarget(action, { put, call, select }) {
            const { policy, targets } = action;
            const body = {
                stId: policy.code+'',
                type: 'chart',
                obj: targets.map(t => ({
                    obId: t.code,
                    objectType: t.isGroup ? '0' : '1'
                }))
            };
            try {
                const res = yield call(service.fetch, {
                    url: URLS.CHART_POLICY_TARGET_UPDATE,
                    body
                });
                console.log('设置策略对象', body, res);
                if(!res.err && res.data.code > 0) {
                    yield put({ type: 'modify', policy: {
                        ...policy,
                        targets
                    } });
                }else {
                    message.error('设置对象失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(body, e);
                message.error('设置对象失败');
            }
        },
        /**
         * 获得列数据
         */
        *remoteColumnData(action, { put, call, select }) {
            const body = action.chartCode;
            try {
                const res = yield call(service.fetch, {
                    url: URLS.CHART_QUERY_DATACOLUMNS,
                    body
                });
                console.log('获得图表列数据', body, res);
                if(!res.err && res.data.code > 0) {
                    let columnData = res.data.data.map(d => ({
                        name: d.columnName,
                        label: d.columnRaname,
                        type: d.columnType,
                    }));
                    yield put({ type: 'setColumnData', columnData });
                }else {
                    message.error('获得图表列数据失败: ' + res.err || res.data.msg);
                }
            }catch(e) {
                console.log(body, e);
                message.error('获得图表列数据失败');
            }
        }
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname, query }) => {
            })
        }
    }
};