<template>
  <div style="height: 100%">
    <el-row style="height: 100%">
      <el-col :span="12" style="height: 100%;overflow: auto;padding-bottom: 12px;" class="leftCol">
        <div style="text-align: center">
          <el-switch
            v-model="configSwitch"
            active-text="数据配置"
            inactive-text="图表配置">
          </el-switch>
        </div>
        <div v-show="!configSwitch" style="height: 100%">
          <el-form ref="form" :model="defaultData.configForm" label-width="80px">
            <el-form-item label="字体颜色">
              <el-cascader
                v-model="defaultData.configForm['textColor']" placeholder="请选择字体颜色"
                :options="getCascaderOption('color')"
                @change="textColorChange">
                <template #default="{ node, data }">
                  <span
                    :style="`color:${$testColor(data.color)?data.color: '#000'}`">{{
                      data.label
                    }}</span>
                </template>
              </el-cascader>
            </el-form-item>
            <el-form-item label="X坐标数据">
              <el-select v-model="defaultData.configForm['Xdata']" placeholder="请选择数据" @change="XdataChange"
                         clearable>
                <el-option :label="i" :value="i"
                           v-for="i in Object.keys(networkData)"></el-option>
              </el-select>
            </el-form-item>
            <div v-for=" (item,k) in defaultData.configForm['datas']">
              <el-form-item label="名称">
                <el-input v-model="item.name" @change="nameChange(k)"></el-input>
              </el-form-item>
              <el-form-item label="数据">
                <el-select v-model="item['data']" placeholder="请选择数据" @change="dataChange(k)"
                           clearable>
                  <el-option :label="i" :value="i"
                             v-for="i in Object.keys(networkData)"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="线颜色">
                <el-cascader
                  v-model="item['lineColor']" placeholder="请选择线颜色"
                  :options="getCascaderOption('color')"
                  @change="lineColorChange(k)"></el-cascader>
              </el-form-item>
              <div class="add" @click="addDatas()" v-if="k === defaultData.configForm['datas'].length -1">
                <img :src="addIcon" alt="" style="width: 100%">
              </div>
              <div class="subtract" @click="subtractDatas(k)">
                <img :src="subtractIcon" alt="" style="width: 100%">
              </div>
            </div>
            <div class="add" @click="addDatas()" v-if="  defaultData.configForm['datas'].length ===0">
              <img :src="addIcon" alt="" style="width: 100%">
            </div>
          </el-form>

          <div style="text-align: center;height: 60px;line-height: 60px">
            <el-button type="primary" @click="onSubmit">立即创建</el-button>
            <el-button>重置</el-button>
          </div>
        </div>
        <div v-show="configSwitch">
          <NetworkRequest :requests="defaultData.requests" @GetFinalData="getData" />
        </div>
      </el-col>
      <el-col :span="12" style="height: 100%">
        <div class="chart">
          <ComplexChart :defaultData="chartData" :colors="(styleData||{}).colors1"></ComplexChart>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import ComplexChart from '@/components/Configure/complex/chart';
import { queryGlobalCfg } from '@/api/configure/configuration/globalCfg';
import NetworkRequest from '@/components/Configure/networkRequest/NetworkRequest';

import addIcon from '@/assets/add.png';
import subtractIcon from '@/assets/subtract.png';

const props = defineProps({
  defaultData: Object,
  isDialog: Boolean,
  styleData: Object
});

const { defaultData, isDialog, styleData } = toRefs(props);

const globalList = ref([]);
const configSwitch = ref(false);
const chartData = ref({});
const networkData = ref({});
const $detectingNullValues = inject('$detectingNullValues');
const $delete = inject('$delete');
const $getFinalData = inject('$getFinalData');
const $testColor = inject('$testColor');


watch(() => networkData, (newVal) => {
    textColorChange();
    defaultData.value.configForm['datas'].forEach((i, k) => {
      dataChange(k);
      lineColorChange(k);
    });
    XdataChange();
  }, { deep: true }
);
watch(() => defaultData.value.requests, async (newVal) => {
    await getData();
    textColorChange();
    defaultData.value.configForm['datas'].forEach((i, k) => {
      dataChange(k);
      lineColorChange(k);
    });
    XdataChange();
  }, { deep: true }
);
onMounted(async () => {
  $detectingNullValues(defaultData.value, ['configForm', 'textColor']);
  $detectingNullValues(defaultData.value, ['configForm', 'datas', 0]);
  chartData.value = JSON.parse(JSON.stringify(defaultData.value.chartData));
  // 获取全局配置
  await queryGlobalCfg().then(e => {
    globalList.value = e;
  });
  // 轮询
  await getData();
  getChartData();
});

