<template>
  <div class="crossVariety-edit-page" 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">
        <div>
          <el-button type="primary" @click="saveChartHandle">保存</el-button>
          <el-button type="primary" plain @click="$router.back()">取消</el-button>

        </div>
        <div style="color:#409EFF;font-size: 16px;cursor: pointer;" @click="showExplain = true">
            <i class="el-icon-document" style="font-size:22px;"></i>
            操作说明
        </div>
      </div>

      <div class="left-min">
        <section class="section-item">
          <div class="top">
            <label>选择品种</label>
            <el-button
              v-permission="permissionBtn.statisticPermission.crossVariety_variety_edit"
              type="text" 
              @click="setDialogOpen('variety')"
            >品种管理</el-button>
          </div>
          <div class="list" v-if="varietyOptions.length">
            <el-tag 
              size="small" 
              :class="['tag',{'act':checkedVarietys.includes(item.ChartVarietyId)}]"
              v-for="item in varietyOptions"
              :key="item.ChartVarietyId"
              @click="checkVarietyHandle(item)"
            >{{item.ChartVarietyName}}</el-tag>
          </div>

          <tableNoData v-else text="暂无品种" size="mini"/>
        </section>

        <el-divider/>

        <section class="section-item">
          <div class="top">
            <label>标签配置</label>
            <el-button
              v-permission="permissionBtn.statisticPermission.crossVariety_tag_edit"
              type="text" 
              @click="setDialogOpen('tag')"
            >标签管理</el-button>
          </div>
          <div class="list" v-if="tagOptions.length">
            <el-tag 
              size="small" 
              :class="item.VarietyTotal?'act tag':'tag'"
              v-for="item in tagOptions"
              :key="item.ChartTagId"
              @click="setTagRelationOpen(item)"
            >{{item.ChartTagName}}</el-tag>
          </div>

          <tableNoData text="暂无标签" size="mini" v-else/>
        </section>

      </div>
      
      <span
        class="move-btn resize"
        v-drag
        id="resize"
      ></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"
      >
        <div class="chart-wrapper" v-if="options.series&&options.series.length">
          <div class="chart-show-cont"  v-if="!chartInfo.WarnMsg">
            <div style="position:relative;">
              <h2 class="chart-title">{{ chartInfo.ChartName }}</h2>
              <Chart 
                :options="options"
                minHeight="400px" 
                height="450px"
                ref="chartRef"
              />
              <span class="chart-author">作者:{{ chartInfo.SysUserRealName || accountName}}</span>

              <!-- 上下限 -->
              <template>	
                <div class="range-cont left">
                  <el-input
                    style="width: 60px; display: block"
                    size="mini"
                    type="number"
                    :min="0"
                    :max="100"
                    placeholder="上限"
                    v-model="chartLimit.max"
                    @change="changeLimit"
                  />
                  <el-input
                    class="min-data-input"
                    size="mini"
                    type="number"
                    :min="0"
                    :max="100"
                    placeholder="下限"
                    v-model="chartLimit.min"
                    @change="changeLimit"
                  />
                </div>
                <!-- x轴上下限 -->
                <div class="range-cont bottom" > 
                  <el-input
                    class="left"
                    size="mini"
                    type="number"
                    :min="0"
                    :max="100"
                    placeholder="下限"
                    v-model="chartLimit.x_min"
                    @change="changeLimit"
                  />
                  <el-input
                    class="left"
                    size="mini"
                    type="number"
                    :min="0"
                    :max="100"
                    placeholder="上限"
                    v-model="chartLimit.x_max"
                    @change="changeLimit"
                  />
                </div>
              </template>
              
            </div>
          </div>

          <!-- 异常显示 -->
          <p class="error-tip" style="min-height: 400px;" v-if="chartInfo.WarnMsg">{{chartInfo.WarnMsg}}</p>
        </div>

        <div class="nodata" v-else>
          <tableNoData text="暂无信息"/>
        </div>

        <div class="bottom-wrapper">
          <!-- 图表相关配置 -->
          <chartFormSection
            :tagList="tagOptions"
            :chartInfo="chartInfo"
            ref="chartFormRef"
            @getData="getChartPreviewData"
          />

          <!-- 指标列表 -->
          <edbTableSection :tableData="tableData"/>
        </div>

      </div> 

    </div>

    <!-- 管理弹窗 -->
    <tagSetDialog
      :isShow.sync="isShowSetDia"
      :type="dialogType"
      :dataList="dialogType==='variety'?varietyOptions:tagOptions"
      @refresh="dialogType==='tag'?getTagList():getVarietyList();"
    />

    <!-- 标签指标配置 -->
    <tagRelationDialog
      :isShow.sync="isShowTagRelationDia"
      :varietyList="varietyOptions"
      :info="tagRelationInfo"
      @refresh="getTagList"
    />

    <!-- 操作说明 -->
    <ExplainDialog 
        textArrName="crossVarietyAnalisisTextArr"
        :show-explain="showExplain"
        @close="showExplain = false"
    />
  </div>
