import { observable, action, computed } from 'mobx';
import {WeaLocaleProvider} from 'ecCom';
import {WeaTableNew} from 'comsMobx';
import {Button, message} from 'antd';
import HrmBaseStore from './baseStore';
import * as api from '../apis/outside';
import moment from 'moment';
import {i18n} from '../public/i18n';
import {addContentPath} from '../util/index'

const {TableStore} = WeaTableNew;
const {getLabel} = WeaLocaleProvider;

class OutsideV2 extends HrmBaseStore{
    @action init = async () => {
        this.clearData();
        this.getTab();
        this.getData();
    }
    
    @action clearData = () => {
        this.selectedDate = new moment().format('YYYY-MM-DD');
        this.selectedIds = '';
        this.isMult = false;
        this.checkedDatas = false;
        this.selectedTabKey = '0';
        this.selectedDateTabKey = '0';
        this.hasRight = true;
    }

    @computed get topProps(){
        const d = ecCom.WeaTools.getIconBGC('hrm');
        return {
            title: getLabel('518268', "外勤签到"),
            icon: <i className={d.icon}/>,
            iconBgcolor: d.iconBgcolor,
            showDropIcon: true,
            ...this.topBtnAndMenus
        }
    }

    @computed get topBtnAndMenus(){
        const buttons = [], dropMenuDatas = [];
        this.selectedTabKey == '2' && [{isTop: '1', menuIcon: 'icon-coms-export', menuName: getLabel(28343, '导出Excel'), onClickHandle: this.exportData}].map((btn, index) => {
            const {isTop, menuIcon, menuName, onClickHandle, disabled} = btn;
            if(isTop == '1'){
                buttons.push(
                    (
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bv327s@${index}`} type='primary' onClick={onClickHandle} disabled={disabled||false}>{menuName}</Button>
                    )
                )
            }
            dropMenuDatas.push({
                key: index.toString(),
                content: menuName,
                icon: <i className={menuIcon}/>,
                onClick: onClickHandle,
                disabled: disabled || false
            });
        })
        return {buttons, dropMenuDatas};
    }

    //#region orgtreee props
    @observable _isMult = false;
    @computed get isMult(){return this._isMult}
    set isMult(v){
        this._isMult = v;
        !v && (this.checkedDatas = []);
    }

    @observable checkedDatas = [];
    @observable _browserReplaceDatas = [];
    @computed get browserReplaceDatas(){return this._browserReplaceDatas}
    set browserReplaceDatas(v){this._browserReplaceDatas = v}
    @computed get rootid(){
        if(this.browserReplaceDatas.length > 0)
            return {
                rootid: this.browserReplaceDatas[0].id
            }
        return {};
    }
    
    renderNodeId = item => item.id;

    treeNodeClickHandle = e => {
        if(this.isMult)
            return;
        this.selectedIds = e.node.props.id;
        this.hrmName = e.node.props.name;
        this.getData();
    }

    onTreeNodeCheckHandle = (ids, datas) => {
        if(!this.isMult)
            return;
        if(ids){
            this.selectedIds = ids.join(',');
        }
        this.getData();
    }

    @computed get orgTreeProps(){
        return {
            dataUrl: '/api/hrm/base/getHrmResourceTree',
            ref: 'orgTree',
            rootKey: 'rootManager',
            renderNodeId: this.renderNodeId,
            isMult: this.isMult,
            checkStrictly: false,
            checkedDatas: this.checkedDatas,
            treeNodeClick: this.treeNodeClickHandle,
            onCheck: this.onTreeNodeCheckHandle,
            params: this.rootid
        }
    }
    //#endregion

    //#region tab
    @observable selectedTabKey = '';
    @observable tabData = [];

    @computed get tabProps(){
        return {
            datas: this.tabData,
            keyParam: 'viewcondition',
            selectedKey: this.selectedTabKey,
            onChange: this.onTabChangeHandle
        }
    }

    @action getTab = () => {
        this.tabData = [
            {
                viewcondition: '0',
                title: getLabel('387101', '时间视图'),
            }, {
                viewcondition: '1',
                title: getLabel('387102', '地图视图'),
            }, {
                viewcondition: '2',
                title: getLabel('387103', '明细'),
            },
        ];
    }

    @action onTabChangeHandle = async key => {
        this.selectedTabKey = key;
        if(key == 2){
            this.hasRight = true;
            this.selectedIds = '';
            this.draw = null;
            this.conditionParams = {};
            this.getCondition();
        }else
            this.getData();
    }
    //#endregion

    //#region searchbar
    @observable _selectedDateTabKey = '0';
    @computed get selectedDateTabKey(){return this._selectedDateTabKey}
    set selectedDateTabKey(v){this._selectedDateTabKey = v}

    get dateTabDatas(){
        return [{
            title: getLabel(518269, '今天'),
            key: '0',
        }, {
            title: getLabel('82640', "昨天"),
            key: '1',
        }, {
            title: getLabel(383428, '本月'),
            key: '2',
        }];
    }

    @observable _selectedDate = new moment().format('YYYY-MM-DD');
    @computed get selectedDate(){return this._selectedDate}
    set selectedDate(v){this._selectedDate = v}

    @action onDatePickerChangeHandle = (v1, v2) => {
        this.selectedDate = v2;
        this.getData();
    }

    @computed get datePickerProps(){
        return {
            arrow: true,
            type: (this.selectedDateTabKey == 2 ? 'month' : 'day'),
            date: this.selectedDate,
            onChange: this.onDatePickerChangeHandle
        }
    }
    //#region 

    //#region 时间视图、地图视图获取数据
    selectedIds = '';
    hrmName = '';

    @observable hasRight = false;
    @observable timeData = [];

    @observable table = new TableStore();

    @observable _showSignInfo = false;
    @computed get showSignInfo(){return this._showSignInfo}
    set showSignInfo(v){
        this._showSignInfo = v;
        this.getData(true);
    }

    @action getData = async (refresh = false) => {
        this.showWeaLoadingGlobal();
        const params = {
            cmd: (this.selectedTabKey == '0' ? 'timeData' : (this.selectedTabKey == '1' ? 'mapData' : 'detialData')),
        }
        if(this.selectedTabKey != 2){
            Object.assign(params, {
                loaddata: '1',
                signtype: (this.showSignInfo ? 1 : 0),
                fromDate: this.selectedDate,
                toDate: this.selectedDate
            });
            this.selectedIds && Object.assign(params, {resourceId: this.selectedIds});
        }else{
            Object.assign(params, this.conditionParams);
        }
        
        const data = await api.getHrmMobileSignInInfo(params);
        this.hasRight = (data.status == '1');
        if(this.selectedTabKey == '2'){
            this.table = new TableStore();
            this.table.getDatas(data.sessionkey, 1);
        }else{
            this.timeData = data.result || [];
            this.selectedTabKey == '1' && refresh && this.draw && this.draw();
        }

        this.hideWeaLoadingGlobal();
    }
    //#endregion

    //#region 明细条件
    @observable config = [];
    conditionParams = {};
    @action onChangeHandle = params => {
        console.debug(params);
        const {typeselect, fromDate, toDate} = params;
        if(typeselect == '6' && fromDate.length == 0 && toDate.length == 0) return;
        this.conditionParams = params;
        this.getData();
    }

    @computed get radioGroupProps(){
        return {
            config: this.config,
            onChange: this.onChangeHandle
        }
    }

    @action getCondition = async () => {
        const data = await api.getSearchCondition();
        if(data.api_status){
            const {condition} = data;
            const configfirstrow = {
                label: i18n.label.date(),
                options: [{
                    key: '0',
                    showname: i18n.label.all(),
                }, {
                    key: '1',
                    showname: i18n.label.today(),
                    selected: true,
                }, {
                    key: '2',
                    showname: i18n.label.tswk(),
                }, {
                    key: '3',
                    showname: i18n.label.tsmth(),
                }, {
                    key: '4',
                    showname: i18n.label.tssn(),
                }, {
                    key: '5',
                    showname: i18n.label.tsyr(),
                }, {
                    key: '7',
                    showname: i18n.label.preMonth(),
                }, {
                    key: '8',
                    showname: i18n.label.preYear(),
                }, {
                    key: '6',
                    showname: i18n.label.dateRange(),
                }],
                domkey: ['typeselect'],
                selectLinkageDatas: {
                    6: {
                    conditionType: 'RANGEPICKER',
                    domkey: ['fromDate', 'toDate'],
                    },
                },
                labelcol: 4,
                fieldcol: 20,
            };
            condition[0].items.unshift(configfirstrow);
            this.config = condition[0].items;
        }else{
            message.error(data.message);
        }
    }
    //#endregion

    @action handleViewClick = async id => {
        const data = await api.getShowSignImg({id});
        const {
            signImgIds
        } = data;
    
        if (signImgIds) {
            const imgPool = signImgIds.split(',').map(id => `/weaver/weaver.file.FileDownload?fileid=${id}`);
            this.doCarousel(imgPool, 0);
        }
    }

    doCarousel = (imgPool, index) => {
        if (window.IMCarousel) {
            window.IMCarousel.showImgScanner4Pool(true, imgPool, index, null, window.top);
        } else {
            loadjs([
                addContentPath('/social/js/drageasy/drageasy.js'), 
                addContentPath('/social/js/bootstrap/js/bootstrap.js?v=20171218'), 
                addContentPath('/social/im/js/IMUtil_wev8.js'), 
                addContentPath('/social/js/imcarousel/imcarousel.js')
            ], () => {
                window.IMCarousel.showImgScanner4Pool(true, imgPool, index, null, window.top);
            });
        }
    }

    @action exportData = () => this.table.exportAll();

    @observable _locationInfoDialogVisible = false;
    @computed get locationInfoDialogVisible(){return this._locationInfoDialogVisible}
    set locationInfoDialogVisible(v){this._locationInfoDialogVisible = v}

    @action onLocationInfoDialogCancelHandle = () => this.locationInfoDialogVisible = false;

    @observable selectedSignInfo;
    @action showLocationInfo = signInfo => {
        this.selectedSignInfo = signInfo;
        this.locationInfoDialogVisible = true;
    }

    @computed get locationInfoDialogProps(){
        return {
            visible: this.locationInfoDialogVisible,
            onCancel: this.onLocationInfoDialogCancelHandle,
            closable: true,
            style: {width: 700, height: 500},
            title: getLabel('386506',"位置详情"),
            icon: 'icon-coms-hrm',
            iconBgcolor: '#008572',
            parentClassName: 'outside_location_info'
        }
    }
}

export const outsideV2 = new OutsideV2(); 