<template>
  <div class="view-container decustomview dareport-bbzscustom-view">
    <app-studioaction :viewTitle="$t(model.srfCaption)" viewName="dareportbbzscustomview"></app-studioaction>
    <card class="view-card view-no-toolbar" :disHover="true" :padding="0" :bordered="false" >
      <h6 style="text-align: center; padding: 5px">
        {{ headname }}
      </h6>
      <div class="content-container">
        <div class="selectAndData">
          <Treeselect ref="dim" v-model="treeValue" :options="treeOptions" :normalizer="normalizer" :placeholder='dimPlaceholder' ></Treeselect>
          <el-select ref="cxfs" v-model="type" @change="typechange" placeholder="请选择查询方式" >
              <template v-if='options && options.length>0'>
                    <template v-for='(item) in options'>
                         <el-option :key="item.value" :value="item.value" :label="item.label" ></el-option>
                    </template>
              </template>
          </el-select>
          <el-date-picker ref="time" v-model="dataValue" value-format="yyyy-MM-dd" :type='type' range-separator='至' start-placeholder='起始' end-placeholder='结束'></el-date-picker>

          <div class="toolbar"  style="margin-left: auto" >
           <el-button @click="exportReport">导出</el-button>
            <el-button @click="getReportData">搜索</el-button>
          </div>

        </div>
        <div class="grid">
          <ag-grid-vue
            style="width: 100%; height: 95%"
            class="ag-theme-balham"
            :columnDefs="columnDefs"
            :enableFilter="false"
            :enableColResize="true"
            :singleClickEdit="true"
            :pagination="false"
            :localeText="localeText"
             headerHeight=30
            @onGridReady="onGridReady"
            @onselectionChanged="selectionChanged"
            @onrowDoubleClicked="rowDoubleClicked"
            @onCellDoubleClicked="onCellClick"
            :rowData="items"
          ></ag-grid-vue>
        </div>
      </div>
    </card>
  </div>
</template>

<script lang='tsx'>
import { Component, Prop, Watch, Model } from 'vue-property-decorator';
import DAReportBBZSCustomViewBase from './dareport-bbzscustom-view-base.vue';
import 'ag-grid-enterprise';
import Treeselect from '@riophae/vue-treeselect';
import { AgGridVue } from "ag-grid-vue";
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