const addDatas = () => {
  let series = JSON.parse(JSON.stringify(chartData.value.series[0]));
  chartData.value.series[defaultData.value.configForm['datas'].length] = series;
  defaultData.value.chartData.series[defaultData.value.configForm['datas'].length] = series;
  defaultData.value.configForm['datas'][defaultData.value.configForm['datas'].length] = {
    data: '',
    lineColor: '',
    name: ''
  };
};
const subtractDatas = (k) => {
  $delete(chartData.value.series, k);
  $delete(defaultData.value.chartData.series, k);
  $delete(defaultData.value.configForm['datas'], k);
};
const getCascaderOption = (el) => {
  if (el === 'color') {
    let styleData1 = JSON.parse(JSON.stringify(styleData.value?.colors || []));
    return [
      {
        value: 'system',
        label: '全局变量',
        children: globalList.value.filter(e => e.globalCfgType === el).map(v => {
          return {
            value: v.globalCfgId,
            label: v.globalCfgName,
            color: v.globalCfgDate
          };
        })
      },
      {
        value: 'styleData',
        label: '界面风格',
        children: styleData1?.map((v, k) => {
          return {
            value: k,
            label: v,
            color: v
          };
        }) || []
      }
    ];
  } else {
    return [
      {
        value: 'system',
        label: '全局变量',
        children: globalList.value.filter(e => e.globalCfgType === el).map(v => {
          return {
            value: v.globalCfgId,
            label: v.globalCfgName,
            color: v.globalCfgDate
          };
        })
      }
    ];
  }
};
const getData = async (e) => {
  let data = await $getFinalData(defaultData.value.requests);
  networkData.value = data;
};
const emit = defineEmits(['close']);
const onSubmit = async () => {
  if (isDialog.value) {
    emit('close');
  }
};
const getChartData = () => {
  textColorChange();
  XdataChange();
  defaultData.value.configForm['datas'].forEach((i, k) => {
    dataChange(k);
    lineColorChange(k);
    nameChange(k);
  });
};
const lineColorChange = (k) => {
  $detectingNullValues(chartData.value, ['series', k, 'lineStyle', 'color']);
  if (defaultData.value.configForm['datas'][k]['lineColor'][0] === 'system') {
    chartData.value.series[k].lineStyle['color'] = globalList.value.find(e => e.globalCfgId === defaultData.value.configForm['datas'][k].lineColor?.[1])?.globalCfgDate || '';
  }
  if (defaultData.value.configForm['datas'][k]['lineColor'][0] === 'styleData') {
    chartData.value.series[k].lineStyle['color'] = styleData.value.colors[defaultData.value.configForm['datas'][k]['lineColor'][1]];
  }
};
const textColorChange = () => {
  $detectingNullValues(chartData.value, ['textStyle', 'color']);
  if (defaultData.value.configForm['textColor'][0] === 'system') {
    chartData.value.textStyle['color'] = globalList.value.find(e => e.globalCfgId === defaultData.value.configForm.textColor?.[1])?.globalCfgDate || '';
  }
  if (defaultData.value.configForm['textColor'][0] === 'styleData') {
    chartData.value.textStyle['color'] = styleData.value.colors[defaultData.value.configForm['textColor'][1]];
  }
};
const dataChange = (k) => {
  $detectingNullValues(chartData.value, ['series', k, 'data']);
  chartData.value.series[k]['data'] = networkData.value[defaultData.value.configForm['datas'][k].data];
};
const XdataChange = (k) => {
  $detectingNullValues(chartData.value, ['xAxis', 'data']);
  chartData.value.xAxis['data'] = networkData.value[defaultData.value.configForm.Xdata];
};
const nameChange = (k) => {
  $detectingNullValues(chartData.value, ['series', k, 'name']);
  chartData.value.series[k]['name'] = defaultData.value.configForm['datas'][k].name;
};
</script>

<style scoped lang="less">
.chart {
  width: 100%;
  height: 100%;
}

.notScroll {
  &::-webkit-scrollbar {
    display: none;
  }
}

.leftCol::-webkit-scrollbar {
  display: none;
}

.add {
  display: inline-block;
  width: 1vw;
  height: 1vw;
  padding: 0.5vw;
  background-color: #409EFF;
  border-radius: 50%;
  margin: 0 1vw;
  cursor: pointer;
}

.subtract {
  display: inline-block;
  width: 1vw;
  height: 1vw;
  padding: 0.5vw;
  background-color: #909399;
  border-radius: 50%;
  margin: 0 1vw;
  cursor: pointer;
}

.textArea {
  position: relative;

  .textAreaIcon {
    position: absolute;
    top: 12px;
    right: 8px;
  }
}
</style>