</template>

<script>
import { crossVarietyInterface } from '@/api/modules/chartRelevanceApi';
import { dataBaseInterface } from '@/api/api';
import { chartSetMixin } from '@/views/dataEntry_manage/mixins/chartPublic';
import Chart from '@/views/dataEntry_manage/components/chart';
import ExplainDialog from '../components/explainDialog.vue';
import chartFormSection from './components/chartFormSection.vue';
import tagSetDialog from './components/tagSetDialog.vue';
import tagRelationDialog from './components/tagRelationDialog.vue';
import edbTableSection from './components/edbTableSection.vue'
export default {
  components: {
    ExplainDialog,
    Chart,
    chartFormSection,
    tagSetDialog,
    tagRelationDialog,
    edbTableSection
  },
  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;
      };
    },
  },
  mixins: [ chartSetMixin ],
  computed: {
    accountName() {
      return localStorage.getItem('userName')
    }
  },
  data() {
    return {
      chart_code: this.$route.query.code || '',
      isSlideLeft: false,
      chartInfo: {
        Source: 10,
        ChartName: '',
        SysUserRealName: ''
      },

      showExplain: false,

      checkedVarietys: [], //选中的品种
      varietyOptions: [],
      tagOptions: [],

      isShowSetDia: false,//管理弹窗
      dialogType: '',

      isShowTagRelationDia: false,//标签指标管理弹窗
      tagRelationInfo: {
        tagName:'',
        id: 0
      }
    };
  },
  methods: {

    /* 获取图表详情 */
    async getChartDetail() {
      if(!this.chart_code) return 

      let res = await dataBaseInterface.getChartByCode({
				UniqueCode: this.chart_code
			})

      if(res.Ret !== 200) return

      const { ChartInfo,DataResp,EdbInfoList } = res.Data;
      let configSet = JSON.parse(ChartInfo.ExtraConfig);
      this.checkedVarietys = configSet.VarietyList;
      this.$refs.chartFormRef.initData(configSet);

      this.chartInfo = ChartInfo;
      this.tableData = EdbInfoList;
      this.crossVarietyChartData = DataResp;
      this.chartLimit = {
        min: DataResp.YMinValue,
        max: DataResp.YMaxValue ,
        x_min: DataResp.XMinValue,
        x_max: DataResp.XMaxValue,
      }

      this.setCrossVarietyChart()
    },

    checkParmas(type='') {
      if(!this.checkedVarietys.length || !this.$refs.chartFormRef.form.CalculateValue || !this.$refs.chartFormRef.form.TagX ||!this.$refs.chartFormRef.form.TagY){
        
        type && this.dealWarnings()
        return false
      }
      return true
    },

    dealWarnings() {
      const {CalculateValue,TagX,TagY } = this.$refs.chartFormRef.form;
      let message = '';
      
      if(!this.checkedVarietys.length) message = '请选择品种'
      else if(!CalculateValue) message = '请输入时间长度'
      else if(!TagX) message = '请选择X轴坐标'
      else if(!TagY) message = '请选择Y轴坐标'

      this.$message.warning(message)
    },

    /* 获取标签列表 */
    async getTagList() {
      let res = await crossVarietyInterface.getTagList()

      if(res.Ret !== 200) return
      this.tagOptions = res.Data.List || []
    },

    async getVarietyList() {
      let res = await crossVarietyInterface.getVarietyList()

      if(res.Ret !== 200) return
      this.varietyOptions = res.Data.List || []
    },

    /* 预览数据 */
    async getChartPreviewData() {
      if(!this.checkParmas()) return;

      let params = {
        VarietyList: this.checkedVarietys,
        ...this.$refs.chartFormRef.form
      }
      let res = await crossVarietyInterface.chartPreview(params)

      if(res.Ret !== 200) return

      const { DataResp,EdbInfoList } = res.Data;
      this.tableData = EdbInfoList;
      
      this.chartLimit = {
        min: Number(DataResp.YMinValue),
        max: Number(DataResp.YMaxValue),
        x_min: Number(DataResp.XMinValue),
        x_max: Number(DataResp.XMaxValue)
      }
      this.crossVarietyChartData = DataResp;
      this.setCrossVarietyChart()
    },
    
    /* 选择品种 */
    checkVarietyHandle(item) {
      this.checkedVarietys.includes(item.ChartVarietyId) 
        ? this.checkedVarietys.splice(this.checkedVarietys.indexOf(item.ChartVarietyId),1) 
        : this.checkedVarietys.push(item.ChartVarietyId)

      this.getChartPreviewData();
    },

    /* 打开标签关联弹窗 */
    setTagRelationOpen(item) {
      this.tagRelationInfo = {
        tagName: item.ChartTagName,
        id: item.ChartTagId
      }
      this.isShowTagRelationDia = true;
    },

    /* 标签管理 */
    setDialogOpen(type) {
      this.dialogType = type;
      this.isShowSetDia = true;
    },

    /* 保存图表 */
    async saveChartHandle() {
      if(!this.checkParmas('warning')) return;

      let { min,max,x_min,x_max } = this.chartLimit;
      let params = {
        VarietyList: this.checkedVarietys,
        ...this.$refs.chartFormRef.form,
        XMinValue: String(x_min),
				XMaxValue: String(x_max),
				YMinValue: String(min),
				YMaxValue: String(max),
      }
      let res = this.chart_code 
        ? await crossVarietyInterface.chartEdit({...params,ChartInfoId: this.chartInfo.ChartInfoId})
        : await crossVarietyInterface.chartAdd(params)

      if(res.Ret !== 200) return
      this.setChartImage(res.Data);
    },

     /* 设置图表封面图片 */
    setChartImage(data) {
      let svg = this.$refs.chartRef.chart.getSVG({
        chart: {
          width: 340,
          height: 230,
        }
      });
      let form = new FormData();
      form.append('Img', svg);
      this.setImageHandle(form,data);
    },
    async setImageHandle(form,{ UniqueCode,ChartInfoId }) {
      let { Data } = await dataBaseInterface.uploadImgSvg(form);
      await dataBaseInterface.setChartImage({
        ChartInfoId: ChartInfoId,
        ImageUrl: Data.ResourceUrl,
      });

			this.$message.success('保存成功');
			this.$router.replace({
				path: '/crossVarietyChartList',
				query: {
					code: UniqueCode,
					id: ChartInfoId
				}
			})

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

  },
  mounted() {
    this.getVarietyList();
    this.getTagList();
    this.getChartDetail();
    window.addEventListener('resize', this.reloadRightWid);
  },
  destroyed() {
    window.removeEventListener('resize', this.reloadRightWid);
  },
  beforeRouteEnter(to, from, next) {
    if(to.query.code){
      to.matched[1].name='编辑图表'
    }else{
      to.matched[1].name='添加图表'
    }
    next()
  }
};
</script>
<style lang="scss" scoped>
.crossVariety-edit-page {
  $font-small: 12px;
  $font-normal: 14px;
  display: flex;
  * {
    box-sizing: border-box;
  }

  .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);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .left-min {
      padding: 0 20px;
      max-height: calc(100vh - 190px);
      overflow-y: auto;
      
      .section-item{
        padding: 20px 0;
        .top {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;

        }
        .list {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          .tag {
            color: #333;
            background: #fff;
            border-color: transparent;
            cursor: pointer;
            &.act {
              color: #0052D9;
              background-color: #e6eefb;
              border-color: #ccdcf7;
            }
          }
        }
      }

      .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%;
    overflow-x: auto;
    .chart-min-cont {
      background: #fff;
      min-width: 880px;
      height: calc(100vh - 118px);
      overflow-y: auto;
      display: flex;
      flex-wrap: wrap;
      .chart-wrapper {
				padding: 30px 0;
        width: 100%;
				/* =================== */
				.chart-show-cont {
					min-height: 400px;
					padding: 0 100px 50px;
					position: relative;
					.chart-title {
						font-size: 16px;
						font-weight: normal;
						text-align: center;
						margin-bottom: 10px;
					}
					.chart-author {
						font-size: 14px;
						color: #333;
						position: absolute;
						bottom: -50px;
						right: -70px;
					}
          .range-cont {
            position: absolute;
            top: 15%;
            .min-data-input {
              width: 60px;
              display: block;
            }
            &.left {
              left: -70px;
            }
            &.bottom {
              width: 100%;
              display: flex;
              justify-content: space-between;
              top: auto;
              right: 0;
              bottom: -4%;
              .left {
                width: 60px;
                display: block;
                flex-shrink: 0;
              }
            }
          }
				}
				.options-cont {
					display: flex;
					flex-wrap: wrap;
					justify-content: space-between;
				}
			}

      @media screen and (min-width: 1711px) {
        .min-data-input {
          margin-top: 290px;
        }
      }
      @media screen and (max-width: 1710px) {
        .min-data-input {
          margin-top: 250px;
        }
      }

    }
    .nodata {
      background-color: #fff;
      text-align: center;
      font-size: 16px;
      color: #666;
      width: 100%;
      padding: 100px 0;
    }
    .bottom-wrapper {
      width: 100%;
      padding: 20px;
      border-top: 1px solid #ebeff6;
    }
  }
}
</style>
<style lang="scss">
.crossVariety-edit-page {
  .el-input--mini .el-input__inner {
		padding: 0 0 0 4px;
	}
}
</style>