@Component({
    components: {
        'ag-grid-vue':AgGridVue,
        'Treeselect':Treeselect
    },
    beforeRouteEnter: (to: any, from: any, next: any) => {
        next((vm: any) => {
            if(!Object.is(vm.navModel,"route")){
                vm.initNavDataWithTab(vm.viewCacheData);
            }
            vm.$store.commit('addCurPageViewtag', { fullPath: to.fullPath, viewtag: vm.viewtag });
        });
    },
})
export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase {

     /**
     * 执行mounted后的逻辑
     * 
     * @memberof DAReportBBZSCustomViewBase
     */
    public afterMounted(){
        const _this: any = this;
        _this.engineInit();
        if (_this.loadModel && _this.loadModel instanceof Function) {
            _this.loadModel();
        }
        _this.getReport(false);
    }

    public normalizer(node){
          //去掉children=null的属性
          if(node.children==null||node.children=='null'){
            delete node.children;
          }
    }

    /**
     * 表头
     */
    public columnDefs: any[] = [];
    public headname: any = '';
    public dimPlaceholder: any='请选择';




    /**
     * 选项值
     */
    public options: any = [
        {
            value: 'year',
            label: '按年查询',
        },
        {
            value: 'monthrange',
            label: '按月查询',
        },
        {
            value: 'daterange',
            label: '按日查询',
        }
    ];

    /**
     * data绑定值
     */
    public dataValue: any =[];



    /**
     * 选择类型
     */
    public type: any='daterange';


    /**
     * 树项
     */
    public treeOptions: any = [];

    /**
     * 树值
     * @param $event 
     */
    public treeValue: any = "";

    public typechange(node:any)
    {
       if(node=='year')
          this.dataValue="";


    }


    public startTime : any;
    public endTime : any;

    public getTimeRange()
    {
         const time: any = this.$refs.time;
         let timeAll = time.displayValue;
         if (this.type === "year") {
                     this.startTime = timeAll + '-01-01';
                     this.endTime = timeAll + '-12-31';
                 }
                 if (this.type === "monthrange") {
                     this.startTime = timeAll[0] + '-01';
                     this.endTime = timeAll[1] + '-31';
                 }
                 if (this.type === "daterange") {
                     this.startTime = timeAll[0];
                     this.endTime = timeAll[1];
                 }
    }

    /**
     * 请求数据
     */
    public getReportData()
    {
        this.getReport(true);
    }

    public getReport(loadData?: boolean) {
        const _this:any = this;

        this.getTimeRange();

        // 请求地址
        //debugger
        let url='/lite/report/'+JSON.parse(this.viewdata).srfparentkey;


        if(!loadData)
            url=url+"/config";
        else  if(this.treeValue&&this.treeValue!='%')
            url=url+"/"+this.treeValue;
        if(this.startTime&&this.endTime)
           url=url+"?startTime="+this.startTime+"&endTime="+this.endTime;

        const params: any = {};
        const post: Promise<any> = this.$http.get(url,params,true);
        post.then((response: any) => {
            if (response && response.status == 200) {

                this.headname = response.data.title;
                if((!loadData)||this.columnDefs.length==0)
                    this.columnDefs=response.data.headers;
                if(loadData)
                    this.items = response.data.rows;

                if((!loadData)||this.treeOptions.length==0)
                    this.treeOptions=response.data.dict.items;
                this.treeValue=response.data.selectValue;
                this.dimPlaceholder="请选择"+response.data.group;
                if(!this.startTime)
                {
                    this.type="daterange"
                    this.dataValue=[response.data.startTime,response.data.endTime]
                }

            }
        }).catch((response: any) => {
            if (!response || !response.status || !response.data) {
                this.$Notice.error({ title: '错误', desc: '系统异常' });
                return;
            }
            const { data: _data } = response;
            this.$Notice.error({ title: _data.title, desc: _data.message });
        });
        
    }

     /**
         * 请求数据
         */
     public exportReport() {
            const _this:any = this;


            // 时间
            this.getTimeRange()

            // 请求地址
            //debugger
            let url='/lite/report/'+JSON.parse(this.viewdata).srfparentkey;
            if(this.treeValue&&this.treeValue!='%')
               url=url+"/"+this.treeValue;
            if(this.startTime&&this.endTime)
                url=url+".xls?startTime="+this.startTime+"&endTime="+this.endTime;
            window.open(url);
     }

    /**
     * 表格对象
     *
     * @memberof Main
     */
    public gridApi: any;

    /**
    * 列对象
    *
    *
    * @memberof Main
    */
    public columnApi: any;

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

    /**
     * 表格数据
     */
    public localeText: any = {
        page: "页",
        more: "更多",
        to: "到",
        of: "of",
        next: "下一页",
        last: "上一页",
        first: "首页",
        previous: "上一页",
        loadingOoo: "加载中...",
        selectAll: "查询全部",
        searchOoo: "查询...",
        blanks: "空白",
        filterOoo: "过滤...",
        applyFilter: "daApplyFilter...",
        equals: "相等",
        notEqual: "不相等",
        lessThan: "小于",
        greaterThan: "大于",
        lessThanOrEqual: "小于等于",
        greaterThanOrEqual: "大于等于",
        inRange: "范围",
        contains: "包含",
        notContains: "不包含",
        startsWith: "开始于",
        endsWith: "结束于",
        group: "组",
        columns: "列",
        filters: "筛选",
        rowGroupColumns: "laPivot Cols",
        rowGroupColumnsEmptyMessage: "la drag cols to group",
        valueColumns: "laValue Cols",
        pivotMode: "laPivot-Mode",
        groups: "laGroups",
        values: "值",
        pivots: "laPivots",
        valueColumnsEmptyMessage: "la drag cols to aggregate",
        pivotColumnsEmptyMessage: "la drag here to pivot",
        toolPanelButton: "la tool panel",
        noRowsToShow: "选定统计条件，点击【搜索】按钮加载数据",
        pinColumn: "laPin Column",
        valueAggregation: "laValue Agg",
        autosizeThiscolumn: "laAutosize Diz",
        autosizeAllColumns: "laAutsoie em All",
        groupBy: "排序",
        ungroupBy: "不排序",
        resetColumns: "重置列",
        expandAll: "展开全部",
        collapseAll: "关闭",
        toolPanel: "工具面板",
        export: "导出",
        csvExport: "导出为CSV格式文件",
        excelExport: "导出到Excel",
        pinLeft: "laPin &lt;&lt;",
        pinRight: "laPin &gt;&gt;",
        noPin: "laDontPin &lt;&gt;",
        sum: "总数",
        min: "最小值",
        max: "最大值",
        none: "无",
        count: "总",
        average: "平均值",
        copy: "复制",
        copyWithHeaders: "携带表头复制",
        ctrlC: "ctrl + C",
        paste: "粘贴",
        ctrlV: "ctrl + V"
    };

    /**
     * 表格加载完成
     *
     * @returns void
     * @memberof Main
     */
    public onGridReady($event: any): void {
        console.log($event);
        this.gridApi = $event.api;
        this.columnApi = $event.columnApi;
        this.gridApi.sizeColumnsToFit();
    }

    /**
     * 行选中变化
     *
     * @returns void
     * @memberof Main
     */
    public selectionChanged($event: any): void {
        console.log(this.getSelections());
    }

    /**
     * 获取选中数据
     *
     * @returns {any[]}
     * @memberof Main
     */
    public getSelections(): any[] {
        return this.gridApi.getSelectedRows();
    }

    /**
     * 行双击
     *
     * @returns void
     * @memberof Main
     */
    public rowDoubleClicked($event: any): void {
        console.log($event.data);
    }

     public onCellClick($event:any): void{
            console.log($event.data);
            const _this = this;
     }

}
</script>