import emitter from '../../../../../../components/xform/utils/emitter';
import i18n from '../../../../../../components/xform/utils/i18n';
import fieldMixin from '../../../../../../components/xform/form-designer/form-widget/field-widget/fieldMixin';

import {deepClone} from '../../../../../../components/xform/utils/util';
import {extendDeeply} from "@base/utils/index.js";
import {use} from 'echarts/core';
import {CanvasRenderer} from 'echarts/renderers';
import {BarChart} from 'echarts/charts';
import {TitleComponent, TooltipComponent, LegendComponent, GridComponent} from 'echarts/components';
import {THEME_KEY} from 'vue-echarts';

use([CanvasRenderer, BarChart, TitleComponent, TooltipComponent, LegendComponent, GridComponent]);

let modules = {};
modules = {
  componentName: 'FieldWidget', //必须固定为FieldWidget，用于接收父级组件的broadcast事件
  mixins: [emitter, fieldMixin, i18n],
  props: {
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,

    designState: {
      type: Boolean,
      default: false
    },

    subFormRowIndex: {
      /* 子表单组件行索引，从0开始计数 */
      type: Number,
      default: -1
    },
    subFormColIndex: {
      /* 子表单组件列索引，从0开始计数 */
      type: Number,
      default: -1
    },
    subFormRowId: {
      /* 子表单组件行Id，唯一id且不可变 */
      type: String,
      default: ''
    }
  },
  provide: {
    [THEME_KEY]: 'light'
  },
  data() {
    return {
      requestAccess: null,
      serieClone: {},
      showChart: true,
      colors: [
        {
          type: 'linear',
          x: 0.5,
          y: 0.9,
          r: 0.2,
          colorStops: [{
            offset: 1, color: '#08C084' // 0% 处的颜色
          }, {
            offset: 0, color: '#97EACE' // 100% 处的颜色
          }],
        },
        {
          type: 'linear',
          x: 0.5,
          y: 0.9,
          r: 0.2,
          colorStops: [{
            offset: 1, color: '#29ABE3' // 0% 处的颜色
          }, {
            offset: 0, color: '#AADEF4' // 100% 处的颜色
          }],
        },
        {
          type: 'linear',
          x: 0.5,
          y: 0.9,
          r: 0.2,
          colorStops: [{
            offset: 1, color: '#0044FE' // 0% 处的颜色
          }, {
            offset: 0, color: '#97B3FF' // 100% 处的颜色
          }],
        },
        {
          type: 'linear',
          x: 0.5,
          y: 0.9,
          r: 0.2,
          colorStops: [{
            offset: 1, color: '#75018A' // 0% 处的颜色
          }, {
            offset: 0, color: '#C492CD' // 100% 处的颜色
          }],
        },
        {
          type: 'linear',
          x: 0.5,
          y: 0.9,
          r: 0.2,
          colorStops: [{
            offset: 1, color: '#BF0104' // 0% 处的颜色
          }, {
            offset: 0, color: '#E59697' // 100% 处的颜色
          }],
        },
        {
          type: 'linear',
          x: 0.5,
          y: 0.9,
          r: 0.2,
          colorStops: [{
            offset: 1, color: '#FF8B01' // 0% 处的颜色
          }, {
            offset: 0, color: '#FFCF95' // 100% 处的颜色
          }],
        },
        {
          type: 'linear',
          x: 0.5,
          y: 0.9,
          r: 0.2,
          colorStops: [{
            offset: 1, color: '#FAFE09' // 0% 处的颜色
          }, {
            offset: 0, color: '#FCFFAF' // 100% 处的颜色
          }],
        }
      ]
    };
  },
  computed: {
    pHeightStyle() {
      let echartHeight = this.field.options.echartHeight;
      if (echartHeight) {
        if (isNaN(echartHeight)) {
          if (echartHeight == 'auto' || echartHeight.slice(-1) == '%') {
            return '100%';
          }
        }
      }
      return '';
    },
    heightStyle() {
      let echartHeight = this.field.options.echartHeight;
      if (echartHeight) {
        let height = echartHeight;
        if (!isNaN(echartHeight)) {
          height = echartHeight + 'px';
        }
        return height;
      }
      return '';
    },
    nameSet: {
      get() {
        let chartOptions = this.field.options.echarBarOption;
        if (this.alignX) {
          return chartOptions.yAxis.data;
        } else {
          return chartOptions.xAxis.data;
        }
      },
      set(val) {
        let chartOptions = this.field.options.echarBarOption;
        if (this.alignX) {
          chartOptions.yAxis.data = deepClone(val || []);
        } else {
          chartOptions.xAxis.data = deepClone(val || []);
        }
      }
    },
    alignField() {
      let chartOptions = this.field.options.echarBarOption;
      if (this.alignX) {
        return 'yAxis';
      } else {
        return 'xAxis';
      }
    },
    alignX: {
      get() {
        let chartOptions = this.field.options.echarBarOption;
        if (chartOptions.xAxis.type == 'category') {
          return false;
        } else {
          return true;
        }
      },
      set(val) {
        let chartOptions = this.field.options.echarBarOption;
        if (val) {
          chartOptions.yAxis.type = 'category';
          chartOptions.xAxis.type = 'value';
          chartOptions.yAxis.data = deepClone(chartOptions.yAxis.data || chartOptions.xAxis.data || []);
          delete chartOptions.xAxis.data;
        } else {
          chartOptions.yAxis.type = 'value';
          chartOptions.xAxis.type = 'category';
          chartOptions.xAxis.data = deepClone(chartOptions.xAxis.data || chartOptions.yAxis.data || []);
          delete chartOptions.yAxis.data;
        }
      }
    },
    chartOption() {
      return this.field.options.echarBarOption
    }
  },
  beforeCreate() {
    /* 这里不能访问方法和属性！！ */
  },

  async created() {
    /* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
         需要在父组件created中初始化！！ */

    this.registerToRefList();
    this.initEventHandler();

    this.handleOnCreated();
    this.initOption();
    this.serieClone = deepClone(this.field.options.echarBarOption.series[0]);
  },

  mounted() {
    this.handleOnMounted();
  },

  beforeDestroy() {
    this.unregisterFromRefList();
  },

  methods: {
    reflush(){
      this.showChart = false;
      this.$nextTick(()=>{
        this.showChart = true
      })
    },
    getColors(){
      let chartColors = this.field.options.echarBarOption.colors || [];
      let colors = [...chartColors, ...this.colors];
      return colors
    },
    adjustColor() {
      let colors = this.getColors();
      let colorsSize = colors.length;
      this.field.options.echarBarOption.series.forEach((serie, index) => {
        if (colorsSize > index) {
          if (serie.itemStyle) {
            serie.itemStyle.color = colors[index]
          } else {
            serie.itemStyle = {
              color: colors[index]
            }
          }
        }
      })
    },
    initOption() {
      let echartConfig = this.handleCustomEvent(this.field.options.echartConfig) || {};
      this.field.options.echarBarOption = extendDeeply(this.field.options.echarBarOption, echartConfig);
      this.adjustColor();
    },
    /*async loadData() {
      if (this.designState) {
        this.showChart = true;
        return;
      }

      await this.initAccess();

      let requestAccess = this.requestAccess;
      if (!requestAccess) {
        return;
      }
      let serieClone = this.serieClone;
      var a, l, s;

      (l = this.getGlobalDsv() || {}),
        (s = new Object({})),
        overwriteObj(s, l),
        (s['widgetName'] = this.field.options.name),
        (s['requestAccess'] = requestAccess),
        (a = requestAccess.dsModel);
      // r = i.sent,
      runDataSourceRequest(a, s, this.getFormRef(), !1, this.$message).then(res => {
        let resDatas = res || [];
        let axisDatas = [];
        let nameDatas = [];
        let newSeries = [];

        if (serieClone) serieClone.data = [];
        resDatas.forEach(resData => {
          if (!axisDatas.includes(resData.axis)) {
            axisDatas.push(resData.axis);
          }
          if (resData.name == null) {
            resData.name = '';
          }
          if (!nameDatas.includes(resData.name)) {
            nameDatas.push(resData.name);
          }
        });
        let colors = this.colors;
        let colorsSize = colors.length;
        nameDatas.forEach((nameItem, index) => {
          let serie = deepClone(serieClone);
          serie.name = nameItem;
          if (serie.itemStyle) {
            if (colorsSize > index) {
              serie.itemStyle.color = colors[index]
            }
          }
          let serieDatas = [];
          axisDatas.forEach(axisData => {
            let value = 0;
            resDatas.forEach(resData => {
              if (axisData == resData.axis && resData.name == nameItem) {
                value = resData.data;
              }
            });
            serieDatas.push(value);
          });
          serie.data = serieDatas;
          newSeries.push(serie);
        });
        let chartOptions = this.field.options.echarBarOption;
        chartOptions[this.alignField].data = axisDatas;
        chartOptions.series = newSeries;
        this.showChart = true;
      });
    },
    async initAccess() {
      if (this.field.options.dsEnabled && this.field.options.accessCode) {
        let chartOptions = this.field.options.echarBarOption;
        let serieClone = this.serieClone;

        chartOptions[this.alignField].data = [];
        chartOptions.series = [];
        this.nameSet = [];
        // this.field.options.echarBarOption.series[0].data = [];
        return this.getFormRef().$http({
          url: SUPPORT_PREFIX + `/report_requestaccess/getByCode`,
          method: `post`,
          data: {
            stringOne: this.field.options.accessCode
          },
          isLoading: true,
          // modalStrictly: true,
          success: res => {
            let requestAccess = res.objx || {};

            let dsModel = {};
            if (requestAccess.accessViewContent) {
              dsModel = JSON.parse(requestAccess.accessViewContent);
            }
            if (!dsModel.headers) dsModel.headers = [];
            if (!dsModel.params) dsModel.params = [];
            if (!dsModel.data) dsModel.data = [];
            if (dsModel.dataHandlerCode == null) dsModel.dataHandlerCode = '';
            if (dsModel.configHandlerCode == null) dsModel.configHandlerCode = '';
            if (dsModel.errorHandlerCode == null) dsModel.errorHandlerCode = '';

            requestAccess.dsModel = dsModel;
            this.requestAccess = requestAccess;
          }
        });
      } else {
        return null;
      }
    },*/
    loadDataDefaultHandle() {
      let reportTemplate = this.getFormRef().reportTemplate;
      let formCode = reportTemplate.formCode;
      let formScriptEnabled = this.field.options.formScriptEnabled || false;
      let scriptCode = this.field.options.formScriptCode
      if (!scriptCode) return;
      let accessParam = this.handleCustomEvent(this.field.options.formScriptParam)
      return this.formHttp({
        scriptCode: scriptCode,
        data: {
          formCode: formCode,
          formVersion: reportTemplate.formVersion,
          taBm: this.fieldKeyName,
          data: {
            ...accessParam
          }
        },
        callback: res => {
          let rows = res.objx || [];
          this.setValue(rows)
        }
      });
    },
    setValue(rows) {
      this.showChart = false;
      let serieClone = this.serieClone;
      let resDatas = rows || [];
      let axisDatas = [];
      let nameDatas = [];
      let newSeries = [];

      if (serieClone) serieClone.data = [];
      resDatas.forEach(resData => {
        if (!axisDatas.includes(resData.axis)) {
          axisDatas.push(resData.axis);
        }
        if (resData.name == null) {
          resData.name = '';
        }
        if (!nameDatas.includes(resData.name)) {
          nameDatas.push(resData.name);
        }
      });
      let colors = this.getColors();
      let colorsSize = colors.length;
      nameDatas.forEach((nameItem, index) => {
        let serie = deepClone(serieClone);
        serie.name = nameItem;
        if (colorsSize > index) {
          if (serie.itemStyle) {
            serie.itemStyle.color = colors[index]
          } else {
            serie.itemStyle = {
              color: colors[index]
            }
          }
        }
        let serieDatas = [];
        axisDatas.forEach(axisData => {
          let value = 0;
          resDatas.forEach(resData => {
            if (axisData == resData.axis && resData.name == nameItem) {
              value = resData.data;
            }
          });
          serieDatas.push(value);
        });
        serie.data = serieDatas;
        newSeries.push(serie);
      });
      let chartOptions = this.field.options.echarBarOption;
      chartOptions[this.alignField].data = axisDatas;
      chartOptions.series = newSeries;
      this.$nextTick(() => {
        this.showChart = true;
      })
    },
    getChart() {
      return this.$refs.chart;
    }
  }
};
export default modules
