<template>
  <div class="commodity-chart-editor-container" id="box">
    <span
      class="slide-icon slide-right"
      @click="isSlideLeft = !isSlideLeft"
      v-show="isSlideLeft"
    >
      <i class="el-icon-d-arrow-right"></i>
    </span>
    <div class="left-cont" v-show="!isSlideLeft" id="left">
      <div class="left-top">
        <el-button type="primary" plain @click="$router.back()">取消</el-button>
      </div>
      <div class="left-min">
        <div class="search-cont">
					<selectTarget  
            :defaultId="chartInfoData.EdbInfoList?chartInfoData.EdbInfoList[0].EdbInfoId:''"
            :defaultOpt="chartInfoData.EdbInfoList?[chartInfoData.EdbInfoList[0]]:[]"
            :defaultType="chartInfoData.EdbInfoList?chartInfoData.EdbInfoList[0].EdbInfoCategoryType:''"
            :selectStyleType="2"
            @select="handleSelectTarget"
          />
				</div>

        <div class="section">
          <div>曲线图</div>
          <div class="section-item">
            <span style="flex-shrink:0;min-width:50px;">时间:</span>
            <el-select
                style="max-width: 110px;flex-shink:0;"
                v-model="chartInfo.Curve.DateType"
                placeholder="请选择"
                @change="getPreviewSplineChart"
            >
              <el-option
                  v-for="item in yearSelector"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
              />
            </el-select>
            <date-picker
              v-model="chartInfo.Curve.Date"
              v-show="chartInfo.Curve.DateType===5"
              style="width:150px;margin-left:10px;"
              type="month"
              range
              value-type="format"
              placeholder="请选择时间段"
              @change="dateChange"
            />
          </div>
          <div class="section-item">
            <span style="flex-shrink:0;min-width:50px;">上下限:</span>
            <el-input
              style="flex:2;margin-left:5px;margin-right:10px"
              :step="1"
              type="number"
              v-model="chartInfo.Curve.LeftMin"
              @change="val => { chartInfo.Curve.LeftMin=Number(val);changeSplineOption() }"
            />
            <span>至</span>
            <el-input
              style="flex:2;margin-left:5px;"
              :step="1"
              type="number"
              v-model="chartInfo.Curve.LeftMax"
              @change="val => { chartInfo.Curve.LeftMax=Number(val);changeSplineOption() }"
            />
          </div>
        </div>

        <div class="section">
          <div>标准差
            <el-tooltip effect="dark" placement="right">
              <div
                slot="content"
                v-html="ruleTips.StandardDeviation"
                style="line-height: 20px;width:300px"
              ></div>
              <i class="el-icon-question" style="color: #666" />
            </el-tooltip>
          </div>
          <div class="section-item">
            <div>滚动期数:</div>
            <el-input
              style="max-width:100px;margin-left:10px"
              :step="1"
              type="number"
              v-model="chartInfo.StandardDeviation.CalculateValue"
              @change="val => { chartInfo.StandardDeviation.CalculateValue = Number(val); }"
            />
          </div>
        </div>

        <div class="section">
          <div>百分位
            <el-tooltip effect="dark" placement="right">
              <div
                slot="content"
                v-html="ruleTips.Percentile"
                style="line-height: 20px;width:300px"
              ></div>
              <i class="el-icon-question" style="color: #666" />
            </el-tooltip>
          </div>
          <div class="section-item">
            <span style="flex-shrink:0;min-width:70px">时间长度:</span>
            <el-input
              style="width:100px;margin-left:5px;margin-right:10px"
              :step="1"
              type="number"
              v-model="chartInfo.Percentile.CalculateValue"
              @change="val => { chartInfo.Percentile.CalculateValue = Number(val); }"
            />
            <el-select
                style="flex:1"
                v-model="chartInfo.Percentile.CalculateUnit"
                placeholder="请选择"
            >
            <el-option
                v-for="item in unitOpt"
                :key="item.val"
                :label="item.label"
                :value="item.val"
            />
            </el-select>
          </div>
        </div>

        <div class="section">
          <div>频率分布
            <el-tooltip effect="dark" placement="right">
              <div
                slot="content"
                v-html="ruleTips.FrequencyDistribution"
                style="line-height: 20px;width:300px"
              ></div>
              <i class="el-icon-question" style="color: #666" />
            </el-tooltip>
          </div>
          <div class="section-item">
            <span style="flex-shrink:0;min-width:70px">时间段：</span>
            <el-select
                style="max-width: 110px;flex-shink:0;"
                v-model="chartInfo.FrequencyDistribution.DateType"
                placeholder="请选择"
            >
            <el-option
                v-for="item in frequencyDateOption"
                :key="item.value"
                :label="item.name"
                :value="item.value"
            />
            </el-select>
            <date-picker
              v-model="chartInfo.FrequencyDistribution.Date"
              v-show="chartInfo.FrequencyDistribution.DateType==8"
              style="width:150px;margin-left:10px;"
              type="month"
              range
              value-type="format"
              placeholder="请选择时间段"
              @change="dateChange($event,'frequecny')"
            />
          </div>
          <div class="section-item">
            <span style="flex-shrink:0;min-width:70px">频段数</span>
            <el-select
                style="max-width: 110px;flex-shink:0;"
                v-model="chartInfo.FrequencyDistribution.FrequencyValue"
                placeholder="请选择频段数"
            >
              <el-option
                :label="10"
                :value="10"
              />
              <el-option
                :label="20"
                :value="20"
              />
            </el-select>
          </div>
        </div>

        <el-button type="primary" style="float:right" @click="handlePreviewChart">确定</el-button>
      </div>
      <span
        class="move-btn resize"
        v-drag
        id="resize"
        @mousemove="dynamicNode && resetNodeStyle(dynamicNode)"
      ></span>
      <span class="slide-icon slide-left" @click="isSlideLeft = !isSlideLeft">
        <i class="el-icon-d-arrow-left"></i>
      </span>
    </div>
    <div
      class="right-cont"
      id="right"
      :style="isSlideLeft ? 'width:100%' : `width:80%`"
    >
      <div
        class="chart-min-cont"
        v-if="chartBatchData"
      >
          <div class="card-wrapper">
            <chartCard 
              :entryType="1"
              ref="chartCard1"
              :data="chartBatchData.CurveData"
              :settings="chartInfo"
              :isChartAdd="buttonAuth.isCurveChartAdd"
              @saveChart="saveChartToBaseHandle"
            />
          </div>
          <div class="card-wrapper" v-if="chartBatchData.StandardDeviationData">
            <chartCard 
              :entryType="2"
              ref="chartCard2"
              :data="chartBatchData.StandardDeviationData"
              :settings="chartInfo"
              :isChartAdd="buttonAuth.isStandardChartAdd"
              :isEdbAdd="buttonAuth.isStandardEdbAdd"
              @saveChart="saveChartToBaseHandle"
              @saveEdb="saveEdbToBaseHandle"
            />
          </div>
          <div class="card-wrapper" v-if="chartBatchData.PercentileData">
            <chartCard 
              :entryType="3"
              ref="chartCard3"
              :data="chartBatchData.PercentileData"
              :settings="chartInfo"
              :isChartAdd="buttonAuth.isPercentileChartAdd"
              :isEdbAdd="buttonAuth.isPercentileEdbAdd"
              @saveChart="saveChartToBaseHandle"
              @saveEdb="saveEdbToBaseHandle"
            />
          </div>
          <div class="card-wrapper" v-if="chartBatchData.FrequencyDistributionData">
            <chartCard 
              :entryType="4"
              ref="chartCard4"
              :data="chartBatchData.FrequencyDistributionData"
              :settings="chartInfo"
              :isChartAdd="buttonAuth.isFrequencyChartAdd"
              @saveChart="saveChartToBaseHandle"
            />
          </div>
      </div>

      <div class="nodata" v-else>
        <img
          src="~@/assets/img/data_m/table_no.png"
          alt=""
          style="display: block; width: 140px; height: 148px; margin: 0 auto"
        />
        暂无信息
      </div>
    </div>

    <!-- 图表保存入库 -->
    <saveChartToBase
      :isShow.sync="isSaveChartToBase"
      :source="saveSource"
      :saveScence="saveScence"
      :chartData="chartData"
      @saveBack="saveChartBack"
    />

    <!-- 指标保存入库 -->
    <saveEdbToBase
      :isShow.sync="isSaveEdbToBase"
      :source="saveSource"
      :saveScence="saveScence"
      :chartData="chartData"
      @saveBack="saveEdbBack"
    />
  </div>
