import {
    observable,
    action,
    computed,
    extendObservable
} from 'mobx';
import * as mobx from 'mobx';
import * as Api from '../apis/resource'; // 引入API接口文件
import {
    WeaForm, WeaTableNew
} from 'comsMobx';
import {
    Modal,
    message,
    Button
} from 'antd'
import {
    WeaSelect,
    WeaInputSearch,
    WeaLocaleProvider,
} from 'ecCom';
import {
    i18n
} from '../public/i18n';
import { getSecondPath } from '../util/index'
import { cloneDeep, isEmpty, trim } from 'lodash';
import HrmBaseStore from './baseStore';


const getLabel = WeaLocaleProvider.getLabel;
const toJS = mobx.toJS;
const {
    TableStore
} = WeaTableNew;


export class ResourceStore extends HrmBaseStore{
    @observable tableStore = new TableStore();
    @observable topMenu = []
    @observable rightMenu = [];
    @observable condition = [];
    @observable searchCondition = [];
    @observable defaultCondition = [];
    @observable isEdit = true;
    @observable isNew = true;
    @observable isPanelShow = false; //高级搜索面板
    @observable form2 = new WeaForm();
    @observable form = new WeaForm();
    @observable lastName = '';
    @observable isBaseValue = true;

    @observable conditionNum = 8;
    @observable ids = ''; //选择行id
    @observable searchConditionLoading = false;
    @observable nEdialogTitle = '';
    @observable visible = false;
    @observable dialogLoading = true;
    @observable userId = '';
    @observable date = '';
    @observable exSpinning = false;

    @observable defaultShowLeft = true;
    @observable companysId = 1
    @observable hasRight = '';
    @observable loginId = '';

    @observable selectTreeNodeInfo;

    @observable enable = false;
    @observable _showRadioGroup = false;
    @computed get showRadioGroup() {
 return this._showRadioGroup 
}
    set showRadioGroup(v) {
        this._showRadioGroup = v;
        setTimeout(() => {
            this.reCalculateTableHeight = new Date().getTime();
        }, 0)
    }

    domRef = {};
    @observable _reCalculateTableHeight = new Date().getTime();
    @computed get reCalculateTableHeight() {
 return this._reCalculateTableHeight 
}
    set reCalculateTableHeight(v) {
 this._reCalculateTableHeight = v 
}
    @computed get tableHeihgt() {
        this.reCalculateTableHeight;
        const topHeight = this.domRef.top && this.domRef.top.refs.content ? this.domRef.top.refs.content.clientHeight : 0;
        const tabHeight = this.domRef.tab ? $(this.domRef.tab)[0].clientHeight : 0;
        const h = topHeight - tabHeight;
        return h <= 0 ? 0 : h;
    }

    @action setDomRef = (dom, type) => {
        dom && Object.assign(this.domRef, { [type]: dom }) && setTimeout(() => this.reCalculateTableHeight = new Date().getTime(), 500);
    }

    @observable rangeConditions = [];
    @observable radioParams = {};

    @observable refreshRadioGroup = new Date().getTime();
    @computed get radioGroupConfig(){
        this.refreshRadioGroup;
        return {
          config: [
            ...this.rangeConditions
          ],
          key: new Date().getTime(),
          onChange: this.onRadioGroupChangeHandle
        }
    }

    @action onRadioGroupChangeHandle = params => { 
        this.radioParams = params;
        this.form2.reset();
        this.getTableInfo();
    }


    @action("列表") getTableInfo() {
        this.tableStore = new TableStore();
        let params = {};
        if(this.isEmptyObject(this.radioParams)) {
            params = {
                isQuickSearch:false,
                ...this.selectTreeNodeInfo,
                
            }
            //外部INPUT搜索
            if (this.isBaseValue) {
                params = {
                    ...params,
                    lastName: this.lastName
                };
            }else {
                params = {
                    ...params,
                    ...this.form2.getFormParams(),
                };
            }
        }else {
            params = {
                ...this.radioParams,
                ...this.selectTreeNodeInfo,
                isQuickSearch:true
            }
        }
        //this.form2.resetForm();
        Api.getSearchList(params).then(res => {
            if (res.code === 200) {
                res.data.datas && this.tableStore.getDatas(res.data.datas, 1);
            } else {
                message.warning(res.msg);
            }
        }, error => {
            message.warning(error.msg);
        })
    }

