<template>
<div v-show="btnShow">
    <template v-if="tooltype === 'form'">
        <div  v-if="visible">
        <Row v-if="'horizontal' === type"  type="flex" justify="start" :gutter="myConfig.spacing">
            <Col v-for="(btn,index) in btnList" :key="'btn_' + index" v-show="btn.visible" >
                <Ebutton v-if="btntype === 'Ebutton'" :ref="btn.name" :config="btn" @click="click" :amplify="amplify" :fontplacement="fontplacement" :dynamic="myConfig.btnDynamic"></Ebutton> 
                <Button v-if="btntype === 'Button'"  :ref="btn.name" @click="action(btn.name)" :icon="btn.iconcls" :type="btn.type" :size="buttonSize" :disabled="btn.disabled">{{btn.text}}</Button>   
            </Col>
        </Row>
        <template v-if="'vertical' === type">
        <Row  v-for="(btn,index) in btnList"  type="flex" :justify="vjustify"  :key="'btn_' + index" style="margin-top: 5px;"> 
            <Ebutton  v-if="btntype === 'Ebutton'" :ref="btn.name" :config="btn" @click="click" :amplify="amplify" :fontplacement="fontplacement" :dynamic="myConfig.btnDynamic"> </Ebutton>
            <Button v-if="btntype === 'Button'" v-show="btn.visible"  :ref="btn.name" @click="action(btn.name)" :icon="btn.iconcls" :type="btn.type" :size="buttonSize">{{btn.text}}</Button>   
        </Row>
        </template>
         </div>
    </template>
    <template v-if="tooltype === 'row'">
        <div  v-if="visible">
        <Row v-if="showType"  type="flex" justify="center" :gutter="8">
            <Col v-for="(item,index) in btnList" :key="'btn_' + index" v-show="item.visible">
                <Button  v-if="myConfig.icon === true" size="small"  :type="getType(item)" :icon="item.icon" :custom-icon="item.customIcon"  @click="action(item.name)"></Button>
                <Button  v-else size="small"  :type="getType(item)" @click="action(item.name)" >{{item.text}}</Button>
            </Col>
        </Row>
        <Dropdown v-if="!showType"  @on-click="action">
            <a href="javascript:void(0)">
                操作
            <CommonIcon type="ios-arrow-down"></CommonIcon>
            </a>
            <template #list>
            <DropdownMenu>
                <DropdownItem v-for="(item,index) in btnList"  :key="'btndropdown_' + index" v-show="item.visible" :name="item.name">{{item.text}}</DropdownItem>
            </DropdownMenu>
            </template>
        </Dropdown>
        </div>
    </template>
    <template v-if="tooltype === 'batch'">
        <Row v-if="visible" type="flex" justify="end" :gutter="8">
        <Col v-if="showAddData">
            <Button icon="ios-add"  @click="action('addData')" >新建</Button>
        </Col>
        <Col>
        <Dropdown v-if="showBatchAction"  @on-click="action">
            <Button>
                批量操作
                <CommonIcon type="ios-arrow-down"></CommonIcon>
            </Button>
             <template #list>
            <DropdownMenu>
                <DropdownItem v-for="(item,index) in btnList"  :key="'dropbtn_' + index" v-show="item.visible" :name="item.name">{{item.text}}</DropdownItem>
            </DropdownMenu>
             </template>
        </Dropdown>
        </Col>
        </Row>
    </template>
