import * as Api from '../apis/applicant'; //TODO
import {
    observable,
    action,
} from 'mobx';
import {
    WeaForm,
    WeaTableNew,
    WeaSwitch,
} from 'comsMobx';
import {
    WeaLocaleProvider,
    WeaFormItem,
    WeaMoreButton,
} from 'ecCom';
import {
    message,
    Button,
    Row,
    Col,
    Modal,
} from 'antd';
const {
    TableStore
} = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;

import {
    tabs,
    fetch,
} from '../components/applicant/util';

const {
    getSearchsAd,
    getButtonsAd
} = tabs;

export class HrmApplicant {
    //*************************index********************************
    @observable main = {
        authorized: false,
        loading: true,
    }

    @action
    getAuth = () => {
        Api.getAuth().then(cb => {
            const {
                status,
                hasRight
            } = cb;

            if (status == '1') {
                hasRight && this.grantAuth();
                this.stoploading();
            } else {
                message.error();
            }
        }).catch(error => {
            message.error();
        });
    }

    @action
    grantAuth = () => {
        this.main.authorized = true;
    }

    @action
    stoploading = () => {
        this.main.loading = false;
    }

    refresh = () => {
        this.getRadioGroupDatas();
    }

    onresize = () => {
        const {
            key
        } = this.tabs;

        [0, 1].map(val => {
            this.barCharts[`echart${val}`] && this.barCharts[`echart${val}`].chart && this.barCharts[`echart${val}`].chart.resize();
        })

        this.tabs[`echart${key}`] && this.tabs[`echart${key}`].chart && this.tabs[`echart${key}`].chart.resize();
    }


    //*************************Top*******************************
    @observable top = {
        title: getLabel('391168', "应聘人员"),
        menu: [],
    }

    @action
    getMenus = () => {
        fetch({
            Api,
            name: 'getButtonsMenu',
            logic: (cb) => {
                this.top.menu = cb.btnMenu
            }
        });
    }