    @action("nodetree事件") doSearch(params) {
        this.selectTreeNodeInfo = params;
        this.showRadioGroup = true;
        this.getTableInfo();
    }

    @action("保存") save() {
        let params = {
            ...this.form.getFormParams()
        };
        this.form.validateForm().then(f => {
            if (f.isValid) {
                Api.add(params).then(response => {
                    return response.json()
                }).then(data => {
                    if (data.code === 200) {
                        message.success(data.msg,1);
                        this.getTableInfo();
                        this.setVisible(false);
                    } else {
                        message.warning(data.msg);
                    }
                }).catch(error => {
                    message.warning(error.msg);
                })
            } else {
                f.showErrors();
                this.setDate(new Date());
            }
        });
    }

    @action("新增表单") getForm() {
        let params = this.isNew ? {} : {
            id: this.userId
        }
        this.setDialogLoadingStatus(true);

        Api.getSchemeForm(params).then(res => {
            if (res.code === 200) {
                this.setDialogLoadingStatus(false);
                res.data.condition && this.setCondition(res.data.condition);
                res.data.condition && this.form.initFormFields(res.data.condition);
            } else {
                message.warning(res.msg);
            }
        }, error => {
            message.warning(error.msg);
        })

    }



    @action("快捷搜索") getQuickSearchCondition() {
        Api.getQuickSearchCondition().then(res => {
            if (res.code === 200) {
                this.rangeConditions = res.data.rangeConditions;
                this.enable = res.data.enable;
            } else {
                message.warning(res.msg);
            }
        }, error => {
            message.warning(error.msg);
        })
    }

    @action("顶部按钮") getHasRight() {
        Api.getHasRight().then(res => {
            if (res.code === 200) {
                this.setHasRight(res.data.hasRight);
                this.loginId = res.data.loginId;
                this.customTemplateId = res.data.customTemplateId;
                this.searchTemplateId = res.data.searchTemplateId;
                res.data.rightMenu && this.setRightMenu(res.data.rightMenu);
                res.data.topMenu && this.setTopMenu(res.data.topMenu);
                //1.获取高级搜索内容
                this.getHSearchTemplate(res.data.searchTemplateId);
                //2.获取列定制内容
                this.getSearchTemplate(res.data.customTemplateId);
            } else {
                message.warning(res.msg);
            }
        }, error => {
            message.warning(error.msg);
        })
    }

    @action("导出") async export() {
        const params = {
            ...this.form.getFormParams()
        }
        this.exSpinning = true;
        await Api.exportResource(toJS(this.tableStore.selectedRowKeysAllPages).toString());
        this.exSpinning = false;
        this.tableStore.selectedRowKeys = [];
        
    }

    @action("另存为版本") version(id) {
        Api.version({ id: id }).then(res => {
            if (res.code === 200) {
                message.success(res.msg);
            } else {
                message.warning(res.msg);
            }
        }, error => {
            message.warning(error.msg);
        })
    }


    /** ============================================================================================= */

    @observable searchDialog = {
        visible: false,
        loading: false
    }

    @observable templates = [];
    @observable customTemplates = [];
    @observable searchTemplateName = '';
    @observable searchTemplateId = "-1";
    @observable customTemplateName = '';
    @observable customTemplateId = '-1';

    @observable search = false;
    SEARCHDIALOG = {
        hasScroll: false,
        icon: 'icon-coms-hrm',
        iconBgcolor: '#217346',
        onCancel: () => this.closeSearchDialog(),
        style: {
            width: 700,
            height: 450
        },
        moreBtn: {
            datas: []
        },
    }


    TRANSFER = {
        height: 350,
        renderItem: (items) => this.renderItem(items),
        filterLeft: (items) => this.filterLeft(items),
        filterRight: (items) => this.filterRight(items),
        onChange: (v) => this.updateTransferKeys(v)
    }

