<template>
<div class='grid' style="height:100%;">
        <el-table v-if="isDisplay === true"
        :default-sort="{ prop: minorSortPSDEF, order: Object.is(minorSortDir, 'ASC') ? 'ascending' : Object.is(minorSortDir, 'DESC') ? 'descending' : '' }"  
        @sort-change="onSortChange($event)"  
        :border="isDragendCol"
        stripe :height="isEnablePagingBar && items.length > 0 ? 'calc(100% - 50px)' : '100%'"  
        @row-click="rowClick($event)"  
        @select-all="selectAll($event)"  
        @select="select($event)"  
        @row-class-name="onRowClassName($event)"  
        @row-dblclick="rowDBLClick($event)"  
        ref='multipleTable' :data="items" :show-header="!isHideHeader">
            <template v-if="!isSingleSelect">
                <el-table-column type='selection' :width="checkboxColWidth"></el-table-column>
            </template>
            <template v-if="getColumnState('porgname')">
                <el-table-column show-overflow-tooltip :prop="'porgname'" :label="$t('org.main_grid.columns.porgname')" :width="100" :align="'left'" :sortable="'custom'">
                    <template v-slot="{row,column}">
                        <span>{{row.porgname}}</span>
                    </template>
                </el-table-column>
            </template>
            <template v-if="getColumnState('orgname')">
                <el-table-column show-overflow-tooltip :prop="'orgname'" :label="$t('org.main_grid.columns.orgname')" :width="150" :align="'left'" :sortable="'custom'">
                    <template v-slot="{row,column}">
                        <span>{{row.orgname}}</span>
                    </template>
                </el-table-column>
            </template>
            <template v-if="getColumnState('updateman')">
                <el-table-column show-overflow-tooltip :prop="'updateman'" :label="$t('org.main_grid.columns.updateman')" :width="150" :align="'left'" :sortable="'custom'">
                    <template v-slot="{row,column}">
                        <span>{{row.updateman}}</span>
                    </template>
                </el-table-column>
            </template>
            <template v-if="getColumnState('updatedate')">
                <el-table-column show-overflow-tooltip :prop="'updatedate'" :label="$t('org.main_grid.columns.updatedate')" :width="150" :align="'left'" :sortable="'custom'">
                    <template v-slot="{row,column}">
                        <span>{{row.updatedate}}</span>
                    </template>
                </el-table-column>
            </template>
            <template v-if="adaptiveState">
                <el-table-column></el-table-column>
            </template>
    </el-table>
    <row class='grid-pagination' v-show="items.length > 0">
        <page class='pull-right' @on-change="pageOnChange($event)" 
            @on-page-size-change="onPageSizeChange($event)"
            :transfer="true" :total="totalrow"
            show-sizer :current="curPage" :page-size="limit"
            :page-size-opts="[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]" show-elevator show-total>
            <span>
                <span class="page-column">
                    <poptip transfer placement="top-start">
                        <i-button icon="md-menu">{{$t('app.gridpage.choicecolumns')}}</i-button>
                        <div slot="content">
                            <template v-for="col in allColumns">
                                <div :key="col.name"><el-checkbox v-model="col.show" @change="onColChange()">{{$t(col.langtag)}}</el-checkbox></div>
                            </template>
                        </div>
                    </poptip>
                </span>
                <span class="page-button"><i-button icon="md-refresh" :title="$t('app.gridpage.refresh')" @click="pageRefresh()"></i-button></span>&nbsp;
                <span>
                    {{$t('app.gridpage.show')}}&nbsp;
                    <span>
                        <template v-if="items.length === 1">
                        1
                        </template>
                        <template v-else>
                            <span>{{(curPage - 1) * limit + 1}}&nbsp;-&nbsp;{{totalrow > curPage * limit ? curPage * limit : totalrow}}</span>
                        </template>
                    </span>&nbsp;
                    {{$t('app.gridpage.records')}}，{{$t('app.gridpage.totle')}}&nbsp;{{totalrow}}&nbsp;{{$t('app.gridpage.records')}}
                </span>
            </span>
        </page>
    </row>