    get menus() {
        const top = this.top.menu.filter(item => item.isTop == '1'),
            right = this.top.menu;

        let buttons = [],
            dropMenuDatas = [];

        top.map((item, i) => {
            buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ogp86j@${i}`} type='primary' onClick={() => this.handleTopBtnsClick(item)}>{item.menuName}</Button>); //TODO
        });

        right.map((item, index) => {
            let obj = {
                key: item.menuFun,
                icon: <i className={`${item.menuIcon}`}/>,
                content: item.menuName,
                onClick: () => this[item.menuFun](item.menuFun)
            }

            if (['log', 'collection'].includes(item.menuFun)) {
                obj.disabled = true;
            }

            dropMenuDatas.push(obj);
        })

        return {
            buttons,
            dropMenuDatas
        };
    }

    @action
    handleTopBtnsClick = (item) => {
        this[item.menuFun] && this[item.menuFun](item.menuFun)
    }

    detailInfo = (type) => {
        this.openDialog(type);
    }

    //*************************RadioGroup*******************************
    @observable radioGroup = {
        config: [],
        loading: false,
    }

    @action
    getRadioGroupDatas = () => {
        this.radioGroup.loading = true;

        fetch({
            Api,
            name: 'getRadioGroupDatas',
            logic: (cb) => {
                ['config', 'loading'].map((v, i) => {
                    this.radioGroup[v] = (i == 0) ? cb.conditions[0].items : false;
                });
            }
        });

    }

    @action
    resetRadioGroup = () => {
        ['config', 'loading'].map((v, i) => {
            this.radioGroup[v] = (i == 0) ? [] : false;
        });
    }

    @action
    radioGroupCallBack = (params) => {
        const {
            createDateSelect,
            createYear
        } = params;

        this.radioGroup.params = params;

        if (createDateSelect == '6' && !createYear) {
            return
        }
        ['getBarChartsDatas', 'getTabsDatas'].map(f => {
            this[f]();
        });
    }

    //*************************BarCharts*******************************
    @observable barCharts = {
        charts: [],
        loading: false,
    }

    @action
    getBarChartsDatas = () => {
        this.barCharts.loading = true;

        fetch({
            Api,
            name: 'getBarChartsDatas',
            fetchParams: this.radioGroup.params,
            logic: (cb) => {
                this.adjustCharts(cb.charts);

                ['charts', 'loading'].map((v, i) => {
                    this.barCharts[v] = (i == 0) ? cb[v] : false
                })
            }
        });
    }

    @action
    adjustCharts = (charts) => {
        const yAxis = charts[0].option.yAxis,
            series = charts[0].option.series,
            {
                data
            } = series[0];

        series[0].barWidth = `${data.length*9}%`;

        yAxis.data = this.getYAxisData(yAxis.data);

        charts[0].option.yAxis.axisLabel = this.getAxisLabel();

    }

    getYAxisData = (datas) => {
        let nd = [],
            ids = [];
        datas.map(data => {
            data.split(' ').map((d, i) => {
                if (i == 0) {
                    nd.push(d);
                } else {
                    ids.push(d.split(':')[1].split('}')[0]);
                }
            });
        });

        this.barCharts.ids = ids;

        return nd;
    }

    getAxisLabel = () => {
        var _this = this;
        return ({
            formatter: function(value) {
                let len = _this.getValueLength(value);
                if (len > 12) {
                    return `${_this.sliceValue(value, 12)}...`;
                } else {
                    return value;
                }

            }
        })
    }

    sliceValue(value, len) {
        let temp = [];
        let count = 0;
        value.split('').map(val => {
            if (count < len) {
                temp.push(val);
                count += this.checkIsChinese(val) ? 2 : 1;
            }
        });
        return temp.join('');
    }


    getValueLength = (values) => {
        let len = 0;

        values.split('').map((v, i) => {
            const a = v.charAt(i);
            if (a.match(/[^\x00-\xff]/ig) != null) {
                len += 2;
            } else {
                len += 1;
            }
        });

        return len;
    }


    checkIsChinese(val) {　　
        let reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");　　
        if (reg.test(val)) return true
    }

    @action
    resetBarCharts = () => {
        ['charts', 'loading'].map((v, i) => {
            this.barCharts[v] = (i == 0) ? [] : false;
        });
    }

    @action
    setRef = (params) => {
        const {
            ref,
            alias,
            type
        } = params;

        if (type == 'barCharts') {
            this.barCharts[alias] = ref;
        } else {
            this.tabs[alias] = ref;
        }
    }


    //*************************Tabs*******************************
    @observable tabs = {
        charts: [],
        key: '0',
        loading: false,
    }

    @action
    getTabsDatas = () => {
        this.tabs.loading = true;

        const {
            params
        } = this.radioGroup, {
            key
        } = this.tabs, {
            value
        } = this.query;

        const fetchParams = {
            ...params
        };

        if (key == '2') {
            Object.assign(fetchParams, {
                salaryNeedeRand: value ? value : 5
            });
        }
        if (key == '3') {
            Object.assign(fetchParams, {
                workTimeRand: value ? value : 2
            });
        }

        fetch({
            Api,
            name: 'getTabsDatas',
            fetchParams,
            logic: (cb) => {
                const {
                    chart
                } = cb;
                this.adjustChart(chart);
                ['charts', 'loading'].map((v, i) => {
                    this.tabs[v] = (i == 0) ? chart : false;
                });
            }
        });

    }

    adjustChart = (charts) => {
        charts.map((chart, index) => {
            const {
                option
            } = chart, {
                series,
                legend
            } = option;

            let arr = [];

            legend.data.map(d => {
                arr.push(d.split('{')[0]);
            });

            option.legend.data = arr;

            const datas = series[0].data;

            let ids = [];
            datas.map(data => {
                data.name.split('{').map((d, i) => {
                    if (i == 0) {
                        data.name = d;
                    } else {
                        ids.push(d.split(':')[1].split('}')[0]);
                    }
                });
                data.label = this.formatLabel(datas.length);
            })

            this.tab[`ids${index}`] = ids;
        });
    }

    formatLabel(length) {
        if (length < 10) {
            return ({
                normal: {
                    formatter: [
                        '{title|{b}}{abg|}',
                        '{c} | {rate|{d}%}',
                    ].join('\n'),
                    rich: {
                        title: {
                            color: '#666',
                            align: 'center',
                        },
                        abg: {
                            width: '100%',
                            align: 'right',
                            height: 25,
                        },
                        rate: {
                            fontFamily: 'Times New Roman',
                        }
                    }
                }

            })
        } else {
            return ({
                normal: {
                    formatter: [
                        '{b} | {c} | {d}%',
                    ].join('\n'),
                }
            })
        }

    }

    @action
    resetTabs = () => {
        ['charts', 'key', 'loading'].map((v, i) => {
            this.tabs[v] = (i == 0) ? [] : (i == 1) ? '0' : false;
        });
    }

    @action
    tabsCallback = (key) => {
        this.tabs.key = key;
        this.getTabsDatas();
    }

    //*************************Query*******************************
    @observable query = {
        value: '',
    }

    @action
    inputCallback = (value) => {
        this.query.value = value;
    }

    @action
    resetQuery = () => {
        this.query.value = '';
    }

    //*************************MainDialog*******************************
    @observable mainDialog = {
        visible: false,
        title: '',
    }

    get buttons() {
        const {
            tableStore
        } = this.table;

        const buttons = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vy78iw@1`} type="primary" disabled={tableStore.loading} onClick={() => tableStore.exportAll()}>{getLabel('28343', "导出Excel")}</Button>),
            (<WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@a5r7n3@2`} datas={this.dropMenuDatas} />)
        ]

        return buttons;
    }

    get style() {
        const {
            type
        } = this.mainDialog;

        return {
            width: type == 'more' ? 800 : 1050,
            height: 700
        }
    }

    get dropMenuDatas() {
        const {
            tableStore
        } = this.table, {
            loading,
            exportAll,
            setColSetVisible,
            tableColSet
        } = tableStore;

        let datas = [];
        ['0', '1'].map(v => {
            datas.push({
                key: v,
                disabled: loading,
                icon: <i className={`icon-coms-${(v == '0') ? 'export' : 'Custom'}`} />,
                content: (v == '0') ? getLabel('28343', "导出Excel") : getLabel('32535', '显示列定制'),
                onClick: () => (v == '0') ? exportAll() : setColSetVisible(true) && tableColSet(true),

            });
        })

        return datas;
    }

    @action
    openDialog = (type, field, isPie) => {
        const title = (type == 'more') ? getLabel('391169', "应聘人最多岗位排名") : getLabel('15729', "具体信息");

        ['type', 'title', 'visible'].map((v, i) => {
            this.mainDialog[v] = (i == 2) ? true : eval(v)
        });

        if (field && !isPie) {
            if (Object.keys(field).length > 1) {
                this.tab.field = field;
                this.barCharts.index = '0';
            } else {
                this.barCharts.index = '1';
                this.tab.createMonth = field;
            }
        }

        if (isPie) {
            this.tab.pie_param = field;
        }
    }

    @action
    closeDialog = () => {
        this.mainDialog.visible = false;
    }


    //*************************Tab*******************************
    @observable tab = {
        isPanelShow: false,
        conditionCount: 10, //TODO
        form: new WeaForm(),
        conditions: [],
        searchBaseValue: '',
    }

    get buttonsAd() {
        const {
            form
        } = this.tab;

        return getButtonsAd({
            form,
            search: () => this.handleSearch(),
            cancel: () => this.changePanelStatus(),
        });

    }

    get searchsAd() {
        const {
            form,
            conditions,
        } = this.tab, {
            isFormInit
        } = form;

        return <div
            onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && this.handleSearch()}
        >{
            getSearchsAd({
                isFormInit,
                conditions,
                form,
            })
        }</div>;
    }

    @action
    changePanelStatus = (bool) => {
        this.tab.isPanelShow = bool;
    }

    @action
    handleSearch = () => {
        const {
            isPanelShow
        } = this.tab;

        isPanelShow && this.changePanelStatus(false);
        this.getTableInfo();
    }

    @action
    getSearchCondition = () => {
        fetch({
            Api,
            name: 'getSearchCondition',
            logic: (cb) => {
                const {
                    conditions
                } = cb;

                this.tab.conditions = conditions;
                this.tab.form.initFormFields(conditions);

                const {
                    field,
                    form
                } = this.tab;

                field && form.updateFields({
                    jobtitleId: field
                })
            }
        });
    }

    @action
    resetTab = () => {
        const {
            type
        } = this.mainDialog;

        if (type == 'more') {
            this.tab.searchBaseValue = '';
        } else {
            ['isPanelShow', 'conditions', 'form', 'field'].map((v, i) => {
                this.tab[v] = (i == 0) ? false : (i == 1) ? [] : (i == 2) ? new WeaForm() : '';
            });
        }
    }

    @action
    setSearchBaseValue = (value) => {
        this.tab.searchBaseValue = value;
    }

    //*************************table*******************************
    @observable table = {
        tableStore: new TableStore(),
    }

    @action
    getTableInfo = () => {
        const {
            form,
            searchBaseValue,
            field,
            createMonth,
            pie_param,
        } = this.tab, {
            type
        } = this.mainDialog, {
            params
        } = this.radioGroup, {
            index
        } = this.barCharts;

        let name, fetchParams;
        if (type == 'more') {
            name = 'getApplyInfoRpList';
            fetchParams = {
                jobtitleName: searchBaseValue,
                ...params,
            }
        }
        if (['bar', 'pie', 'detailInfo'].includes(type)) {
            name = 'getDetailSearchList';
            if (form.isFormInit) {
                fetchParams = form.getFormParams();
            } else {
                fetchParams = {
                    ...params,
                }
                if (type == 'bar') {
                    Object.assign(fetchParams, (index == '0') ? {
                        jobtitleId: field.value
                    } : createMonth);
                }
                if (type == 'pie') {
                    Object.assign(fetchParams, pie_param);
                }
            }
        }

        fetch({
            Api,
            name,
            fetchParams,
            logic: (cb) => {
                this.table.tableStore.getDatas(cb.sessionkey, 1);
            }
        });
    }

    @action
    resetTable = () => {
        this.table.tableStore = new TableStore();
    }


}