    @observable transfer = {
        transferDatas: [],
        transferKeys: [],
        transferOptions: [],
        transferSelectedKey: '0',
        transferleftIptVal: '',
        transferRightIptVal: ''
    }

    @action("常用条件定制保存") saveHrmSearchUserDefine = () => {
        this.closeSearchDialog();
        this.getSearchCondition(false);
    }

    @action("列定制保存") saveCustomDefine = () => {
        if (this.customTemplateId == '-1') {
            message.error(getLabel(547650,'默认模板不能修改,将返回默认模板列'));
    
        }   
        const params = {
            columns: this.transfer.transferKeys,
            templateId: this.customTemplateId
        }
        Api.saveColumnsCustomTemplate(params).then(res => {
            if (res.code === 200) {
                this.searchDialog.visible = false;
                this.getTableInfo();
            }else{
                message.error(getLabel(547857,'该模板字段内容仅管理员可操作，即将返回默认设置值'));
                this.searchDialog.visible = false;
                this.getTableInfo();
            }
        }, error => {
            message.warning(error.msg);
        })
    }

    @action("将当前模板应用到所有人") setOverAll = () => {
        if (this.customTemplateId == '-1') {
            return message.error(getLabel(547854,'默认模板不可应用,请选择其它模板'));
        } 
        const params = {
            templateId: this.customTemplateId
        }
        Api.setOverAll(params).then(res => {
            if (res.code === 200) {
                message.success(res.msg);
            }
        }, error => {
            message.warning(error.msg);
        })
    }

   



    inputSearchStyle = {
        width: "105px",
        float: "right",
        marginTop: "5px",
        marginLeft: "10px"
    }
    selectStyle = {
        marginTop: "-1px",
        width: "85px",
        float: "right"
    }
    @computed get leftHeader() {
        const {
            transferleftIptVal,
            transferOptions,
            transferSelectedKey
        } = this.transfer;
        return (
            <div className="trasfer-header">
                <span>{getLabel(547648,'待选')}</span>
                <WeaInputSearch
                    style={this.inputSearchStyle}
                    value={transferleftIptVal}
                    onSearchChange={this.updateTransferleftIptVal}
                />
                <WeaSelect
                    style={this.selectStyle}
                    options={transferOptions}
                    value={transferSelectedKey}
                    onChange={this.updateTransferSelectedKey}
                />
            </div>
        )
    }

    @computed get rightHeader() {
        const {
            transferRightIptVal,
        } = this.transfer;
        return (
            <div className="trasfer-header">
                <span>{getLabel(547649,'已选')}</span>
                <WeaInputSearch
                    style={this.inputSearchStyle}
                    value={transferRightIptVal}
                    onSearchChange={this.updateTransferRightptVal}
                />
                <WeaSelect
                    style={this.selectStyle}
                    options={this.search ? this.templates : this.customTemplates}
                    value={this.search ? this.searchTemplateId : this.customTemplateId}
                    onChange={v => this.getTemplateSelectKeys(v)}
                />
            </div>
        )
    }

    renderItem = (item) => {
        const {
            label,
            title
        } = item;
        return (<div className="trasfer-list-item" style={{ "padding": "10px 20px", "borderBottom": "1px solid #ddd" }}>
            <div className="top text-overflow" style={{ "marginBottom": "4px" }} title={label}>{label}</div>
            <div className="bottom text-overflow" style={{ "color": "#999" }} title={title}>{title}</div>
        </div>)
    };

    filterLeft = (items) => {
        let leftItems = cloneDeep(items);
        const {
            transferleftIptVal,
            transferSelectedKey
        } = this.transfer;
        if (transferSelectedKey) {
            leftItems = leftItems.filter((item) => item.idx == transferSelectedKey)
        }
        if (trim(transferleftIptVal)) {
            leftItems = leftItems.filter((item) => item.label.indexOf(trim(transferleftIptVal)) > -1)
        }
        return leftItems
    }

