import * as Api from '../apis/useDemand'; //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';
import {addContentPath} from '../util/index.js'
const {
    TableStore
} = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;

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

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

            if (status == '1') {
                hasRight && this.grantAuth();
                this.getTableInfo();
                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, 2].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('6131', "用工需求"), //todo
        menu: [],
    }

    @action
    getMenus = () => {
        Api.getButtonsMenu().then(cb => {
            const {
                api_status,
                btnMenu
            } = cb;

            if (api_status) {
                this.top.menu = btnMenu;
            } else {
                message.error();
            }
        }).catch(error => {
            message.error();
        });
    }

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

        let buttons = [],
            dropMenuDatas = [];

        const {
            tableStore
        } = this.table;

        top.map((item, i) => {
            buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@kav8mn@${i}`} type='primary' disabled={tableStore.loading} 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,
                disabled: tableStore.loading,
                onClick: () => this[item.menuFun](item.menuFun)
            }
            if (item.menuFun == 'log' || item.menuFun == 'collection') {
                obj.disabled = true;
            }
            dropMenuDatas.push(obj);
        })

        return {
            buttons,
            dropMenuDatas
        };
    }

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

    exportExcel = () => {
        const params = {
            ...this.radioGroup.params
        };
        Api.getDetailSearchList(params).then(datas => {
            const {
                sessionkey
            } = datas;
            Api.exportExcel(sessionkey).then(data => {
                if (data.url) {
                    window.location.href =  addContentPath(data.url);
                }
            })
        })
        // this.table.tableStore.exportAll();
    }

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

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

        Api.getRadioGroupDatas().then(cb => {
            const {
                api_status,
                conditions
            } = cb;

            if (api_status) {
                this.radioGroup.config = conditions[0].items;
                this.radioGroup.loading = false;
            } else {
                message.error();
            }
        }).catch(error => {
            message.error();
        });
    }

    @action
    resetRadioGroup = () => {
        this.radioGroup.config = [];
        this.radioGroup.loading = false;
    }

    @action
    radioGroupCallBack = (params) => {
        const {
            demandRegDateSelect,
            demandRegYear,
            company,
            subcompanyid,
            departmentid,
            jobtitle,
            jobtitleId,
        } = params;

        this.radioGroup.params = params;

        ['getBarChartsDatas', 'getSummaryDatas', 'getTabsDatas'].map(f => {
            const b1 = demandRegDateSelect == '6' && !demandRegYear,
                b2 = (company == '1' && !subcompanyid) || (company == '2' && !departmentid),
                b3 = jobtitle == '1' && !jobtitleId;

            if ([b1, b2, b3].some(b => b)) {
                return
            }
            this[f]();
        })
    }

    //*************************Top*******************************
    @observable summary = {
        countDatas: [],
        loading: false,
    }

    @action
    getSummaryDatas = () => {
        this.summary.loading = true;

        const {
            params = {}
        } = this.radioGroup;

        Api.getSummaryDatas(params).then(cb => {
            const {
                api_status,
                countDatas
            } = cb;

            if (api_status) {
                this.summary.countDatas = countDatas;
                this.summary.loading = false;
            } else {
                message.error();
            }
        }).catch(error => {
            message.error();
        });
    }

    @action
    resetSummaryDatas = () => {
        this.summary.config = [];
        this.summary.loading = false;
    }

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

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

        const {
            params = {}
        } = this.radioGroup;


        Api.getBarChartsDatas(params).then(cb => {
            const {
                api_status,
                charts
            } = cb;

            if (api_status) {
                this.adjustCharts(charts);
                this.barCharts.charts = charts;
                this.barCharts.loading = false;
            } else {
                message.error();
            }
        }).catch(error => {
            message.error();
        });
    }

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

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

            yAxis.data = this.getYAxisData({
                datas: yAxis.data,
                index: v
            });

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

    }

    getYAxisData = (params) => {
        const {
            datas,
            index
        } = params;

        let nd = [],
            tIds = [];

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

        this.barCharts[(index == '0') ? 'lIds' : 'rIds'] = tIds;

        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) => { //TODO
        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 = () => {
        this.barCharts.charts = [];
        this.barCharts.loading = 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;

        Api.getTabsDatas(params).then(cb => {
            const {
                api_status,
                charts,
            } = cb;

            if (api_status) {
                this.adjustChart(charts);
                this.tabs.charts = charts;
                this.tabs.loading = false;
            } else {
                message.error();
            }
        }).catch(error => {
            message.error();
        });
    }

    adjustChart = (charts) => {
        charts.map(chart => {
            const datas = chart.option.series[0].data;
            datas.map(d => {
                d.label = this.formatLabel(datas.length);
            })
        });
    }

    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 = () => {
        this.tabs.charts = [];
        this.tabs.key = '0';
        this.tabs.loading = false;
    }

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

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

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

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

        return buttons;
    }

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

        return {
            width: ['more0', 'more1'].includes(type) ? 800 : 1050,
            height: 700
        }
    }

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

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

        return datas;
    }

    @action
    openDialog = (params) => {
        const {
            type,
            field,
            index
        } = params;

        this.mainDialog.type = type;
        this.mainDialog.visible = true;
        this.tab.field = field; //TODO 拼接field

        this.barCharts.index = index;

        let title;
        if (type == 'more0') {
            title = getLabel('391170', "需求最多部门排名")
        } else if (type == 'more1') {
            title = getLabel('391171', "需求最多岗位排名")
        } else {
            title = getLabel('15729', "具体信息")
        }
        this.mainDialog.title = title;
    }

    @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;

        let buttonsAd = [];
        [0, 1, 2].map((v, i) => {
            const func = (v == 0) ? 'handleSearch' : 'changePanelStatus';
            const name = (v == 0) ? getLabel(82529, '搜索') : (v == 1) ? getLabel(27088, '重置') : getLabel(32694, '取消');
            buttonsAd.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qnhk7v@${i}`} type={v==0 ? "primary" : ''} onClick={() => {v==1 ? form.reset() : this[func]()}}>{name}</Button>);
        });

        return buttonsAd;
    }

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

        let arr = [];
        isFormInit && conditions.map(c => {
            c.items.map((field, index) => {
                arr.push(<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@734ynt@${index}`} span={10} offset={1}>
                              <div style={{marginTop: 20}}>
                                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@lnlozf@${index}`}
                                      label={`${field.label}`}
                                      labelCol={{span: 6}}
                                      wrapperCol={{span: 18}}>
                                          {<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@24kb1l@${index}`} fieldConfig={field} form={form} formParams={form.getFormParams()} />}
                                  </WeaFormItem>
                              </div>
                         </Col>)
            })
        })

        if (isFormInit && field) {
            const {
                index
            } = this.barCharts;

            form.updateFields({
                [index == '0' ? 'departmentid' : 'jobtitleId']: field
            })
        }

        return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@i8nmvd`}
            onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && this.handleSearch()}
        >{arr}</Row>
    }

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

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

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

    @action
    getSearchCondition = () => {
        Api.getSearchCondition().then(rs => {
            const {
                api_status,
                conditions
            } = rs;

            if (api_status) {
                this.tab.conditions = conditions;
                this.tab.form.initFormFields(conditions);
            } else {
                message.error();
            }
        }).catch(error => {
            message.error();
        });
    }

    @action
    resetTab = () => {
        this.tab.isPanelShow = false;
        this.tab.conditions = [];
        this.tab.form = new WeaForm();
    }

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

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

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

        let func;
        let cParams;
        if (type == 'more0') {
            func = 'getMoreDeptList';
            cParams = {
                departmentName: searchBaseValue,
                ...params,
            };
        } else if (type == 'more1') {
            func = 'getMoreJobtitleList';
            cParams = {
                jobtitleName: searchBaseValue,
                ...params,
            };
        } else {
            func = 'getDetailSearchList';
            cParams = form.isFormInit ? form.getFormParams() : {
                [index == '0' ? 'departmentid' : 'jobtitleId']: field && field.value,
                ...params,
            };
            Object.assign(cParams, {
                jobtitleName: searchBaseValue,
            });
        }

        Api[func](cParams).then(cb => {
            const {
                api_status,
                sessionkey,
            } = cb;

            if (api_status) {
                this.table.tableStore.getDatas(sessionkey, 1);
            } else {
                message.error();
            }
        }).catch(error => {
            message.error();
        });
    }

    isEmptyObject = (obj) => {
        if (Object.keys(obj) == 0) return true
    }

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

}