</div>
</template>
<script lang='ts'>
import { Vue, Component, Prop, Provide, Emit, Watch, Model } from 'vue-property-decorator';
import { CreateElement } from 'vue';
import { Subject, Subscription } from 'rxjs';
import { ControlInterface } from '@/interface/control';
import { UICounter,UIActionTool } from '@/utils';
import ORGService from '@/service/org/org-service';
import MainService from './main-grid-service';



@Component({
    components: {
    }
})
export default class MainBase extends Vue implements ControlInterface {

    /**
     * 名称
     *
     * @type {string}
     * @memberof Main
     */
    @Prop() protected name?: string;

    /**
     * 视图通讯对象
     *
     * @type {Subject<ViewState>}
     * @memberof Main
     */
    @Prop() protected viewState!: Subject<ViewState>;

    /**
     * 应用上下文
     *
     * @type {*}
     * @memberof Main
     */
    @Prop() protected context: any;

    /**
     * 视图参数
     *
     * @type {*}
     * @memberof Main
     */
    @Prop() protected viewparams: any;

    /**
     * 视图状态事件
     *
     * @protected
     * @type {(Subscription | undefined)}
     * @memberof Main
     */
    protected viewStateEvent: Subscription | undefined;

    /**
     * 获取部件类型
     *
     * @returns {string}
     * @memberof Main
     */
    protected getControlType(): string {
        return 'GRID'
    }

    /**
     * 建构部件服务对象
     *
     * @type {MainService}
     * @memberof Main
     */
    protected service: MainService = new MainService({ $store: this.$store });

    /**
     * 实体服务对象
     *
     * @type {ORGService}
     * @memberof Main
     */
    protected appEntityService: ORGService = new ORGService({ $store: this.$store });
    


    /**
     * 关闭视图
     *
     * @param {any[]} args
     * @memberof Main
     */
    protected closeView(args: any[]): void {
        let _this: any = this;
        _this.$emit('closeview', args);
    }


    /**
     * 获取多项数据
     *
     * @returns {any[]}
     * @memberof Main
     */
    public getDatas(): any[] {
        return this.selections;
    }

    /**
     * 获取单项树
     *
     * @returns {*}
     * @memberof Main
     */
    public getData(): any {
        return this.selections[0];
    }

    /**
     * 显示处理提示
     *
     * @type {boolean}
     * @memberof Main
     */
    @Prop({ default: true }) protected showBusyIndicator?: boolean;

    /**
     * 部件行为--update
     *
     * @type {string}
     * @memberof Main
     */
    @Prop() protected updateAction!: string;
    
    /**
     * 部件行为--fetch
     *
     * @type {string}
     * @memberof Main
     */
    @Prop() protected fetchAction!: string;
    
    /**
     * 部件行为--remove
     *
     * @type {string}
     * @memberof Main
     */
    @Prop() protected removeAction!: string;
    
    /**
     * 部件行为--load
     *
     * @type {string}
     * @memberof Main
     */
    @Prop() protected loadAction!: string;
    
    /**
     * 部件行为--loaddraft
     *
     * @type {string}
     * @memberof Main
     */
    @Prop() protected loaddraftAction!: string;
    
    /**
     * 部件行为--create
     *
     * @type {string}
     * @memberof Main
     */
    @Prop() protected createAction!: string;

    /**
     * 当前页
     *
     * @type {number}
     * @memberof Main
     */
    protected curPage: number = 1;

    /**
     * 数据
     *
     * @type {any[]}
     * @memberof Main
     */
    protected items: any[] = [];

    /**
     * 是否支持分页
     *
     * @type {boolean}
     * @memberof Main
     */
    protected isEnablePagingBar: boolean = true;

    /**
     * 是否禁用排序
     *
     * @type {boolean}
     * @memberof Main
     */
    protected isNoSort: boolean = false;

    /**
     * 排序方向
     *
     * @type {string}
     * @memberof Main
     */
    protected minorSortDir: string = '';

    /**
     * 排序字段
     *
     * @type {string}
     * @memberof Main
     */
    protected minorSortPSDEF: string = '';

    /**
     * 分页条数
     *
     * @type {number}
     * @memberof Main
     */
    protected limit: number = 20;