    filterRight = (items) => {
        let rightItems = cloneDeep(items);
        const {
            transferRightIptVal
        } = this.transfer;
        if (trim(transferRightIptVal)) {
            rightItems = rightItems.filter((item) => item.label.indexOf(trim(transferRightIptVal)) > -1)
        }
        return rightItems
    }

    @action("穿梭框变化回调") updateTransferKeys = (v) => {
        this.transfer.transferKeys = v;
    }

    /******显示列定制功能 *************/
    @action("tab显示列定制点击") openCustomDialog = () => {
        this.search = false;
        this.searchDialog.visible = true;
    }

    @action("列定制模板") getSearchTemplate = (customTemplateId) => {
        Api.getSearchTemplate({ type: 'custom',id:customTemplateId}).then(res => {
            if (res.code === 200) {
                this.setCustomTemplates(res.data.templates);
                this.getCustomTransferData();
            } else {
                message.warning(res.msg);
            }
        }, error => {
            message.warning(error.msg);
        })
    }

    @action("列定制穿梭框内容") getCustomTransferData() {
        Api.getCustomTransferData(this.customTemplateId).then(result => {
            if (result.code === 200) {
                const { transferDatas, transferKeys, transferOptions } = result.data;
                this.transfer.transferDatas = transferDatas;
                this.transfer.transferKeys = transferKeys;
                this.transfer.transferOptions = transferOptions;
                
            } else {
                message.warning(result.msg);
            }
        }, error => {
            message.warning(error.msg);
        })
    }

    @action("列定制存为模板保存") saveCustomTemplate = () => {
        if (this.customTemplateName == '') {
            message.error(getLabel(547652,'列定制模板的名称不能为空'));
        } else {
            const params = {
                showname: this.customTemplateName,
                fields: this.transfer.transferKeys.toString()
            };
            Api.saveCustomTemplate(params).then(response => {
                return response.json()
            }).then(res => {
                if (res.code === 200) {
                    debugger
                    this.setCustomTemplates(res.data.result.templates);
                    this.setCustomTemplateId(res.data.result.id);
                    message.success(res.msg);
                } else {
                    message.warning(res.msg);
                }
            }).catch(error => {
                message.warning(error.msg);
            })
        }
    }

    @action("列定制模板管理") getEditTable() {
        this.searchDialog.visible = false;
        this.temlateManageDialog.visible = true;
        this.relatedData.loading = true;
        this.relatedData.datas = [];
        Api.getEditTable().then(result => {
            if (result.code === 200) {
                const { columns, datas, selectedData } = result.data;
                extendObservable(this.relatedData, {
                    datas: datas,
                    columns: columns
                });
                selectedData && extendObservable(this.relatedData, {
                    selectedData: selectedData
                });
                extendObservable(this.relatedData, {
                    loading: false
                });
            } else {
                message.warning(result.msg);
            }

        }, error => {
            message.warning(error.msg);
        })
    }

    @action("列定制模板管理保存") updateCustomTemplate() {
        let params = this.editTableParams;
        Api.updateCustomTemplate(params).then(res => {
            let { code, msg } = res;
            if (code === 200) {
                message.success(msg || getLabel(30700,'操作成功'));
                this.getSearchTemplate(this.customTemplateId);
                
            } else {
                message.error(msg);
            }
        }).catch(error => {
            message.error(error);
        });
    }


    /******************************************* 高级搜索内容******************************************/
    @action("高级搜索模板内容") getHSearchTemplate = (searchTemplateId) => {
        Api.getSearchTemplate({ type: 'search',id: searchTemplateId }).then(res => {
            if (res.code === 200) {
                this.setTemplates(res.data.templates);
                this.getSearchCondition();
            } else {
                message.warning(res.msg);
            }
        }, error => {
            message.warning(error.msg);
        })

    }