</div>
</template>
<script>
import { oneOf } from '../../utils/assist';
import Ebutton from './ebutton.vue';
export default {
    name: 'Toolbar',
    data () {
        return {
            globalConfig:{
                moduleMethod:[],
            },
            btnList: [],
            myConfig:{
                spacing:16
            },
            modulecode:'' ,
            token:'',
            buttonSize:'default',
            btnShow:true,
            showType:true,
            visible:true,
            showAddData:false,
            showBatchAction:false,
            vjustify:'center',
            defaultStatus:{ // 按钮同斥规则 N:新增后, V:查看, E:编辑后, S:保存后, A:审核后, C:取消后, D:删除后(默认)
                'N' : ['saveData'],
                'V' : [ 'addData', 'editData', 'auditData', 'delData'],
                'E' : [ 'addData', 'saveData', 'delData'],
                'S' : [ 'addData', 'editData', 'auditData', 'delData','printData' ],
                'A' : [ 'addData', 'copyData', 'cancelData'],
                'C' : [ 'addData', 'printData'],
                'D' : [ 'addData']
            },  
            defaultRule: {
                // 按钮可用规则 Y:已审核, N:录入, C:已取消
                billstatus: {
                    Y: [ 'addData', 'cancelData', 'printData' ],
                    N: [ 'addData', 'editData', 'auditData', 'delData', 'printData' ],
                    C: [ 'addData',  'printData' ]
                }
            },
        };
    },
    props: {
        type: {
            validator (value) {
                return oneOf(value, ['horizontal', 'vertical']);
            },
            default: 'vertical'
        },
        config: {
            type: Object,
            default: () => {
                return {};      
            }
        },

        amplify: {
            type: Boolean,
            default:true
        },
        fontplacement: {
            validator (value) {
                return oneOf(value, ['bottom', 'right']);
            },
            default: 'right'
        },
        showback: {
            type: Boolean,
            default: false
        },
        tooltype: {
            type: String,
            default:'form'
        },
        btntype: {
            validator (value) {
                return oneOf(value, ['Button', 'Ebutton']);
            },
            default: 'Ebutton'
        },
        moduleMethod:{
            type:Array,
            default: () => {
                return [];      
            }
        },
        billmoduleid:{
            type: String,
            default:''
        },
        checkBtn:{
            type:Boolean,
            default:false
        },
        row:{
            type: Object,
            default: () => {
                return {};      
            }
        }

    },
    created () {
        this.init();
    },
    components: {
        Ebutton
    },
    methods: {
        init() {
            if (this.config) {
                this.myConfig = Object.assign({}, this.myConfig, this.config);
            }
            if (!this.myConfig.items) {
                this.myConfig.items = [];
            }
            if (this.myConfig.buttonSize) {
                this.buttonSize = this.myConfig.buttonSize;
            }
            if (this.moduleMethod.length > 0) {
                this.globalConfig.moduleMethod = this.$Method.copy(this.moduleMethod);
            }
            this.filterBtn();
            if (this.btnList.length > 0) {
                this.visible = true;
            } else {
                if (this.tooltype === 'batch') {
                    this.visible = this.showAddData;     
                } else {
                    this.visible = false;
                }
            }
            this.btnList.forEach(el => {
                if (el.visible === undefined) {
                    el.visible = true;
                }
            });
            
        },
        filterBtn() {
            if (this.checkBtn) {
                this.getModuleMethod();
            }
            this.filterBtnByToken();
        },
        getModuleMethod() {
            this.modulecode = this.$Method.getUrlParam('modulecode');
            if (!this.modulecode) {
                this.modulecode = this.$Method.getUrlParam('billmoduleid');
            }
            if (this.billmoduleid) {
                this.modulecode = this.billmoduleid;
            }
            this.token = this.$Method.getUrlParam('token');
            if (this.modulecode && this.token) {
                let btnList =  this.getUserModuleMethod(this.modulecode);
                if (btnList) {
                    this.globalConfig.moduleMethod = btnList.modulemethod;
                }
            } 
        },
        filterBtnByToken() {
            let items = this.commonFilterBtn();
            let formItems = [];
            let rowItems = [];
            let batchItems = [];
            items.forEach(el => {
                if (el.name === 'addData') {
                    this.showAddData = true;
                }
                if (el.iconcls === 'batch') {
                    batchItems.push(el);
                } else if (el.iconcls === 'row') {
                    rowItems.push(el);
                } else {
                    formItems.push(el);
                }
            });

            if (batchItems.length > 0) {
                this.showBatchAction = true;
            }

            if (this.tooltype === 'batch') {
                this.btnList = this.$Method.copy(batchItems);
            } else if (this.tooltype === 'row') {
                this.btnList = this.$Method.copy(rowItems);
            } else {
                if (this.fontplacement === 'right') {
                    this.vjustify = 'start';
                }
                this.btnList =  this.$Method.copy(formItems);
                if (this.isBillImport()) {
                    let importconfig  = {};
                    if (this.myConfig.importbtn && JSON.stringify(this.myConfig.importbtn) !== '{}') {
                        importconfig = Object.assign({},{iconcls:'_download',name:'downTemplate',text:'导入模版'},this.myConfig.backbtn) ;
                        importconfig.name = 'downTemplate';  
                    } else {
                        importconfig = {
                            iconcls:'_download',
                            name:'downTemplate',
                            text:'导入模版'
                        };
                    }
                    importconfig.visible = true;
                    this.btnList.push(importconfig);
                }

                if (this.showback) {
                    let back  = {};
                    if (this.myConfig.backbtn && JSON.stringify(this.myConfig.backbtn) !== '{}') {
                        back = Object.assign({},{iconcls:'_back',name:'back',text:'返回'},this.myConfig.backbtn) ;
                        back.name = 'back';  
                    } else {
                        back = {
                            iconcls:'_back',
                            name:'back',
                            text:'返回'
                        };
                    }
                    back.visible = true;
                    this.btnList.push(back);
                }
                this.initStatus();
            }
        },
        commonFilterBtn() {
            let tokenlength = this.globalConfig.moduleMethod.length;
            if (tokenlength <= 0) {
                return this.myConfig.items;
            }
            let items = [];
            this.globalConfig.moduleMethod.forEach(el => {
                let index = this.myConfig.items.findIndex(el2 => el2.name === el.name);
                if (index > -1) {
                    items.push(this.$Method.copy(this.myConfig.items[index]));
                }
            });
            let index2 = this.myConfig.items.findIndex(el => el.name === 'editRowForm');
            if (index2 > -1) {
                items.push(this.$Method.copy(this.myConfig.items[index2]));
            }
            return items;
        },
        initStatus() {
            if (this.myConfig.status) {
                Object.keys(this.defaultStatus).forEach(temp => {
                    if (this.myConfig.status[temp] === undefined) {
                        this.myConfig.status[temp] = [];
                    }
                    let array = this.myConfig.status[temp].concat(this.defaultStatus[temp]);
                    this.myConfig.status[temp] = this.uniqueArr(array);
                });
            } else {
                this.myConfig.status = this.$Method.copy(this.defaultStatus);
            }
            if (this.myConfig.rule) {
                Object.keys(this.defaultRule).forEach(temp2 => {
                    if (this.myConfig.rule[temp2]) {
                        Object.keys(this.defaultRule[temp2]).forEach(temp3 => {
                            if (this.defaultStatus[temp2]) {
                                if (this.myConfig.rule[temp2][temp3] === undefined) {
                                    this.myConfig.rule[temp2][temp3] = [];
                                }
                                if (this.defaultStatus[temp2][temp3]  === undefined) {
                                    this.defaultStatus[temp2][temp3] = [];
                                }
                            } else {
                                this.defaultStatus[temp2] ={};
                                this.defaultStatus[temp2][temp3] = [];
                                if (this.myConfig.rule[temp2][temp3] === undefined) {
                                    this.myConfig.rule[temp2][temp3] = [];
                                }
                            }
                            let rule = this.myConfig.rule[temp2][temp3].concat(this.defaultStatus[temp2][temp3]);
                            this.myConfig.rule[temp2][temp3] = this.uniqueArr(rule);
                        });
                    }
                });
            } else {
                this.myConfig.rule = this.$Method.copy(this.defaultRule);
            }
        },
        click(name) {
            let para = {};
            para.name = name;
            this.$emit('doAction', para);
        },
        changedStatusCommon(para) {
            this.btnList.forEach(el => {
                this.setReadOnly(el.name,true);
            });
            if (!para) {
                para = [];
            } 
            para = para.concat(['back','downTemplate','editRowForm']);
            para.forEach(name =>{
                this.setReadOnly(name,false);
            });
        },
        changedStatus(flag) {
            if (flag) {
                let para = this.myConfig.status[flag];
                this.changedStatusCommon(para);
            } 
        },
        isBillImport(){
            return  this.btnList.some(item => item.name === 'billImport');
        },

        gridChangedStatus(name, code) {
            if (this.myConfig && this.myConfig.rule && this.myConfig.rule[name]) {
                let para = this.myConfig.rule[name][code];
                this.changedStatusCommon(para);
            }
        },
        uniqueArr(array) {
            let r = [];
            const lenght = array.length ;
            for (let i = 0, l = lenght; i < l; i++) {
                for (let j = i + 1; j < l; j++)
                    if (array[i] === array[j]) j = ++i;
                r.push(array[i]);
            }
            return r;
        },
        action(name) {
            let para = {};
            para.name = name;
            this.$emit('doAction', para);
        },
        getType(item) {
            if (item.type) {
                return item.type;
            } else {
                return 'text';
            }
        },
        setVisible(name,value,tempBtntype) {
            let btntype = this.btntype;
            if (tempBtntype) {
                btntype = tempBtntype;
            }
            if (btntype === 'Ebutton') {
                if (this.$refs[name] && this.$refs[name][0]) {
                    this.$refs[name][0].setVisible(value);
                }
            } else {
                const index = this.btnList.findIndex(item => item.name === name);
                if (index > -1) {
                    let newConfig = this.$Method.copy(this.btnList[index]);
                    newConfig.visible = value;
                    this.btnList.splice(index,1,newConfig);
                }              
            }
        },
        setReadOnly(name, value,tempBtntype) {
            let btntype = this.btntype;
            if (tempBtntype) {
                btntype = tempBtntype;
            }
            if (btntype === 'Ebutton') {
                if (this.$refs[name] && this.$refs[name][0]) {
                    this.$refs[name][0].setEnabled(value);
                }
            } else {
                const index = this.btnList.findIndex(item => item.name === name);
                if (index > -1) {
                    let newConfig = this.$Method.copy(this.btnList[index]);
                    newConfig.disabled = value;
                    this.btnList.splice(index,1,newConfig);
                }              
            }
        }
        
    },
    mounted () {
        //this.changedStatus('V');
        let self = this;
        if (self.config.customInit) {
            self.config.customInit(self.row,self);
        }
    }
};
</script>