"use strict";
import {util} from "../../util/util.js";
import {httpUtil} from "../../util/httpUtil.js";
import {fullMap} from "../../fullMap.js";
import {khcToastr} from "../alert/khcToastr.js";
import {config} from "../../config.js";

class charts{
    constructor(data) {
        this.eleID = util.getUUID();
        this.objID = util.getUUID() + 'div';
        this.parentObjID = data.parentObjID;
        this.code=data.chartsCode.code;
        this.chartsCode = data.chartsCode;
        this.chartsHeight = this.code.chartsHeight;
        this.option={};
    }
    init(){
        let that=this;
        return new Promise((resolve, reject) => {
            this.componentMap = new Map();//存储组件信息
            let col=that.chartsCode.code.col;
            let htmlTemplate=`<div id="${that.objID}" 
            class="col-${!util.isNull(col)?col*2:'12'} col-xl-${!util.isNull(col)?col:'12'}"
            style="margin-bottom:20px;">
            <div style="padding-left: 1rem;padding-right: 1rem;" class="card">
            <h6 class="card-header with-elements">
            <div class="card-header-title" id="${that.objID}title"></div>
            <div class="card-header-elements ml-auto">
            <div id="${that.objID}radioButtons" class="btn-group btn-group-xs btn-group-toggle" data-toggle="buttons"></div>
            <div id="${that.objID}refreshButton"></div>
            </div>
            </h6>
            <div class="card-datatable table-responsive mt- pl-2 pr-2" style="padding: 1rem;">
            <div id="${that.objID}charts" style="width:100%;height:${util.isNull(that.chartsHeight)?350:that.chartsHeight}px;col-12"></div>
            </div>
            </div>
            </div>`;
            document.getElementById(that.parentObjID).insertAdjacentHTML("beforeEnd", htmlTemplate);
            resolve();
        })
    }
    render(){
        let that=this;
        that.init().then(()=>{
            let myViewObj=document.getElementById(that.objID+'charts');
            that.loadScript(function (){
                that.chart=echarts.init(myViewObj)
                window.addEventListener('resize',()=>{
                    that.chart.resize();//自适应屏幕
                })
                fullMap.push(that.objID,that);
                that.refreshCharts();
            });
        })
    }
    setOption(option){
        let that=this;
        that.option=option;
        that.chart.setOption(that.option);
    }
    setValue(value){
        let that=this;
        let dataType=that.chartsInfo.charts_data_type;//1静态（JSON）,2SQL,3扩展类
        let chartsType=that.chartsInfo.charts_type;//1折线图,2柱状图,3饼图
        if(dataType=='1'||dataType=='3'||chartsType=='3'){
            that.option.series[0].data=value
            if(chartsType=='1' || chartsType=='2'){
                let nameArr=[];
                for (let i = 0; i < value.length; i++) {
                    nameArr.push(value[i].name);
                }
                that.option.xAxis.data=nameArr;
            }
        }else if(chartsType=='1'){
            that.option.series[0].data=value;
            let nameArr=[];
            for (let i = 0; i < value.length; i++) {
                nameArr.push(value[i].name);
            }
            that.option.xAxis.data=nameArr;
        }else if(chartsType=='2'){
            that.option.series[0].data=value;
            let nameArr=[];
            for (let i = 0; i < value.length; i++) {
                nameArr.push(value[i].name);
            }
            that.option.xAxis[0].data=nameArr;
        }
        that.chart.setOption(that.option);
    }
    setTitle(title){
        let that=this;
        if(title.indexOf('${value}')>0){
            if(util.isNull(that.checkedValue)){
                title = title.replace('${value}', '');
            }else{
                title = title.replace('${value}', '--'+that.checkedValue);
            }
        }
        document.getElementById(that.objID+'title').innerText=title;
    }
    /**
     * @param value 允许为空 当设置了radioButton时需设置查询默认值（图表配置）
     */
    refreshCharts(value){
        if(util.isNull(value)){
            value='';
        }
        let that=this;
        that.radioValue=value;
        let params = { version: '1.0.0', dsCode: 'ds_charts',queryCode:'query_charts', methodName: 'getChartsInfo',value:value }
        params.chartsCode=that.code.chartsData.charts_code;
        let obj={url:config.getConfigJson().myActionUrl,params:params}
        return httpUtil.post(obj, (response)=>{
            that.chartsInfo=response.data.data.chartsInfo;
            if(!util.isNull(that.chartsInfo.js_file)){
                let jsonConfig={objID:that.objID,button_method:that.chartsInfo['js_method_name']}
                util.import2023(that.chartsInfo.js_file,jsonConfig);
            }else{
                let option=util.toOldChar(that.chartsInfo.option_config)
                option=util.fixJsonString(option)
                let optionObj=JSON.parse(option);//校验是不是js对象
                that.setOption(optionObj);
                let dataType=that.chartsInfo.charts_data_type;
                if(dataType!=''&&dataType=='1'){//静态JSON
                    let data=util.toOldChar(that.chartsInfo.d_json)
                    let dataObj=JSON.parse(data);//校验是不是js对象
                    that.setValue(dataObj);
                }
                if(dataType=='2'){//sql
                    that.setValue(that.chartsInfo.data);
                }
                if(dataType=='3'){//扩展类
                    that.setValue(that.chartsInfo.data);
                }
                that.showRefreshButton()
                that.showRadioButtons(value)
            }
            that.setTitle(that.chartsInfo.title)
        })
    }
    showRefreshButton(){
        let that=this;
        let isShowRefreshButton=that.chartsInfo.is_refresh_button;
        if(util.isNull(isShowRefreshButton)||isShowRefreshButton=='N'){
            return ;//未配置展示刷新按钮则不渲染
        }
        let html=`<button type="button" title="刷新" id="${that.objID}refresh"
        class="btn btn-outline-primary btn-xs icon-btn md-btn-flat">
           <i class="ion ion-md-sync"></i>
        </button>`;
        document.getElementById(that.objID+'refreshButton').innerHTML=html;
        let refreshEle=document.getElementById(that.objID+'refresh');
        util.addEventListener(refreshEle,'click',function (){
            that.refreshCharts().then(()=>{
                khcToastr.showSuccessMessage('刷新成功');
            });
        })
    }
    /**
     * @param value 允许为空 默认选中的值
     */
    showRadioButtons(value){
        let that=this;
        let isShowRadioButton=that.chartsInfo.is_radio_button;
        if(util.isNull(isShowRadioButton)||isShowRadioButton=='N'){
            return ;//未配置展示radio按钮则不渲染
        }
        if(util.isNull(value)){
            value=that.chartsInfo.radio_default_value//设置默认选中
        }
        let dict=that.chartsInfo.radio_dict;
        let radioShowType=that.chartsInfo['radio_show_type']
        that.checkedValue='';
        if(util.isNull(radioShowType)||radioShowType=='1'){
            let radioButtonHtml=``;
            for (let i = 0; i < dict.length; i++) {
                radioButtonHtml+=`
            <label class="btn btn-default borderless md-btn-flat ${value==dict[i].key?'active':''}" id="${that.objID}${dict[i].key}radio">
            <input type="radio" name="btn-radio" value="${dict[i].key}">${dict[i].value}
            </label>`;
                if(value==dict[i].key){
                    that.checkedValue=dict[i].value;
                }
            }
            document.getElementById(that.objID+'radioButtons').innerHTML=radioButtonHtml;
            for (let i = 0; i < dict.length; i++) {
                let refreshEle=document.getElementById(that.objID+dict[i].key+'radio');
                util.addEventListener(refreshEle,'click',function (){
                    that.refreshCharts(dict[i].key);
                })
            }
        }else{
            let selectButtonHtml=``;
            let itemHtml=``;
            for (let i = 0; i < dict.length; i++) {
                itemHtml+=`<a class="dropdown-item ${value==dict[i].key?'active':''}" href="javascript:void(0)" id="${that.objID}${dict[i].key}radio">${dict[i].value}</a>`;
                if(value==dict[i].key){
                    that.checkedValue=dict[i].value;
                }
            }
            selectButtonHtml+=`<div class="btn-group" style="${that.chartsInfo['is_show_radio']=='Y'?'':'display:none'}">
                    <button class="btn btn-default btn-sm dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="false">切换</button>
                    <div class="dropdown-menu" x-placement="bottom-start" style="position: absolute; top: 25px; left: 0px; will-change: top, left;">
                      ${itemHtml}
                    </div>
                  </div>`
            document.getElementById(that.objID+'radioButtons').innerHTML=selectButtonHtml;
            for (let i = 0; i < dict.length; i++) {
                let refreshEle=document.getElementById(that.objID+dict[i].key+'radio');
                util.addEventListener(refreshEle,'click',function (){
                    that.refreshCharts(dict[i].key);
                })
            }
        }
    }
    loadScript(callback){
        util.loadScript('../js/echarts/echarts.min.js','text/javaScript',callback)
    }
}
export {charts}