    /**
     * 是否显示标题
     *
     * @type {boolean}
     * @memberof Main
     */
    protected isHideHeader: boolean = false;

    /**
     * 是否单选
     *
     * @type {boolean}
     * @memberof Main
     */
    @Prop() protected isSingleSelect?: boolean;

    /**
     * 是否开启行编辑
     *
     * @type {boolean}
     * @memberof Main
     */
    @Prop({default: false}) protected isOpenEdit!: boolean;

    /**
     * 总条数
     *
     * @type {number}
     * @memberof Main
     */
    protected totalrow: number = 0;

    /**
     * 选中行数据
     *
     * @type {any[]}
     * @memberof Main
     */
    protected selections: any[] = [];

    /**
     * 拦截行选中
     *
     * @type {boolean}
     * @memberof Main
     */
    protected stopRowClick: boolean = false;


    /**
     * 表格是否显示
     *
     * @type {boolean}
     * @memberof Main
     */
    protected isDisplay:boolean = true;

    /**
     * 部件刷新
     *
     * @param {any[]} args
     * @memberof Main
     */
    protected refresh(args: any[]): void {
        this.load();
    }

	/**
	 * 选项框列宽
	 *
	 * @type {number}
	 * @memberof AppIndex
	 */
	protected checkboxColWidth: number = 80;

    /**
     * 是否允许拖动列宽
     *
     * @type {boolean}
     * @memberof AppEmbedPicker
     */
    protected isDragendCol: boolean = false;

    /**
     * 所有列成员
     *
     * @type {any[]}
     * @memberof Main
     */
    protected allColumns: any[] = [
        {
            name: 'porgname',
            label: '父机构名称',
            langtag: 'org.main_grid.columns.porgname',
            show: true,
            util: 'PX'
        },
        {
            name: 'orgname',
            label: '机构名称',
            langtag: 'org.main_grid.columns.orgname',
            show: true,
            util: 'PX'
        },
        {
            name: 'updateman',
            label: '更新人',
            langtag: 'org.main_grid.columns.updateman',
            show: true,
            util: 'PX'
        },
        {
            name: 'updatedate',
            label: '更新时间',
            langtag: 'org.main_grid.columns.updatedate',
            show: true,
            util: 'PX'
        },
    ]

    /**
     * 属性值规则
     *
     * @type {*}
     * @memberof Main
     */
    protected rules: any = {
        srfkey: [
             { required: false, validator: (rule:any, value:any, callback:any) => { return (rule.required && (value === null || value === undefined || value === "")) ? false : true;}, message: '机构标识 值不能为空', trigger: 'change' },
            { required: false, validator: (rule:any, value:any, callback:any) => { return (rule.required && (value === null || value === undefined || value === "")) ? false : true;}, message: '机构标识 值不能为空', trigger: 'blur' },
        ],
    }

    /**
     * 表格数据加载
     *
     * @param {*} [arg={}]
     * @memberof Main
     */
    protected load(opt: any = {}): void {
        if(!this.fetchAction){
            this.$Notice.error({ title: '错误', desc: 'ORGGridView视图表格fetchAction参数未配置' });
            return;
        }
        const arg: any = {...opt};

        const page: any = {};
        if (this.isEnablePagingBar) {
            Object.assign(page, { page: this.curPage-1, size: this.limit });
        }
        // 设置排序
        if (!this.isNoSort && !Object.is(this.minorSortDir, '') && !Object.is(this.minorSortPSDEF, '')) {
            const sort: string = this.minorSortPSDEF+","+this.minorSortDir;
            Object.assign(page, { sort: sort });
        }
        Object.assign(arg, page);

        const parentdata: any = {};
        this.$emit('beforeload', parentdata);
        Object.assign(arg, parentdata);
        if(this.context.srfparentdename && !this.context[this.context.srfparentdename.toLowerCase()]){
            return;
        }
        const post: Promise<any> = this.service.search(this.fetchAction,this.context, arg, this.showBusyIndicator);
        post.then((response: any) => {
            if (!response.status || response.status !== 200) {
                if (response.errorMessage) {
                    this.$Notice.error({ title: '错误', desc: response.errorMessage });
                }
                return;
            }
            const data: any = response.data;
            if (Object.keys(data).length > 0) {
                this.items = JSON.parse(JSON.stringify(data.records));
                this.totalrow = data.total;
            }
            // 清空selections
            this.selections = [];
            this.$emit('load', this.items);
        }).catch((response: any) => {
            if (response && response.status === 401) {
                return;
            }
            this.$Notice.error({ title: '错误', desc: response.errorMessage });
        });
    }

