<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"
            @cellDoubleClicked="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;


        let domain=this.getDomain();

        if(!loadData)
        {
            if(domain)
                url=url+"/"+domain+"/config";
            else
                url=url+"/config";
        }
        else  if(!this.treeValue)
        {
            alert('请选择统计范围');
            return;
        }
        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)
                {
                    let dictItems: any=this.getDict(response.data.dict.items,domain);
                    if(dictItems)
                        this.treeOptions=dictItems;
                    else
                        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 getDict(items: any,curOrg: string ) :any
    {
        if(curOrg)
        {
            let nodes: any = null;
            items.forEach((item: any) => {
                if(item.value===curOrg)
                {
                    nodes = [item];
                    return nodes;
                }
                if(item.children)
                {
                    let tmp=this.getDict(item.children,curOrg);
                    if(tmp)
                    {
                        nodes = tmp;
                        return nodes;
                    }
                }
            });
            return nodes;

        }
        else
           return items;
    }

    public getDomain(): string
    {
            let curOrg:string = this.$store.getters.getAppData().context.srforgcode;
            if(curOrg)
            {
                if(curOrg.startsWith("10"))
                    return null;
                else if(curOrg.endsWith("0000"))
                    return curOrg.substring(0,2);
                else if(curOrg.endsWith("00"))
                    return curOrg.substring(0,4);
                else
                    return curOrg;
            }
            return null;
    }

     /**
         * 请求数据
         */
     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{
            if ($event && $event.colDef){
                let field = $event.colDef.field;
                if (!field){
                    // 计算表达式列，没有相应指标承载，不支持反查
                    console.log('无指标列，不支持反查!');
                    return;
                }
            }
            let colId=$event.column.colId;
            let rowId=$event.data["itemId"];
            let total=$event.data[$event.column.colId];
            this.getTimeRange();
             const params: any = {};
            if(colId==='no')
                return;
            else if(colId==='itemName')
            {
                this.treeValue=rowId;
                this.getReportData();
                return;
            }
            let url='/lite/lookup/'+colId+'/'+rowId+'?page=0&size=1000&total='+total;
            if(this.startTime&&this.endTime)
                url=url+"&startTime="+this.startTime+"&endTime="+this.endTime;
            const post: Promise<any> = this.$http.get(url,params,true);
                 post.then((response: any) => {
                        if (response && response.status == 200) {

                            console.log("keys:"+response.data.keys);
                            console.log("field:"+response.data.field);
                            console.log("totalPages:"+response.data.totalPages);
                            console.log("total:"+response.data.total);
                            console.log("page:"+response.data.page);
                            console.log("size:"+response.data.size);
                            console.log("metricId:"+response.data.metricId);
                            console.log("dimValue:"+response.data.dimValue);

                           }
                        }).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 });
            });

            const _this = this;
     }

}
</script>