</template>

<script>
import { dataBaseInterface } from '@/api/api.js';
import * as preDictEdbInterface from '@/api/modules/predictEdbApi.js';
import {yearSelector} from '@/utils/defaultOptions';
import {statisticFeatureInterface} from '@/api/modules/chartRelevanceApi';
import selectTarget from './components/selectTarget.vue'
import chartCard from './components/chartCard.vue';
import SaveChartOther from '@/views/dataEntry_manage/components/SaveChartOther';
import saveChartToBase from './components/saveChartTobaseDia.vue';
import saveEdbToBase from './components/saveEdbToBaseDia.vue'
export default {
  components: { selectTarget,chartCard,SaveChartOther,saveChartToBase,saveEdbToBase },
  directives: {
    drag(el, bindings) {
      el.onmousedown = function (e) {
        var init = e.clientX;
        // console.log(init);
        var box = $('#box')[0];
        // console.log(box.clientWidth)
        let total_wid = box.offsetWidth;
        var left = $('#left')[0];
        var right = $('#right')[0];
        var initWidth = left.offsetWidth;
        document.onmousemove = function (e) {
          var end = e.clientX;
          var newWidth = end - init + initWidth;
          left.style.width = newWidth + 'px';
          right.style.width = newWidth > 300 ? total_wid - newWidth + 'px' : total_wid - 320 + 'px';
        };
        document.onmouseup = function () {
          document.onmousemove = document.onmouseup = null;
          e.releaseCapture && e.releaseCapture();
        };
        e.setCapture && e.setCapture();
        return false;
      };
    },
  },
  data() {
    return {
      chart_code: this.$route.query.code || '',
      isSlideLeft: false,
      chartInfoData: {},
      chartBatchData:null,

      yearSelector: [
        ...yearSelector,
        { name: '自定义',value: 5 }
      ],

      frequencyDateOption: [
        { name: '最近3月',value:1 },
        { name: '最近6月',value:2 },
        { name: '最近1年',value:3 },
        { name: '最近2年',value:4 },
        { name: '最近3年',value:5 },
        { name: '最近5年',value:6 },
        { name: '最近10年',value:7 },
        { name: '自定义',value:8 },
      ],
      chartInfo: {
        MultipleGraphConfigId: 0,
        EdbInfoId: 0,
        Curve: {
          DateType:yearSelector[0].value,
          Date: [],
          StartDate: '',
          EndDate: '',
          LeftMin: 0,
          LeftMax: 0
        },
        StandardDeviation: {
          CalculateValue: 0
        },
        Percentile: {
          CalculateValue: 0,
          CalculateUnit: '天'
        },
        FrequencyDistribution: {
          DateType: 1,
          Date: [],
          StartDate: '',
          EndDate: '',
          FrequencyValue: 10,
        }
      },
      unitOpt:[
        {label:'年',val:'年'},
        {label:'季',val:'季'},
        {label:'月',val:'月'},
        {label:'周',val:'周'},
        {label:'天',val:'天'},
      ],

      buttonAuth: { //按钮控制
        isCurveChartAdd: false,
        isStandardChartAdd: false,
        isStandardEdbAdd: false,
        isPercentileChartAdd: false,
        isPercentileEdbAdd: false,
        isFrequencyChartAdd: false,
      },

      ruleTips: {
        StandardDeviation: `计算所选时间范围内数据的样本标准差s，s=sqrt(((x1-x)^2 (x2-x)^2 ......(xn-x)^2)/(n-1))，n表示数据个数。`,
        Percentile: `对所选时间范围内的数据，取最大值Max，最小值Min，计算Max-Min，百分位=(现值-Min)/(Max-Min)，Max=Min时不予计算。`,
        FrequencyDistribution: `在所选时间范围内，取最大值和最小值，根据频段数划分多个间距相同的区间（左闭右开，最后一个区间为左闭右闭），统计数据值落在每个区间的数据个数，频率=落在某区间数据个数/所选时间段内数据总个数，累计频率为从最小值所在区间对应的频率开始累加。`
      },

      /* 图表入库 */
      isSaveChartToBase: false,
      saveSource:0,//图表位置1 2 3 4
      chartData: {},
      saveScence: '',//另存为

       /* 指标入库 */
      isSaveEdbToBase: false,

      oldEdbInfoType: 0,//原指标来源
    };
  },
  methods: {

    async getOptionDetail() {
      if(!this.chart_code) return
      const res = await statisticFeatureInterface.getOptionByCode({ UniqueCode: this.chart_code });

      if(res.Ret !== 200) return 

      const { 
        MultipleGraphConfigId,
        Curve,
        Percentile,
        StandardDeviation,
        FrequencyDistribution,
        EdbInfoList,
        ChartMappingList,
        EdbMappingList
      } = res.Data;

      this.chartInfoData = {
        EdbInfoList: EdbInfoList
      }
      this.oldEdbInfoType = EdbInfoList[0].EdbInfoCategoryType;

      this.chartInfo = {
        MultipleGraphConfigId,
        EdbInfoId:EdbInfoList[0].EdbInfoId,
        Curve: {
          ...Curve,
          Date: [Curve.StartDate,Curve.EndDate],
        },
        StandardDeviation,
        Percentile,
        FrequencyDistribution: {
          ...FrequencyDistribution,
          Date: [FrequencyDistribution.StartDate,FrequencyDistribution.EndDate],
        }
      }


      //统计图的2 3 4对应source8 9 10但其实图表source又是7 8 9 别问为什么这样搞问后端 我也乱的一批
      this.buttonAuth =  {
        isCurveChartAdd: ChartMappingList.some(_ => _.MultipleLocationSource===1),
        isStandardChartAdd: ChartMappingList.some(_ => _.MultipleLocationSource===8),
        isStandardEdbAdd: EdbMappingList.some(_ => _.MultipleLocationSource===8),
        isPercentileChartAdd: ChartMappingList.some(_ => _.MultipleLocationSource===9),
        isPercentileEdbAdd: EdbMappingList.some(_ => _.MultipleLocationSource===9),
        isFrequencyChartAdd: ChartMappingList.some(_ => _.MultipleLocationSource===10),
      }

      this.getPreviewChartData(); 
    },

    // 确定保存图表配置
    async handlePreviewChart(){
      let params = {
       ...this.chartInfo 
      }
      const res = await statisticFeatureInterface.chartOptionsSet(params);
      if(res.Ret !== 200) return

      const { MultipleGraphConfigId } = res.Data;
      this.chartInfo.MultipleGraphConfigId = MultipleGraphConfigId;
      this.getPreviewChartData()
      
    },

    async getPreviewChartData(){
      if(!this.chartInfo.EdbInfoId) return this.$message.warning('请选择指标')
      let params = {
       ...this.chartInfo 
      }
      const res = await statisticFeatureInterface.previewChartBatch(params);
      if(res.Ret !== 200) return
      this.chartBatchData = res.Data;
          
    },

    /* 获取曲线图数据 */
    async getPreviewSplineChart() {
      if(!this.chartInfo.EdbInfoId) return
      let params = {
       ...this.chartInfo 
      }
      const res = await statisticFeatureInterface.previewSpline(params);
      if(res.Ret !== 200) return
      this.chartBatchData = this.chartBatchData ? {
        ...this.chartBatchData,
        CurveData: res.Data.CurveData
      } : { CurveData: res.Data.CurveData};
    },

    /* 曲线配置变化重绘图 */
    changeSplineOption() {
      const { LeftMin,LeftMax } = this.chartInfo.Curve;
      if(this.$refs.chartCard1) {
        this.$refs.chartCard1.options.yAxis[0].max = Number(LeftMax);
        this.$refs.chartCard1.options.yAxis[0].min = Number(LeftMin);
      }
    },

    dateChange(val,type='') {
      if(type === 'frequecny') {
        this.chartInfo.FrequencyDistribution.StartDate = val[0] || '';
        this.chartInfo.FrequencyDistribution.EndDate = val[1] || '';
      }else {
        this.chartInfo.Curve.StartDate = val[0] || '';
        this.chartInfo.Curve.EndDate = val[1] || '';
        this.getPreviewSplineChart()
      }
    },

    // 指标选择
    async handleSelectTarget(e){
      if(!e) return
      this.chartInfo.EdbInfoId=e.EdbInfoId;
      const {max,min} = await this.getEdbDetail(e);
      this.chartInfo.Curve.LeftMin = min;
      this.chartInfo.Curve.LeftMax = max;
      this.getPreviewSplineChart()
    },

    //选择指标后填入上下限
    async getEdbDetail({EdbInfoId,EdbInfoType}) {
      this.oldEdbInfoType = EdbInfoType;
      const { Data } = EdbInfoType 
      ? await preDictEdbInterface.edbDetail({EdbInfoId})
      : await dataBaseInterface.calculateDetail({EdbInfoId})

      return { 
        max: EdbInfoType ? Data.MaxValue : Data.EdbInfoDetail.MaxValue,
        min: EdbInfoType ? Data.MinValue : Data.EdbInfoDetail.MinValue,
      }
    },

    reloadRightWid() {
      let total_wid = $('#box')[0].offsetWidth;
      let left = $('#left')[0].offsetWidth;
      let rigtWid = total_wid - left - 20 + 'px';
      $('#right')[0].style.width = rigtWid;
    },

    /* 保存指标入库 */
    saveEdbToBaseHandle({type,chartData,scence}) {
      this.saveSource = type;
      this.chartData = chartData;
      this.saveScence = scence;
      this.isSaveEdbToBase = true;
    },

    /* 保存完指标 按钮控制 */
    saveEdbBack({source}) {

      if(source===2) this.buttonAuth.isStandardEdbAdd = true;
      else if(source===3)  this.buttonAuth.isPercentileEdbAdd = true;
    },

    /* 保存图表 */
    saveChartToBaseHandle({type,chartData,scence}) {
      this.saveSource = type;
      this.chartData = chartData;
      this.saveScence = scence;
      this.isSaveChartToBase = true;
    },


    /* 保存完图表 */
    saveChartBack({source,id}) {
      this.$message.success('保存成功');
      this.setButtonAuth(source);
      //封面图
      this.$refs[`chartCard`+source].setChartImage(source,id)
    },
    
    /* 保存图表后按钮控制 */
    setButtonAuth(source) {
      const sourceMap = {
        1: 'isCurveChartAdd',
        2: 'isStandardChartAdd',
        3: 'isPercentileChartAdd',
        4: 'isFrequencyChartAdd'
      }
      this.buttonAuth[sourceMap[source]] = true;
    }
  },
  mounted() {
    this.getOptionDetail();
    window.addEventListener('resize', this.reloadRightWid);
  },
  destroyed() {
    window.removeEventListener('resize', this.reloadRightWid);
  }
};
</script>
<style lang="scss">
.commodity-chart-editor-container {
  $font-small: 12px;
  $font-normal: 14px;

  display: flex;
  * {
    box-sizing: border-box;
  }
  .el-form--label-top .el-form-item__label {
    padding: 0;
  }
  .label-left{
      display: flex;
      margin-top: 20px;
      .el-form-item__label{
          flex-shrink: 0;
          margin-right: 10px;
      }
      .el-date-editor.el-input, .el-date-editor.el-input__inner{
          width: auto;
      }
  }
  
  .target-other-name .el-input__inner {
    padding: 0 30px 0 5px !important;
    height: 40px !important;
    line-height: 40px !important;
  }
  .el-color-picker--mini .el-color-picker__trigger {
    width: 60px;
    height: 25px;
    padding: 0;
  }
  .el-color-picker--mini .el-color-picker__mask {
    width: 60px;
    height: 25px;
  }

  .slide-icon {
    padding: 20px 0;
    /* display: block; */
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.3);
    border-radius: 5px;
    cursor: pointer;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    z-index: 99;
    &:hover {
      background-color: rgba(0, 0, 0, 0.05);
    }
    &.slide-left {
      right: 0;
    }
    &.slide-right {
      left: 0;
    }
  }
  .left-cont {
    width: 380px;
    min-width: 380px;
    background: #fff;
    margin-right: 20px;
    border: 1px solid #ececec;
    border-radius: 4px;
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
    height: calc(100vh - 113px);
    overflow: hidden;
    position: relative;
    box-sizing: border-box;
    .left-top {
      padding: 15px 20px;
      border-bottom: 1px solid #ececec;
      box-shadow: 0px 3px 6px rgba(167, 167, 167, 0.09);
    }
    .left-min {
      padding: 20px;
      max-height: calc(100vh - 190px);
      overflow-y: auto;
      
      .section {
        border-top: 1px dashed #DCDFE6;
        margin-top: 20px;
        padding-top: 15px;
        .section-item{
          display: flex;
          align-items: center;
          font-size: 14px;
          color: #606266;
          margin: 10px 0;
        }
      }

      .left-bottom {
        margin-top: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
     
    }
    .move-btn {
      height: 100%;
      width: 4px;
      position: absolute;
      right: 0px;
      top: 0;
      &:hover {
        cursor: col-resize;
      }
    }
  }
  .right-cont {
    width: 80%;
    /* =================== */
    .chart-min-cont {
      /* background: #fff; */
      height: calc(100vh - 118px);
      overflow-y: auto;
      display: flex;
      flex-wrap: wrap;
      .card-wrapper {
        width: 48%;
        margin-bottom: 20px;
        min-height: 350px;
        &:nth-child(2n) {
          margin-left: 15px;
        } 
        .card-item {
          padding: 20px;
          background: #fff;
          .top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
          }
          .title {
            /* max-width: 250px; */
            font-size: 15px;
            text-align: left;
            margin: 10px 0;
          }
        }
      }
    }
    .nodata {
      height: calc(100vh - 120px);
      background-color: #fff;
      text-align: center;
      font-size: 16px;
      color: #666;
      padding: 100px 0;
    }
  }
}
</style>
<style lang="scss">
.commodity-chart-editor-container  {
  .edb-item-style .el-input__icon {
    line-height: 27px;
  }
  .mx-datepicker {
    width: 200px !important;
  }
}
</style>