    /**
     * 删除
     *
     * @param {any[]} datas
     * @returns {Promise<any>}
     * @memberof Main
     */
    protected async remove(datas: any[]): Promise<any> {
        if(!this.removeAction){
            this.$Notice.error({ title: '错误', desc: 'ORGGridView视图表格removeAction参数未配置' });
            return;
        }
        let _datas:any[] = [];
        datas.forEach((record: any, index: number) => {
            if (!record.srfkey) {
                this.items.some((val: any, num: number) =>{
                    if(JSON.stringify(val) == JSON.stringify(record)){
                        this.items.splice(num,1);
                        return true;
                    }
                }); 
            }else{
               _datas.push(datas[index]);
            }
        });
        if (_datas.length === 0) {
            return;
        }
        let dataInfo = '';
        _datas.forEach((record: any, index: number) => {
            let srfmajortext = record.srfmajortext;
            if (index < 5) {
                if (!Object.is(dataInfo, '')) {
                    dataInfo += '、';
                }
                dataInfo += srfmajortext;
            } else {
                return false;
            }
        });

        if (_datas.length < 5) {
            dataInfo = dataInfo + ' 共' + _datas.length + '条数据';
        } else {
            dataInfo = dataInfo + '...' + ' 共' + _datas.length + '条数据';
        }

        const removeData = () => {
            let keys: any[] = [];
            _datas.forEach((data: any) => {
                keys.push(data.srfkey);
            });
            const context:any = JSON.parse(JSON.stringify(this.context));
            const post: Promise<any> = this.service.delete(this.removeAction,Object.assign(context,{ org: keys.join(';') }),{ orgid: keys.join(';') }, this.showBusyIndicator);
            return new Promise((resolve: any, reject: any) => {
                post.then((response: any) => {
                    if (!response || response.status !== 200) {
                        this.$Notice.error({ title: '', desc: '删除数据失败,' + response.info });
                        return;
                    } else {
                        this.$Notice.success({ title: '', desc: '删除成功!' });
                    }
                    this.load({});
                    this.$emit('remove', null);
                    this.selections = [];
                    resolve(response);
                }).catch((response: any) => {
                    if (response && response.status === 401) {
                        return;
                    }
                    if (!response || !response.status || !response.data) {
                        this.$Notice.error({ title: '错误', desc: '系统异常' });
                        reject(response);
                        return;
                    }

                    const { data: _data } = response;
                    this.$Notice.error({ title: _data.title, desc: _data.message });
                    reject(response);
                });
            });
        }

        dataInfo = dataInfo.replace(/[null]/g, '').replace(/[undefined]/g, '');
        this.$Modal.confirm({
            title: '警告',
            content: '确认要删除 ' + dataInfo + '，删除操作将不可恢复？',
            onOk: () => {
                removeData();
            },
            onCancel: () => { }
        });
        return removeData;
    }


    /**
     * 批量添加
     *
     * @param {*} [arg={}]
     * @memberof Main
     */
    protected addBatch(arg: any = {}): void {
        if(!this.fetchAction){
            this.$Notice.error({ title: '错误', desc: 'ORGGridView视图表格fetchAction参数未配置' });
            return;
        }
        if(!arg){
            arg = {};
        }
        console.error("批量添加未实现");
    }

