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

export default {
    namespace: 'dataConnect',
    state: {
        list: [],
        newOne: {},
        filterLabel: '',
        validInfo: {}
    },
    reducers: {
        list(state, action) {
            const data = action.data;
            return Object.assign({}, state, {list: data});
        },
        add(state, action) {
            let newOne = Object.assign({}, state.newOne);
            let list = state.list;
            newOne.key = new Date().getMilliseconds()+(Math.random()*100).toFixed(0);
            newOne.code = new Date().getMilliseconds()+(Math.random()*100).toFixed(0);
            list.push(newOne);
            return Object.assign({}, state, {list});
        },
        modify(state, action) {
            const { newOne } = state;
            let list = state.list;
            for(let i = 0; i < list.length; i++) {
                if(list[i].code === newOne.code) {
                    list[i] = Object.assign({}, newOne);
                    break;
                }
            }
            return Object.assign({}, state, {list});
        },
        delete(state, action) {
            const { model } = action;
            let { list } = state;
            for(let i = 0; i < list.length; i++) {
                if(list[i].code === model.code) {
                    list.splice(i, 1);
                }
            }
            return Object.assign({}, state, {list});

        },
        setSelected(state, action) {
            const { selected } = action;
            return Object.assign({}, state, {selected});
        },
        resetSelected(state, action) {
            return Object.assign({}, state, {selected: null});
        },
        setFilterLabel(state, action) {
            const { label } = action;
            return Object.assign({}, state, { filterLabel: label });
        },
        setNewModelField(state, action) {
            const { name, value } = action;
            let newOne = state.newOne;
            let validInfo = state.validInfo;
            newOne[name] = value;
            delete newOne.invalid;
            
            return Object.assign({}, state, { newOne, validInfo });
        },
        setNewModelFields(state, action) {
            const { fields } = action;
            let newOne = state.newOne;
            for(let i = 0; i < fields.length; i++) {
                newOne[fields[i]['name']] = fields[i]['value'];
            }
            delete newOne.invalid;
            return Object.assign({}, state, {newOne});
        },
        setNewModel(state, action) {
            const { model } = action;
            let newOne = Object.assign({}, model);
            return Object.assign({}, state, {newOne});
        },
        resetNewModel(state, action) {
            let newOne = state.newOne;
            delete newOne.name;
            delete newOne.dbType;
            delete newOne.address;
            delete newOne.port;
            delete newOne.dbName;
            delete newOne.userName;
            delete newOne.password;
            delete newOne.description;
            return Object.assign({}, state, {newOne});
        },
        setNewModelInvalid(state, action) {
            const { value } = action;
            let newOne = state.newOne;
            newOne.invalid = value;
            return Object.assign({}, state, {newOne});
        }
    },
    effects: {
        *fetchList(action, { select, call, put, takeEvery, takeLatest }) {
            try {
                const dataConnect = yield select(state => state.present.dataConnect);
                if(!action.mandatory && dataConnect.list.length > 0) {
                    return;
                }
                const res = yield call(service.fetch, {
                    url: URLS.DATACONNECT_LIST,
                    body: {}
                });
                console.log('请求数据连接配置列表',  res);
                if(!res.err && res.data.code > 0) {
                    let data = res.data.data.map((r, i) => {
                        return {
                            key: i,
                            code: r.id,
                            name: r.name,
                            dbName: r.dataName,
                            dbType: r.databaseType,
                            address: r.addrass,
                            port: r.port,
                            userName: r.userName,
                            password: r.passWord,
                            description: r.note
                        }
                    });
                    yield put({ type: 'list', data });
                }else {
                    message.error('读取数据连接配置列表错误: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                message.error('读取数据连接配置列表错误');
                console.log(e);
            }
        },
        *remoteValidate(action, { select, call, put, takeEvery, takeLatest }) {
            const dataConnect = yield select(state => state.present.dataConnect);
            const model = dataConnect.newOne;
            try {
                // 设置validating为true
                yield put({ type: 'setNewModelField', name: 'validating', value: true });
                // 调用检测接口检测连接配置是否合法
                let validBody = {
                    id: model.code,
                    name: model.name,
                    addrass: model.address,
                    port: model.port,
                    databaseType: model.dbType,
                    dataName: model.dbName,
                    userName: model.userName,
                    passWord: model.password
                }
                const res = yield call(service.fetch, {
                    url: URLS.DATACONNECT_VALIDATE,
                    body: validBody
                });

                console.log('校验数据连接配置', validBody, res);

                // 设置validating为false
                yield put({ type: 'setNewModelField', name: 'validating', value: false });

                if(!res.err && res.data.code > 0) {
                    // 如果合法
                    // 设置valid为true
                    yield put({ type: 'setNewModelInvalid', name: 'invalid', value: false });
                }else {
                    message.error('校验失败: ' + (res.err || res.data.msg));
                    yield put({ type: 'setNewModelInvalid', name: 'invalid', value: true });
                }
            }catch(e) {
                console.log(e);
                message.error('校验失败');
            }
        },
        *remoteAdd(action, { select, call, put, takeEvery, takeLatest }) {
            try {
                const dataConnect = yield select(state => state.present.dataConnect);
                const model = dataConnect.newOne;

                let flag = false;
                if(model.invalid === false) {
                    flag = true;
                }else {
                    // 设置validating为true
                    yield put({ type: 'setNewModelField', name: 'validating', value: true });
                    // 调用检测接口检测连接配置是否合法
                    let validBody = {
                        id: model.code,
                        name: model.name,
                        addrass: model.address,
                        port: model.port,
                        databaseType: model.dbType,
                        dataName: model.dbName,
                        userName: model.userName,
                        passWord: model.password
                    }
                    const validRes = yield call(service.fetch, {
                        url: URLS.DATACONNECT_VALIDATE,
                        body: validBody
                    });
                    flag = !validRes.err && validRes.data.code > 0
                    // 设置validating为false
                    yield put({ type: 'setNewModelField', name: 'validating', value: false });
                }

                if(flag) {
                    // 如果合法
                    // 设置valid为true
                    yield put({ type: 'setNewModelInvalid', name: 'invalid', value: false });

                    // 继续执行保存
                    let body = {
                        name: model.name,
                        addrass: model.address,
                        port: model.port,
                        databaseType: model.dbType,
                        dataName: model.dbName,
                        userName: model.userName,
                        passWord: model.password,
                        note: model.description
                    }
                    const res = yield call(service.fetch, {
                        url: URLS.DATACONNECT_ADD,
                        body: body
                    });
                    if(!res.err && res.data.code > 0) {
                        yield put({ type: 'add' });
                        yield put({ type: 'setNewModelField', name: 'visibleBox', value: false });
                        message.success('新增成功');
                    }else {
                        message.error('新增失败: ' + res.err || res.data.msg);
                    }
                }else {
                    yield put({ type: 'setNewModelInvalid', name: 'invalid', value: true });
                }
            }catch(e) {
                console.log(e);
                message.error('新增失败');
            }
        },
        *remoteModify(action, { select, call, put }) {
            try{
                const dataConnect = yield select(state => state.present.dataConnect);
                const model = dataConnect.newOne;

                let flag = false;
                if(model.invalid === false) {
                    flag = true;
                }else {
                    // 设置validating为true
                    yield put({ type: 'setNewModelField', name: 'validating', value: true });
                    // 调用检测接口检测连接配置是否合法
                    let validBody = {
                        id: model.code,
                        name: model.name,
                        addrass: model.address,
                        port: model.port,
                        databaseType: model.dbType,
                        dataName: model.dbName,
                        userName: model.userName,
                        passWord: model.password
                    }
                    const validRes = yield call(service.fetch, {
                        url: URLS.DATACONNECT_VALIDATE,
                        body: validBody
                    });
                    flag = !validRes.err && validRes.data.code > 0;
                    // 设置validating为false
                    yield put({ type: 'setNewModelField', name: 'validating', value: false });
                }
                if(flag) {
                    // 如果合法
                    // 设置valid为true
                    yield put({ type: 'setNewModelInvalid', name: 'invalid', value: false });

                    // 继续执行保存
                    const code = action.code;

                    let data = {
                        id: code,
                        name: model.name,
                        addrass: model.address,
                        port: model.port,
                        databaseType: model.dbType,
                        dataName: model.dbName,
                        userName: model.userName,
                        passWord: model.password,
                        note: model.description
                    };
                    const res = yield call(service.fetch, {
                        url: URLS.DATACONNECT_UPDATE,
                        body: data
                    });
                    console.log('修改数据连接配置', data, res);
                    if(!res.err && res.data.code > 0) {
                        let list = dataConnect.list;
                        list = list.map(l => {
                            if((l.code+'') === (action.code+'')) {
                                l = model;
                            }
                            return l;
                        });
                        yield put({ type: 'list', data: list });
                        message.success('修改成功');
                        yield put({ type: 'setNewModelField', name: 'visibleBox', value: false });
                    }else {
                        message.error('修改失败: ' + res.err || res.data.msg);
                    }
                }else {
                    yield put({ type: 'setNewModelInvalid', name: 'invalid', value: true });
                }
            }catch(e) {
                message.error('修改失败');
            }
        },
        *remoteDelete(action, { select, call, put, takeEvery, takeLatest }) {
            const dataConnect = yield select(state => state.present.dataConnect);
            const code = action.code;
            let list = dataConnect.list;
            try {
                const res = yield call(service.fetch, {
                    url: URLS.DATACONNECT_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', data: list });
                    message.success('删除成功');
                }else {
                    message.error('删除失败: ' + (res.err || res.data.msg));
                }
            }catch(e) {
                console.log(e);
                message.error('删除失败');
            }
        }
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname, query }) => {
            })
        }
    }
};