import * as Api from '../apis/recruitInfo';
import {
    observable,
    action,
    computed,
} from 'mobx';
import {
    WeaForm,
    WeaTableNew,
    WeaSwitch,
} from 'comsMobx';
import {
    WeaLocaleProvider,
    WeaFormItem,
    WeaSearchGroup,
    WeaMoreButton,
    WeaTools,
    WeaButtonIcon,
} 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 HrmRecruitInfo {
    //*************************index********************************
    @observable main = {
        authorized: false,
        loading: true,
        isSingle: false,
    }

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

    @action
    refresh = () => {
        this.resetSearch();
        this.getTableInfo();
    }

    @action
    setPropsFromParent = (id) => {
        if (id) {
            this.main.isSingle = true;
            this.main.id = id;
        } else {
            this.main.isSingle = false;
            this.main.id = '';
        }
    }

    @action
    setChildRef = (ref) => {
        this.main.ref = ref;
    }

    //*************************Top*******************************
    @observable top = {
        title: getLabel('366', "招聘信息"),
        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;

        const {
            tableStore
        } = this.mainTable;

        let buttons = [],
            dropMenuDatas = [];

        top.map((item, index) => {
            if (item.menuFun !== 'batchDelete') {
                buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@kx8zmm@${index}`} type='primary' disabled={tableStore.loading} onClick={() => this.handleTopBtnsClick(item)}>{item.menuName}</Button>);
            } else {
                buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ani0pj@${index}`} type='primary' disabled={tableStore.selectedRowKeys.length == 0} onClick={() => this.handleTopBtnsClick(item)}>{item.menuName}</Button>);
            }
        });

        right.map((item, index) => {
            let obj = {
                key: item.menuFun,
                icon: <i className={`${item.menuIcon}`}/>,
                content: item.menuName,
                onClick: () => this[item.menuFun](item.menuFun)
            }
            if (item.menuFun == 'collection' || item.menuFun == 'help' || item.menuFun == 'pageAddress') {
                obj.disabled = true;
            }
            if (item.menuFun == 'batchDelete') {
                obj.disabled = tableStore.selectedRowKeys.length == 0;
            }
            dropMenuDatas.push(obj);
        })

        return {
            buttons,
            dropMenuDatas
        };
    }

    @action
    handleTopBtnsClick = (item) => {
        const {
            isPanelShow
        } = this.mainTab;

        isPanelShow && this.changePanelStatus(false);
        this[item.menuFun] && this[item.menuFun](item.menuFun)
    }

    log = () => {
        window.setLogViewProps({
            logSmallType: '3046',
        });
    }

    @action
    new = (funcName) => {
        this.openDialog(funcName);
    }

    batchDelete = () => {
        this.showConfirm('batch');
    }

    @action
    custom = () => {
        const {
            tableStore
        } = this.mainTable;

        tableStore.setColSetVisible(true);
        tableStore.tableColSet(true);
    }

    //*************************MainTab*******************************
    @observable mainTab = {
        isPanelShow: false,
        conditionCount: 1,
        form: new WeaForm(),
        conditions: [],
        baseValue: ''
    }

    get buttonsAd() {
        const {
            visible
        } = this.mainDialog, {
            replaceDatas
        } = this.subTab;

        const form = !visible ? this.mainTab.form : this.subTab.form;

        const buttonsAd = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qqfoam`} type="primary" onClick={() => this.handleSearch()}>{getLabel(82529, '搜索')}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@imq5b3`} onClick={() => {form.reset();visible && form.updateFields({
                inviteInfoId:{
                    value:replaceDatas.id,
                    valueSpan:replaceDatas.name,
                    valueObj:[replaceDatas]
                }
            })}}>{getLabel(27088, '重置')}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@10m2rl`} onClick={() => this.changePanelStatus(false)}>{getLabel(32694, '取消')}</Button>),
        ];

        return buttonsAd;
    }

    get searchsAd() {
        if (!this.mainDialog.visible) {
            const {
                form,
                conditions
            } = this.mainTab, {
                isFormInit
            } = form;

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

            return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@e3v1ut`}
                onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && this.handleSearch()}
            >{arr}</Row>
        } else {
            const {
                form,
                conditions
            } = this.subTab, {
                isFormInit
            } = form;
            let outterArray = [];

            isFormInit && conditions.map((c, i) => {
                let innerArray = [];
                c.items.map((field, index) => {
                    const key = field.domkey[0];
                    innerArray.push({
                        com: (
                            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@ly4uhn@${index}`}
                            label={`${field.label}`}
                            labelCol={{span: (index%2==0)?7:6}}
                            wrapperCol={{span: (index%2==0)?17:18}}>
                                {<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@fhsonx@${index}`} fieldConfig={field} form={form} formParams={form.getFormParams()} />}
                        </WeaFormItem>
                        ),
                        colSpan: 1
                    })
                })
                outterArray.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@eawfrh@${i}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={innerArray} col={2} />)
            })

            return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@2e0uyq`}>{outterArray}</Row>
        }
    }

    @action
    clickTab = (key) => {
        this.subTab.curKey = key;
        this.subTab.selectedRowKeys = '';
    }

    @action
    changePanelStatus = (bool) => {
        if (!this.mainDialog.visible) {
            this.mainTab.isPanelShow = bool;
        } else {
            this.subTab.isPanelShow = bool;
        }
    }

    @action
    handleSearch = () => {
        const isPanelShow = !this.mainDialog.visible ? this.mainTab.isPanelShow : this.subTab.isPanelShow;

        isPanelShow && this.changePanelStatus(false);

        if (!this.mainDialog.visible) {
            this.getTableInfo();
        } else {
            this.main.ref.getTableInfo(this.subTab.form.getFormParams());
        }
    }

    @action
    getSearchCondition = () => {
        const params = {};
        let func;
        if (!this.mainDialog.visible) {
            func = 'getSearchCondition';
        } else {
            func = 'getSearchConditionSub';
            Object.assign(params, {
                inviteInfoId: this.mainTable.id
            });
        }

        Api[func](params).then(rs => {
            const {
                api_status,
                conditions
            } = rs;

            if (api_status) {
                if (!this.mainDialog.visible) {
                    this.mainTab.conditions = conditions;
                    this.mainTab.form.initFormFields(conditions);
                } else {
                    this.handleSubConditons(conditions);
                    this.subTab.conditions = conditions;
                    this.subTab.form.initFormFields(conditions);
                }
            } else {
                message.error();
            }
        }).catch(error => {
            message.error();
        });
    }

    handleSubConditons = (conditions) => {
        conditions.map(c => {
            c.items.map(item => {
                const key = item.domkey[0];
                if (key == 'inviteInfoId') {
                    const {
                        browserConditionParam
                    } = item, {
                        replaceDatas
                    } = browserConditionParam;

                    this.subTab.replaceDatas = replaceDatas[0];
                }
            });
        });
    }

    @action
    setSearchsBaseValue = (val) => {
        this.mainTab.baseValue = val;
    }

    @action
    resetSearch = () => {
        this.mainTab.isPanelShow = false;
        this.mainTab.baseValue = ''; //TODO
        this.mainTab.form.reset();
    }

    //*************************MainTable*******************************
    @observable mainTable = {
        tableStore: new TableStore(),
        index: '',
    }

    @action
    getTableInfo = (arg) => {
        const params = {
            qname: this.mainTab.baseValue,
        };
        this.main.id && Object.assign(params, {
            careerPlanId: this.main.id,
            cmd: 'notchangeplan',
        });
        if (arg) {
            Object.assign(params, {
                ...arg,
            });
        } else {
            Object.assign(params, {
                ...this.mainTab.form.getFormParams(),
            });
        }

        this.mainTable.tableStore = new TableStore();

        Api.getTableInfo(params).then(cb => {
            const {
                api_status,
                sessionkey,
            } = cb;

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

    onOperatesClick = (record, rowIndex, operate) => {
        const {
            index
        } = operate, {
            randomFieldId,
            careername,
            careernamespan,
        } = record;

        if (index == '1') {
            this.openDialog(index, randomFieldId);
        }
        if (index == '2') {
            this.mainTable.id = randomFieldId;
            this.showConfirm('del');
        }
        if (index == '3') {
            window.setLogViewProps({
                logSmallType: '3046',
                targetId: randomFieldId,
            });
        }
        if (index == '4') {
            const dialog = WeaTools.createDialog({
                title: getLabel('386999', "应聘情况"),
                moduleName: 'hrm',
                url: addContentPath(`/spa/hrm/engine.html#/hrmengine/recruitLibrary?inviteInfoId=${randomFieldId}`),
                style: {
                    width: 820,
                    height: 650
                },
                callback: (datas) => {},
                onCancel: () => {}
            });
            dialog.show();
        }

    }

    showConfirm = (type) => {
        let _this = this;
        confirm({
            title: getLabel(131329, '信息确认'),
            content: (type == 'batch') ? getLabel(385625, '确定要删除选择的记录吗？') : getLabel(83877, '确定要删除吗？'),
            okText: getLabel(33703, '确定'),
            cancelText: getLabel(32694, '取消'),
            onOk() {
                _this.onOk(type)
            },
            onCancel() {
                return false
            },
        });
    }

    onOk = (type) => {
        this.del(type)
    }

    del = (type) => {
        const {
            tableStore,
            id
        } = this.mainTable;

        const params = {
            inviteInfoIds: (type == 'batch') ? tableStore.selectedRowKeys.toString() : id,
        };

        Api.deleteTableInfo(params).then(rs => {
            const {
                api_status,
                sign
            } = rs;

            if (api_status) {
                if (sign == '1') {
                    message.success(rs.message);
                    this.getTableInfo();
                } else {
                    message.warning(rs.message)
                }
            }
        }).catch(error => {
            message.error();
        });
    }

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

    get buttons() {
        const {
            index
        } = this.mainTable, {
            curKey
        } = this.subTab, {
            loading
        } = this.formInfo;

        let buttons = [];
        if (index == 'new' || (index == '1' && curKey !== '2')) {
            buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@p5io6f`} type="primary" disabled={(curKey == '0') ? loading: this.tableEdit.loading} onClick={(curKey=='1')?this.saveTableEditDatas:this.save}>{getLabel('30986',"保存")}</Button>);
        }

        if (index == 'new') {
            buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@htrn9g`} type="primary" disabled={loading} onClick={() => this.save('saveAndSet')}>{getLabel(32159, '保存并进入详细设置')}</Button>);
        }

        buttons.push(<WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@dyc20i`} datas={this.dropMenuDatas} />);

        return buttons;

    }

    get style() {
        return {
            width: 800,
            height: 720
        }
    }

    get dropMenuDatas() {
        const {
            index
        } = this.mainTable, {
            curKey
        } = this.subTab, {
            loading
        } = this.formInfo;

        let datas = [];
        if (index == 'new' || (index == '1' && curKey !== '2')) {
            datas.push({
                key: '3',
                disabled: loading,
                icon: <i className='icon-coms-Preservation' />,
                content: getLabel('30986', "保存"),
                disabled: (curKey == '0') ? loading : this.tableEdit.loading,
                onClick: (curKey == '1') ? this.saveTableEditDatas : this.save,
            })
        }

        if (index == 'new') {
            datas.push({
                key: '4',
                disabled: loading,
                icon: <i className='icon-coms-Preservation' />,
                content: getLabel(32159, '保存并进入详细设置'),
                disabled: loading,
                onClick: () => this.save('saveAndSet'),
            })
        }

        return datas;
    }

    @action
    openDialog = (index, id) => {
        this.mainTable.index = index;
        this.mainTable.id = id;
        this.mainDialog.visible = true;

        let title;
        if (index == 'new') {
            title = getLabel('17153', "新建招聘信息");
        }
        if (index == '1') {
            title = getLabel('387000', "编辑招聘信息")
        }
        if (index == '4') {
            title = getLabel('387405', "招聘情况")
        }
        this.mainDialog.title = title;

    }

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

    save = (arg) => {
        const {
            form
        } = this.formInfo;

        form.validateForm().then(f => {
            if (f.isValid) {
                const {
                    index,
                    id
                } = this.mainTable, {
                    curKey
                } = this.subTab;

                let func;
                const params = form.getFormParams();

                if (index == 'new') {
                    func = 'add';
                }
                if (index == '1' && curKey == '0') {
                    func = 'edit';
                    Object.assign(params, {
                        inviteInfoId: id
                    })
                }
                this.formInfo.loading = true;

                Api[func](params).then(rs => {
                    const {
                        api_status,
                        sign,
                        inviteInfoId,
                    } = rs;

                    if (api_status) {
                        this.formInfo.loading = false;
                        if (sign == '1') {
                            message.success(rs.message);
                            this.closeDialog();
                            this.getTableInfo();
                            if (arg == 'saveAndSet') this.openDialog('1', inviteInfoId);
                        } else {
                            message.warning(rs.message)
                        }
                    }
                }).catch(error => {
                    message.error(error);
                });
            } else {　　　　　　
                f.showErrors();
                this.setDate(new Date());
            }
        })
    }　　
    @action
    setDate = (date) => {
        this.formInfo.date = date;
    }


    //*************************SubTab*******************************
    @observable subTab = {
        curKey: '0',
        isPanelShow: false,
        conditionCount: 10,
        conditions: [],
        form: new WeaForm(),
        selectedRowKeys: ''
    }

    get subTabDatas() {
        const datas = [{
            key: '0',
            title: getLabel('81711', "基本信息"),
        }, {
            key: '1',
            title: getLabel('15720', "招聘日程"),
        }, {
            key: '2',
            title: getLabel('386999', "应聘情况"),
        }];

        return datas
    }

    get iconButtons() {
        const {
            curKey
        } = this.subTab;

        const btns = [
            <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@fka2v7`} buttonType='add' type="primary" onClick={() => (curKey == '2') ? this.main.ref.openDialog('new') : this.tableEdit.ref.doAdd()}/>,
            <div className='wea-button-icon'>
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@km301q`} type="primary" disabled={this.subTab.selectedRowKeys === ''} onClick={() => this.main.ref.sendMail('sendMail')}>
                     <span title={getLabel('2051',"发送邮件")} className='icon-coms-email' style={{fontSize:25}}></span>
                </Button>
            </div>
        ]

        if (curKey == '1') {
            return [...btns.slice(0, 1), (
                <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@uvwmxp`} 
                    buttonType='del' 
                    type="primary" 
                    disabled={!this.subTab.selectedRowKeys ? true : false}
                    onClick={() => this.tableEdit.ref.doDelete()}
                />
            )]
        }

        return btns;
    }

    @action
    resetSubTab = () => {
        this.subTab.curKey = '0';
        this.subTab.isPanelShow = false;
        this.subTab.conditions = [];
        this.subTab.form = new WeaForm();
    }

    @action
    setSelectedRowKeys = (keys) => {
        this.subTab.selectedRowKeys = keys.toString();
    }

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

    //*************************FormInfo*******************************
    @observable formInfo = {
        form: new WeaForm(),
        conditions: [],
        loading: true,
        date: '',
    }

    @action
    getFormConditions = () => {
        const {
            index,
            id
        } = this.mainTable, {
            form
        } = this.formInfo;

        form.isFormInit && this.resetFormInfo();

        const params = {};
        if (id) {
            Object.assign(params, {
                inviteInfoId: id
            });
        }

        this.main.id && Object.assign(params, {
            careerPlanId: this.main.id,
        });

        Api.getFormConditions(params).then(rs => {
            const {
                api_status,
                conditions,
            } = rs;
            if (api_status) {
                this.formInfo.conditions = conditions;
                this.formInfo.form.initFormFields(conditions);
                this.formInfo.loading = false;
            } else {
                message.error();
            }
        }).catch(error => {
            message.error();
        });
    }

    @action
    resetFormInfo = () => {
        this.formInfo.conditions = [];
        this.formInfo.form = new WeaForm();
        this.formInfo.loading = true;
    }


    handleChange = (cb) => {
        if (Object.keys(cb)[0] == 'useDemandId') {
            this.getUseDemandInfo(cb.useDemandId.value)
        }
    }

    getUseDemandInfo = (id) => {
        const params = {
            useDemandId: id
        };

        Api.getUseDemandInfo(params).then(rs => {
            const {
                api_status,
            } = rs;

            delete rs.api_status;

            if (api_status) {
                this.formInfo.form.updateFields({
                    ...rs
                })
            } else {
                message.error();
            }
        }).catch(error => {
            message.error();
        });
    }


    //*************************TableEdit*******************************
    @observable tableEdit = {
        table: [],
        loading: true,
    }

    @action
    exportDatas = (datas, index) => {
        this.tableEdit.table[index].datas = datas;
    }

    getTableEditDatas = () => {
        const params = {
            inviteInfoId: this.mainTable.id,
        };
        Api.getTableEditDatas(params).then(rs => {
            const {
                api_status,
                table,
            } = rs;
            if (api_status) {
                this.tableEdit.table = table;
                this.tableEdit.loading = false;
            } else {
                message.error();
            }
        }).catch(error => {
            message.error();
        });
    }

    saveTableEditDatas = () => {
        const {
            table
        } = this.tableEdit;

        if (!this.compareTime(table)) {
            return
        }

        const params = {
            inviteInfoId: this.mainTable.id
        };

        table.map(t => {
            Object.assign(params, this.jsonTranslation(t.datas));
            Object.assign(params, {
                [t.rownumName]: t.datas.length
            });
        })

        this.tableEdit.loading = true;

        Api.saveInviteSchedule(params).then(rs => {
            const {
                api_status,
                sign,
            } = rs;

            if (api_status) {
                this.tableEdit.loading = false;
                if (sign == '1') {
                    message.success(rs.message);
                } else {
                    message.warning(rs.message)
                }
            }
        }).catch(error => {
            message.error(error);
        });
    }

    compareTime = (table) => {
        for (let i = 0; i < table.length; i++) {
            const tb = table[i];
            for (let j = 0; j < tb.datas.length; j++) {
                const data = tb.datas[j];
                const {
                    stepStartDate,
                    stepEndDate
                } = data;

                if (stepStartDate && stepEndDate && !this.isLater(stepStartDate, stepEndDate)) {
                    message.warning(`${getLabel('15323',"第")} ${j + 1} ${getLabel('27592',"行")}${getLabel(387072, '结束时间需要大于开始时间！')}`);
                    return false
                }
            }
        }
        return true
    }

    jsonTranslation = (datas) => {
        const obj = {};
        datas.map((data, index) => {
            Object.keys(data).map(key => {
                obj[`${key}_${index}`] = data[key]
            })
        });
        return obj
    }

    isLater = (startTime, endTime) => {
        let arr = [];
        ['startTime', 'endTime'].map(v => {
            arr.push(Date.parse(eval(v).replace(/-/g, "/")));
        })

        const [st, et] = arr;

        if (st > et) {
            return false
        }
        return true

    }


    @action
    resetTableEditDatas = () => {
        this.tableEdit.table = [];
        this.tableEdit.loading = true;
    }

    @action
    setRef = (com) => {
        this.tableEdit.ref = com;
    }

}