    //key为true时根据模板id查找模板内容
    @action("高级搜索表单") getSearchCondition(key = true) {
        this.setScLoadingStatus(true);
        this.form2 = new WeaForm();
        let params = {};
        key ? params = {
            templateId: this.searchTemplateId
        } : params = {
            selectKeys: this.transfer.transferKeys,
        }
        Api.getAdvanceSearchCondition(params).then(res => {
            if (res.code === 200) {
                this.setScLoadingStatus(false);
                res.data.conditions && this.setSearchCondition(res.data.conditions);
                res.data.defaultcondition && this.setDefaultCondition(res.data.defaultcondition);
                res.data.defaultcondition && this.form2.initFormFields(res.data.defaultcondition);
            } else {
                message.warning(res.msg);
            }
        }, error => {
            message.warning(error.msg);
        })
    }

    @action("高级搜索模板切换") changeSearchTemplate(v) {
        this.searchTemplateId = v;
        this.getSearchCondition();
    }

    @action("常用条件定制") formatTransfer = () => {
        const transferDatas = []
        const transferKeys = []
        const transferOptions = [{
            key: "",
            showname: ""
        }]
        this.transfer.transferSelectedKey = '0';
        this.transfer.transferleftIptVal = '';
        this.transfer.transferRightIptVal = '';
        this.searchCondition.forEach((c, idx) => {
            transferOptions.push({
                key: `${idx}`,
                showname: c.title,
            })
            c.items.forEach((i) => {
                transferDatas.push({
                    id: i.domkey[0],
                    label: i.label,
                    title: c.title,
                    idx: `${idx}`
                })
            })
        })
        this.defaultCondition.forEach((c, idx) => {
            c.items.forEach((i) => {
                transferKeys.push(i.domkey[0]);
            })
        })
        this.transfer.transferDatas = transferDatas;
        this.transfer.transferKeys = transferKeys;
        this.transfer.transferOptions = transferOptions;
        this.searchDialog.visible = true;
    }


    @action("高级搜索常用条件定制模板切换") getTemplateSelectKeys = v => {
        if (!this.search) {
            this.customTemplateId = v;
        }

        const params = {
            templateId: v,
            type: this.search ? 'search' : 'custom'
        }
        Api.getTemplateSelectKeys(params).then(res => {
            if (res.code === 200) {
                this.transfer.transferKeys = res.data.split(",");
            } else {
                message.warning(res.msg);
            }
        }, error => {
            message.warning(error.msg);
        })
    }


    @action("高级搜索模板保存") saveTemplate = () => {
        if (this.searchTemplateName == '') {
            message.error(getLabel(547651,'搜索模板的名称不能为空'));
        } else {
            const fields = [];
            this.defaultCondition.forEach((c, idx) => {
                c.items.forEach((i) => {
                    fields.push(i.domkey[0]);
                })
            })
            const params = {
                showname: this.searchTemplateName,
                fields: fields.toString()
            }

            Api.saveSearchTemplate(params).then(response => {
                return response.json()
            }).then(data => {
                if (data.code === 200) {
                    this.setSearchTemplateId(data.data);
                    this.getHSearchTemplate(data.data);
                } else {
                    message.warning(data.msg);
                }
            }).catch(error => {
                message.warning(error.msg);
            })
        }

    }


    @action("高级搜索模板删除") deleteSearchTemplate = () => {

        if (this.searchTemplateId == -1) {
            return message.error(getLabel(547653,'默认模板不可删除'));
        }
        Api.deleteSearchTemplate({ id: this.searchTemplateId }).then(response => {
            return response.json()
        }).then(data => {
            if (data.code === 200) {
                message.success(data.msg);
                this.setSearchTemplateId('-1');
                this.getHSearchTemplate('-1');
            } else {
                message.warning(data.msg);
            }
        }).catch(error => {
            message.warning(error.msg);
        })
    }

    @observable relatedData = {
        datas: [],
        columns: [],
        loading: true,
        selectedData: {}
    };

    @observable temlateManageDialog = {
        title: getLabel(547582,'模板管理'),
        visible: false,
        hasScroll: true,
        icon: 'icon-coms-hrm',
        iconBgcolor: '#217346',
        onCancel: () => this.closeTemlateManageDialog(),
        style: {
            width: 600,
            height: 450
        },
        buttons: [<Button type='primary' onClick={() => this.updateCustomTemplate()}>{getLabel(547360,'保存')}</Button>]
    }