    /**
     * 数据导出
     *
     * @param {*} data
     * @memberof Main
     */
    protected exportExcel(data: any = {}): void {
        const arg: any = {};

        const page: any = {};
        if (!this.isNoSort && !Object.is(this.minorSortDir, '') && !Object.is(this.minorSortPSDEF, '')) {
            const sort: string[] = [this.minorSortPSDEF];
            if (Object.is(this.minorSortDir, 'ASC')) {
                Object.assign(page, { asc: sort });
            } else {
                Object.assign(page, { desc: sort });
            }
        }

        if (Object.is(data.type, 'maxRowCount')) {
            Object.assign(page, { page: 0, size: data.maxRowCount });
        } else if (Object.is(data.type, 'activatedPage')) {
            Object.assign(page, { page: this.curPage-1, size: this.limit });
        }
        Object.assign(arg, { page: page });

        const parentdata: any = {};
        this.$emit('beforeload', parentdata);
        Object.assign(arg, parentdata);
        console.error("数据导出未实现");
    }

    /**
     * 生命周期
     *
     * @memberof Main
     */
    protected created(): void {
        this.afterCreated();
    }

    /**
     * 执行created后的逻辑
     *
     *  @memberof Main
     */    
    protected afterCreated(){
        this.setColState();
        if (this.viewState) {
            this.viewStateEvent = this.viewState.subscribe(({ tag, action, data }) => {
                if (!Object.is(tag, this.name)) {
                    return;
                }
                if (Object.is('load', action)) {
                    this.load(data);
                }
                if (Object.is('remove', action)) {
                    this.remove(data);
                }
                if (Object.is('save', action)) {
                    this.save(data);
                }
            });
        }
    }

    /**
     * vue 生命周期
     *
     * @memberof Main
     */
    protected destroyed() {
        this.afterDestroy();
    }

    /**
     * 执行destroyed后的逻辑
     *
     * @memberof Main
     */
    protected afterDestroy() {
        if (this.viewStateEvent) {
            this.viewStateEvent.unsubscribe();
        }
    }

    /**
     * 获取选中行胡数据
     *
     * @returns {any[]}
     * @memberof Main
     */
    protected getSelection(): any[] {
        return this.selections;
    }

    /**
     * 行双击事件
     *
     * @param {*} $event
     * @returns {void}
     * @memberof Main
     */
    protected rowDBLClick($event: any): void {
        if (!$event || this.isOpenEdit) {
            return;
        }
        this.selections = [];
        this.selections.push(JSON.parse(JSON.stringify($event)));

        const refs: any = this.$refs;
        if (refs.multipleTable) {
            refs.multipleTable.clearSelection();
            refs.multipleTable.toggleRowSelection($event);
        }

        this.$emit('rowdblclick', this.selections);
        this.$emit('selectionchange', this.selections);
    }

    /**
     * 复选框数据选中
     *
     * @param {*} $event
     * @returns {void}
     * @memberof  Main
     */
    protected select($event: any): void {
        if (!$event) {
            return;
        }
        this.selections = [];
        this.selections = [...JSON.parse(JSON.stringify($event))];
        this.$emit('selectionchange', this.selections);
    }

    /**
     * 复选框数据全部选中
     *
     * @param {*} $event
     * @memberof  Main
     */
    protected selectAll($event: any): void {
        if (!$event) {
            return;
        }
        this.selections = [];
        this.selections = [...JSON.parse(JSON.stringify($event))];
        this.$emit('selectionchange', this.selections);
    }

    
    /**
     * 行单击选中
     *
     * @param {*} $event
     * @returns {void}
     * @memberof Main
     */
    protected rowClick($event: any, ifAlways: boolean = false): void {
        if (!ifAlways && (!$event || this.isOpenEdit)) {
            return;
        }
        if(this.stopRowClick) {
            this.stopRowClick = false;
            return;
        }
        if(this.isSingleSelect){
            this.selections = [];
        }
        this.selections.push(JSON.parse(JSON.stringify($event)));

        const refs: any = this.$refs;
        if (refs.multipleTable) {
            if(this.isSingleSelect){
                refs.multipleTable.clearSelection();
            }
            refs.multipleTable.toggleRowSelection($event);
        }

        this.$emit('selectionchange', this.selections);
    }


    /**
     * 页面变化
     *
     * @param {*} $event
     * @returns {void}
     * @memberof Main
     */
    protected pageOnChange($event: any): void {
        if (!$event) {
            return;
        }
        if ($event === this.curPage) {
            return;
        }
        this.curPage = $event;
        this.load({});
    }