    @computed get editTableParams() {
        let datas = this.relatedData.datas;
        let selectedData = this.relatedData.selectedData.status;
        let params = this.arrToJson(toJS(datas), toJS(selectedData), 'status');
        params.rownum = datas.length;
        return params;
    }

    


    @action updateTransferleftIptVal = (v) => {
        this.transfer.transferleftIptVal = v;
    }

    @action updateTransferSelectedKey = (v) => {
        this.transfer.transferSelectedKey = v;
    }

    @action updateTransferKeys = (v) => {
        this.transfer.transferKeys = v;
    }


    @action updateTransferRightptVal = (v) => {
        this.transfer.transferRightIptVal = v;
    }



    @action("高级搜索显示列定制") openSearchDialog = () => {
        this.formatTransfer();
    }

   

    @action closeSearchDialog = () => {
        this.searchDialog.visible = false;
    }

    @action closeTemlateManageDialog = () => {
        this.temlateManageDialog.visible = false;
    }

    setTableEditDatas(e) {
        e.map(item => {
            for (let key in item) {
                if (key == "undefined") {
                    delete item[key];
                }
                if (!item["isused"]) {
                    item["isused"] = "";
                }
            }
        });
        extendObservable(this.relatedData, {
            datas: e
        });
    }

    setEnableRows(e) {
        extendObservable(this.relatedData, {
            selectedData: {
                isused: e
            }
        });
    }

    updateFields(val) {
        this.form2.updateFields({
            "-1_hrm_lastname": {
                value: val
            }
        });
    }

    hideRadioGroup() {
        this.radioParams = {};
        this.showRadioGroup = false;
    }

    setSearchCondition(condition) {
        this.searchCondition = condition;
    }

    setDefaultCondition(defaultcondition) {
        this.defaultCondition = defaultcondition;
    }

    @action setTemplates(datas) {
        this.templates = datas;
    }

    @action setSearchTemplateId(id) {
        this.searchTemplateId = id;
    }
  

    @action setCustomTemplates(datas) {
        this.customTemplates = datas;
    }

    @action setCustomTemplateId(id) {
        this.customTemplateId = id;
    }

    setScLoadingStatus(bool) {
        this.searchConditionLoading = bool;
    }

    setPanelStatus(bool) {
        this.search = true;
        this.isPanelShow = bool;
    }

    arrToJson(arr, rows, rowKey = "isused") {
        let json = {};
        const _rows = isEmpty(arr) ? [] : rows;
        _rows && _rows.map(index => {
            arr[index][rowKey] = "1";
        });
        arr.map((item, index) => {
            if (!item[rowKey]) item[rowKey] = "0";
            for (let key in item) {
                json[key + "_" + index] = item[key];
            }
        });

        return json;
    }

    setLastName(val) {
        this.lastName = val;
    }

    isEmptyObject(obj) {
        for (let key in obj) {
            return false;
        }
        return true;
    }

    setIds(ids) {
        this.ids = ids;
    }

    scLoadingReset() {
        this.searchConditionLoading = true;
    }


    formReset() {
        this.form = new WeaForm();
    }

    dialogLoadingReset() {
        this.dialogLoading = true;
    }

    setVisible(bool) {
        this.visible = bool;
        this.formReset();
        !bool && this.dialogLoadingReset();
    }

    setDialogLoadingStatus(bool) {
        this.dialogLoading = bool;
    }

    setNeDialogTitle(title) {
        this.nEdialogTitle = title;
    }

    setIsNew(bool) {
        this.isNew = bool;
    }

    setCondition(condition) {
        this.condition = condition;
    }

    setUserId(userId) {
        this.userId = userId;
    }

    setDate(date) {
        this.date = date;
    }

    setTopMenu(topMenu) {
        this.topMenu = topMenu;
    }

    setRightMenu(rightMenu) {
        this.rightMenu = rightMenu;
    }

    setHasRight(bool) {
        this.hasRight = bool;
    }

}