    /**
     * 分页条数变化
     *
     * @param {*} $event
     * @returns {void}
     * @memberof Main
     */
    protected onPageSizeChange($event: any): void {
        if (!$event) {
            return;
        }
        if ($event === this.limit) {
            return;
        }
        this.limit = $event;
        if (this.curPage === 1) {
            this.load({});
        }
    }

    /**
     * 分页刷新
     *
     * @memberof Main
     */
    protected pageRefresh(): void {
        this.load({});
    }

    /**
     * 排序变化
     *
     * @param {{ column: any, prop: any, order: any }} { column, prop, order }
     * @memberof Main
     */
    protected onSortChange({ column, prop, order }: { column: any, prop: any, order: any }): void {
        const dir = Object.is(order, 'ascending') ? 'asc' : Object.is(order, 'descending') ? 'desc' : '';
        if (Object.is(dir, this.minorSortDir) && Object.is(this.minorSortPSDEF, prop)) {
            return;
        }
        this.minorSortDir = dir;
        this.minorSortPSDEF = prop ? prop : '';
        this.load({});
    }

    /**
     * 表格行选中样式
     *
     * @param {{ row: any, rowIndex: any }} { row, rowIndex }
     * @returns {string}
     * @memberof Main
     */
    protected onRowClassName({ row, rowIndex }: { row: any, rowIndex: any }): string {
        const index = this.selections.findIndex((select: any) => Object.is(select.srfkey, row.srfkey));
        return index !== -1 ? 'grid-row-select' : '';
    }



    /**
     * 界面行为
     *
     * @param {*} row
     * @param {*} tag
     * @param {*} $event
     * @memberof Main
     */
	protected uiAction(row: any, tag: any, $event: any) {
        this.rowClick(row, true);
    }

    /**
     * 设置列状态
     *
     * @memberof Main
     */
    protected setColState() {
		const _data: any = localStorage.getItem('org_main_grid');
		if (_data) {
			let columns = JSON.parse(_data);
			columns.forEach((col: any) => {
				let column = this.allColumns.find((item) => Object.is(col.name, item.name));
				if (column) {
					Object.assign(column, col);
				}
			});
		}
    }

    /**
     * 列变化
     *
     * @memberof Main
     */
    protected onColChange() {
        localStorage.setItem('org_main_grid', JSON.stringify(this.allColumns));
    }

    /**
     * 获取列状态
     *
     * @param {string} name
     * @returns {boolean}
     * @memberof Main
     */
    protected getColumnState(name: string): boolean {
        let column = this.allColumns.find((col: any) =>
            Object.is(name, col.name)
        );
        return column.show ? true : false;
    }

    /**
     * 表格列是否自适应布局
     *
     * @readonly
     * @type {boolean}
     * @memberof Main
     */
    get adaptiveState(): boolean {
        return !this.allColumns.find((column: any) => column.show && Object.is(column.util, 'STAR'));
    }

    /**
     * 保存
     *
     * @param {*} $event
     * @returns {void}
     * @memberof Main
     */
    protected save(args: any[], params?: any, $event?: any, xData?: any): void {
        let _this = this;
        let promises:any = [];
        _this.items.forEach((item:any)=>{
            if(Object.is(item.srfuf, '0')){
                if(!this.createAction){
                    this.$Notice.error({ title: '错误', desc: 'ORGGridView视图表格createAction参数未配置' });
                    return;
                }
                Object.assign(item,this.viewparams);
                promises.push(this.service.add(this.createAction, this.context,item, this.showBusyIndicator));
            }else{
                if(!this.updateAction){
                    this.$Notice.error({ title: '错误', desc: 'ORGGridView视图表格updateAction参数未配置' });
                    return;
                }
                Object.assign(item,this.viewparams);
                if(item.org){
                    Object.assign(this.context,{org:item.org})
                }
                promises.push(this.service.add(this.updateAction,this.context,item, this.showBusyIndicator));
            }
        });
        Promise.all(promises).then((response: any) => {
            this.$emit('save', response);
        }).catch((response: any) => {
            this.$Notice.error({ title: '错误', desc: '系统异常' });
        });
    }


}
</script>

<style lang='less'>
@import './main-grid.less';
</style>