<template>
  <div class="add-predicedb-page">
    <div class="aside-warp" v-show="isAsideShow">
      <div class="btn-box">
        <el-button type="primary" @click="saveHandle"><!-- 保存 -->{{$t('Dialog.confirm_save_btn')}}</el-button>
        <el-button type="primary" plain @click="$router.back()"><!-- 取消 -->{{$t('Dialog.cancel_btn')}}</el-button>
      </div>
      <div class="con">
        <el-form
          ref="formRef"
          hide-required-asterisk
          :model="formData"
          :rules="formRules"
        >
          <el-form-item prop="classify">
            <div class="item">
              <span class="label">{{$t('PredictEditPage.add_to_classify')}}<!-- 添加到分类 --></span>
              <el-cascader
                    v-model="formData.classify"
                    :options="classifyArr"
                    :props="{
                        label: 'ClassifyName',
                        value: 'ClassifyId',
                        children: 'Children',
                        checkStrictly: true
                    }"
                    style="width: 90%"
                    :placeholder="$t('Edb.InputHolderAll.input_classify')"
                />
            </div>
          </el-form-item>
          <el-form-item prop="oldEdb" v-if="!formData.edb_id">
            <div class="item">
              <span class="label">{{$t('Edb.choose_edb')}}<!-- 选择指标 --></span>
              <el-select
                v-model="formData.oldEdb"
                v-loadMore="searchLoad"
                style="width: 100%"
                :filterable="!formData.oldEdb"
                remote
                clearable
                :placeholder="$t('Edb.InputHolderAll.input_name_orid')"
                :remote-method="searchHandle"
                @click.native="inputFocusHandle"
                @change="selectEdbHandle"
              >
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
                <el-option
                  v-for="item in searchOptions"
                  :key="item.EdbInfoId"
                  :label="currentLang==='en'?(item.EdbNameEn||item.EdbName):item.EdbName"
                  :value="item.EdbInfoId"
                  :disabled="!item.HaveOperaAuth"
                >
                  <edbDetailPopover :info="item">
                    <div slot="reference">
                      <img 
                        :src="$icons.lock_ico2" 
                        width="18" 
                        height="18" 
                        style="vertical-align:middle" 
                        v-if="!item.HaveOperaAuth"
                      />

                      {{currentLang==='en'?(item.EdbNameEn||item.EdbName):item.EdbName}}
                    </div>
                  </edbDetailPopover>
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item prop="edbName">
            <div class="item">
              <span class="label">{{$t('PredictEditPage.predict_edb_name')}}<!-- 预测指标名称 --></span>
              <el-input
                v-model="formData.edbName"
                style="width: 100%"
                :placeholder="$t('Edb.InputHolderAll.input_name')"
              />
            </div>
          </el-form-item>
          <el-form-item prop="dateType">
            <div class="item">
              <span class="label">{{$t('PredictEditPage.predict_date_type')}}<!-- 预测日期类型 --></span>
               <el-select
                v-model="formData.dateType"
                :placeholder="$t('PredictEditPage.ph_date_type')"
                style="width: 100%"
                @change="getChartInfo"
              >
                <el-option :label="$t('PredictEditPage.date_type_trade')" value="交易日"></el-option>
                <el-option :label="$t('PredictEditPage.date_type_normal')" value="自然日"></el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item v-if="formData.oldEdbName">
            <div class="item" style="margin-top: 30px">
              <span class="label">{{$t('PredictEdbPage.old_edb_name')}}<!-- 原指标名称 -->：{{ formData.oldEdbName }}</span>
            </div>
          </el-form-item>
          <el-form-item prop="frequency">
            <div class="item">
              <span class="label">{{$t('Edb.Detail.e_fre')}}<!-- 频度 -->：{{ getFrequencyTrans(formData.frequency||'null') }}</span>
            </div>
          </el-form-item>
          <el-form-item prop="newdata">
            <div class="item">
              <span class="label">{{$t('Edb.Detail.e_latest_value')}}<!-- 最新值 -->：{{ formData.newdata }}</span>
            </div>
          </el-form-item>
          <el-form-item prop="lasetDate">
            <div class="item" style="margin-bottom: 30px">
              <span class="label">{{$t('Edb.Detail.e_latest_date')}}<!-- 最新日期 -->：{{ formData.lasetDate }}</span>
            </div>
          </el-form-item>
        </el-form>

        <!-- 规则 -->
        <el-collapse v-model="activeNames" class="rules-ul">
          <el-collapse-item
            v-for="(item, index) in rulesArr"
            :key="index"
            :name="index"
          >
            <template slot="title">
              <span class="text_oneLine"><!-- 时间段 -->{{$t('PredictEditPage.label_time_period')}}{{ index + 1 }}</span>
              <i
                class="el-icon-delete del-icon"
                @click.stop="removeRuleHandle(item, index)"
              />
            </template>
            <div class="wrap">
              <div class="item">
                <span class="label">{{$t('PredictEdbPage.predict_end_date')}}<!-- 预测截止日期 --></span>
                <el-date-picker
                  v-model="item.endDate"
                  type="date"
                  style="width: 100%"
                  value-format="yyyy-MM-dd"
                  :placeholder="$t('Edb.InputHolderAll.input_date')"
                  :picker-options="timePickerOptions"
                  @change="changeDateHandle($event,index)"
                >
                  <!-- :disabled="index!==0 && !rulesArr[index-1].endDate" -->
                </el-date-picker>
              </div>
              <div class="item">
                <span class="label">
                  <!-- 预测规则 -->{{$t('PredictEdbPage.predict_rule')}}
                  <el-tooltip effect="dark" placement="right">
                    <div
                      slot="content"
                      v-html="$t('PredictEditPage.rule_tip')"
                      style="line-height: 20px;max-width:600px;max-height:550px;overflow-y:auto"
                    ></div>
                    <i class="el-icon-question" style="color: #666" />
                  </el-tooltip>
                </span>
                <el-select
                  v-model="item.predict_type"
                  style="width: 100%"
                  @change="changePredictType($event,item,index)"
                >
                  <el-option
                    v-for="item in predictTypeSetting"
                    :key="item.key"
                    :label="item.label"
                    :value="item.key"
                    :disabled="formData.frequency==='年度'&&[5,6,11,12].includes(item.key)"
                  >
                  </el-option>
                </el-select>
              </div>
              <div class="item" v-if="![1,9,11,12,14,15].includes(item.predict_type)">
                <span class="label">{{labelMap[item.predict_type]}}</span>
                <el-input
                  v-model="item.fixedValue"
                  style="width: 100%"
                  :placeholder="$t('Edb.InputHolderAll.input_number')"
                  type="number"
                />
              </div>

              <!-- 季节性规则 -->
              <div v-if="[11,15].includes(item.predict_type)">
                <div class="item">
                  <span class="label"><!-- 选择方式 -->{{$t('PredictEditPage.season_select')}}</span>
                  <el-select
                    v-model="item.season_way"
                    placeholder="请选择方式"
                    style="width: 100%"
                    @change="item.n_value = '';item.season_years=[]"
                  >
                    <el-option :label="$t('PredictEditPage.season_select_cont')" :value="1"/>
                    <el-option :label="$t('PredictEditPage.season_select_formula')" :value="2"/>
                  </el-select>
                </div>
                <div class="item" v-if="item.season_way===1">
                  <span class="label"><!-- 年数 -->{{$t('PredictEditPage.label_years')}}</span>
                  <el-input
                    v-model="item.n_value"
                    style="width: 100%"
                    :placeholder="$t('Edb.InputHolderAll.input_number')"
                    type="number"
                  />
                </div>
                <div class="item" v-else>
                  <el-date-picker
                    v-model="select_year"
                    type="year"
                    value-format="yyyy"
                    placeholder="选择年份"
                    @change="pushYear($event,item)"
                  />
                  <div class="season-year-cont" v-if="item.season_years.length">
                    <el-tag
                      v-for="year in item.season_years"
                      :key="year"
                      style="margin: 5px;"
                      @close="removeYear(year,item)"
                      closable
                    >
                      {{year}}
                    </el-tag>
                  </div>
                </div>
                <div class="item" v-if="item.predict_type===11">
                  <el-radio-group v-model="item.season_type">
                    <el-radio label="公历"><!-- 公历 -->{{$t('PredictEditPage.option_season_calendar1')}}</el-radio>
                    <el-radio label="农历"><!-- 农历 -->{{$t('PredictEditPage.option_season_calendar2')}}</el-radio>
                  </el-radio-group>
                </div>
              </div>

              <!-- 移动平均同比 -->
              <div v-else-if="item.predict_type===12">
                <div class="item">
                  <span class="label"><!-- 期数 -->{{$t('PredictEditPage.label_periods')}}</span>
                  <el-input
                    v-model="item.n_value"
                    style="width: 100%"
                    :placeholder="$t('Edb.InputHolderAll.input_number')"
                    type="number"
                  />
                </div>
                <div class="item">
                  <span class="label"><!-- 同比年份 -->{{$t('PredictEditPage.label_yoy_year')}}</span>
                  <el-date-picker
                    v-model="item.move_average_year"
                    type="year"
                    value-format="yyyy"
                    :placeholder="$t('PredictEditPage.ph_yoy_year')"
                    @change="pushYear($event,item)"
                  />
                </div>

              </div>

              <!-- 一元线性拟合 -->
              <div v-else-if="item.predict_type===14">
                <div class="item">
                  <span class="label">
                    <!-- 自变量 -->{{$t('PredictEditPage.label_slef_var')}}
                    <el-radio-group v-model="edbFromType">
                      <el-radio :label="0" style="margin-right: 15px"><!-- ETA指标 -->{{$t('Edb.eta_name')}}</el-radio>
                      <el-radio :label="1"><!-- ETA预测指标 -->{{$t('Edb.eta_predictor_name')}}</el-radio>
                    </el-radio-group>
                  </span>
                  <el-select
                    v-model="item.self_target"
                    v-loadMore="searchLoad"
                    ref="searchRef"
                    :filterable="!item.self_target"
                    remote
                    clearable
                    :placeholder="$t('Edb.InputHolderAll.input_name_orid')"
                    style="width:88%;margin-top: 10px;display:inline-block"
                    :remote-method="searchHandle"
                    @click.native="inputFocusHandle($event,'self_target')"
                  >
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                    <el-option
                      v-for="item in searchOptions"
                      :key="item.EdbInfoId"
                      :label="currentLang==='en'?(item.EdbNameEn||item.EdbName):item.EdbName"
                      :value="item.EdbInfoId"
                      :disabled="!item.HaveOperaAuth"
                    >
                      <div>
                        <img 
                          :src="$icons.lock_ico2" 
                          width="18" 
                          height="18" 
                          style="vertical-align:middle" 
                          v-if="!item.HaveOperaAuth"
                        />
                        {{currentLang==='en'?(item.EdbNameEn||item.EdbName):item.EdbName}}
                      </div>
                    </el-option>
                  </el-select>
                  <i class="el-icon-tickets" style="color:#409EFF;font-size:18px" @click="toHistoryPage(item.self_target,$route.matched);lookEdbId=item.self_target;" v-if="item.self_target"/>
                </div>
                <div class="item">
                  <span class="label">
                    <!-- 领先天数 -->{{$t('PredictEditPage.label_lead_day')}}
                    <el-input
                      v-model="item.fixedValue"
                      style="width: 80px;margin:0 5px;"
                      type="number"
                      :step="1"
                      @keyup.native="filterCode(item)"
                    />{{$t('PredictEditPage.lead_day_unit')}}
                  </span>
                </div>
                <div class="item">
                  <span class="label"><!-- 拟合时间段 -->{{$t('PredictEditPage.lead_day_unit')}}</span>
                  <el-date-picker
                    v-model="item.fit_date[0]"
                    range-separator="至"
                    :placeholder="$t('PredictEditPage.ph_start_time')"
                    value-format="yyyy-MM-dd"
                    style="width: 90%;margin-bottom: 10px;"
                    @change="changeFitDate(item)"
                  />
                  <!-- 至 -->{{$t('Common.to')}}
                  <el-date-picker
                    v-model="item.fit_date[1]"
                    :placeholder="$t('PredictEditPage.ph_end_time')"
                    value-format="yyyy-MM-dd"
                    style="width: 90%"
                    @change="changeFitDate(item)"
                    :picker-options="{
                      shortcuts: [{
                        text: $t('PredictEditPage.tonow'),
                        onClick(picker) {
                          const date = new Date();
                          picker.$et('pick',date);
                        }
                      }]
                    }"
                  />
                </div>
              </div>

              <!-- 年度值倒退 -->
              <div v-else-if="item.predict_type===16">
                <div class="item">
                  <span class="label"><!-- 余额分配方式 -->{{$t('PredictEditPage.label_distru_way')}}</span>
                  <el-select
                    v-model="item.distribute_type"
                    placeholder="请选择方式"
                    style="width: 100%"
                    @change="item.on_year=''"
                  >
                    <el-option :label="$t('PredictEditPage.option_distru_way1')" :value="1"/>
                    <el-option :label="$t('PredictEditPage.option_distru_way2')" :value="2"/>
                  </el-select>
                </div>
                <div class="item" v-if="item.distribute_type===2">
                  <span class="label"><!-- 同比年份 -->{{$t('PredictEditPage.label_yoy_year')}}</span>
                  <el-date-picker
                    v-model="item.on_year"
                    type="year"
                    value-format="yyyy"
                    :placeholder="$t('PredictEditPage.ph_yoy_year')"
                  />
                </div>
              </div>


              <el-button type="text" v-if="item.predict_type===9" @click="setRingAddHandle(item,index)"><!-- 设置环比增加值 -->{{$t('PredictEditPage.set_mom_btn')}}</el-button>
            </div>
          </el-collapse-item>
        </el-collapse>
        <div class="rules-add" @click="addRuleHandle">
          <img
            src="~@/assets/img/set_m/add_ico.png"
            alt=""
            style="width: 16px; height: 16px; margin-right: 10px"
          />
          <span><!-- 添加更多 -->{{$t('PredictEditPage.add_more_btn')}}</span>
        </div>
      </div>
    </div>
    <div class="main-wrap" id="right">
      <div class="con-box" v-show="edbData.DataList">
        <div class="top-title">{{ formData.edbName }}</div>
        <div class="chart-wrap">
            <chartInfo
                :edbData="edbData"
                :isAllowEditLimit="true"
                @refreshData="refreshData"
                ref="chartInfo"
                />
        </div>
        
      </div>
      <div class="empty-box" v-show="!edbData.DataList">
        <tableNoData :text="$t('Common.no_info_msg')"/>
      </div>
    </div>
    <span
        class="slide-icon slide-btn-icon"
        :class="{'slide-left':isAsideShow,'slide-right':!isAsideShow}"
        @click="isAsideShow = !isAsideShow"
    >
        <i :class="{'el-icon-d-arrow-left':isAsideShow,'el-icon-d-arrow-right':!isAsideShow}"></i>
    </span>

    <!-- 设置动态环差弹窗 -->
    <dynamic-differ
      :isOpenDialog.sync="isOpenDialog"
      :edbList="dynamicDifferList"
      :info="dynamicDifferInfo"
      @ensureBack="saveDynamicDifferRule"
      @lookHistory="id => {toHistoryPage(id,$route.matched);lookEdbId=id;}"
    />

    <!-- 指标历史记录 -->
    <!-- <edbHistoryDialog
      :isOpenDialog.sync="isLookHistory"
      :edbId="lookEdbId"
    /> -->
    
  </div>
</template>

<script>
import * as preDictEdbInterface from "@/api/modules/predictEdbApi.js";
import { dataBaseInterface } from "@/api/api.js";
import chartInfo from "./components/chartInfo.vue";
import dynamicDiffer from './components/dynamicRingdiffer.vue';
export default {
  components: { chartInfo,dynamicDiffer },
  computed: {
    // 图需要更新的依赖项
    showChart() {
      return {
        oldEdb: this.formData.oldEdb,
      };
    },
    timePickerOptions() {
      let that=this
      let obj={
        disabledDate(time) {
          if(that.formData.lasetDate){
            return time.getTime() < new Date(that.formData.lasetDate).getTime()
          }else{
            return time.getTime() < Date.now()
          }
        }
      }
      return obj
    },
    predictTypeSetting(){
        return [
        { key: 1, label: /* "最新" */this.$t('PredictEditPage.rule_newset') },
        { key: 2, label: /* "固定值" */this.$t('PredictEditPage.rule_fix') },
        { key: 3, label: /* "同比" */this.$t('PredictEditPage.rule_onyear') },
        { key: 4, label: /* "同差" */this.$t('PredictEditPage.rule_differ') },
        { key: 5, label: /* "环比" */this.$t('PredictEditPage.rule_mom') },
        { key: 6, label: /* "环差" */this.$t('PredictEditPage.rule_mom_differ') },
        { key: 7, label: /* "N期移动均值" */this.$t('PredictEditPage.rule_move_average') },
        { key: 8, label: /* "N期段线性外推值" */this.$t('PredictEditPage.rule_linear') },
        { key: 9, label: /* '动态环差' */this.$t('PredictEditPage.rule_dynamic_differ') },
        { key: 10, label: /* "给定终值后插值" */this.$t('PredictEditPage.rule_inter_end') },
        { key: 11, label: /* "季节性" */this.$t('PredictEditPage.rule_season') },
        { key: 12, label: /* "移动平均同比" */this.$t('PredictEditPage.rule_yoy_move') },
        { key: 13, label: /* "同比增速插值" */this.$t('PredictEditPage.rule_yoy_growth') },
        { key: 14, label: /* "一元线性拟合" */this.$t('PredictEditPage.rule_linear_reg') },
        { key: 15, label: /* "N年均值" */this.$t('PredictEditPage.rule_n_year') },
        { key: 16, label: /* "年度值倒推" */this.$t('PredictEditPage.rule_value_back') },
      ]
    },
    labelMap(){
        return {
            2: /* '固定值' */this.$t('PredictEditPage.rule_fix'),
            3: /* '同比增速' */this.$t('PredictEditPage.label_value_yoy_growth'),
            4: /* '同比增加值' */this.$t('PredictEditPage.label_value_yoy_add'),
            5: /* '环比增速' */this.$t('PredictEditPage.label_value_mom_growth'),
            6: /* '环比增加值' */this.$t('PredictEditPage.label_value_mom_add'),
            7: /* '期数' */this.$t('PredictEditPage.label_periods'),
            8: /* '期数' */this.$t('PredictEditPage.label_periods'),
            10: /* '预测终值' */this.$t('PredictEditPage.label_periods'),
            11: /* '期数' */this.$t('PredictEditPage.label_periods'),
            12: /* '期数' */this.$t('PredictEditPage.label_periods'),
            13: /* '同比增速终值' */this.$t('PredictEditPage.label_value_yoy_end'),
            16: /* '年度值' */this.$t('PredictEditPage.label_value_year')
        }
    },

    currentLang() {
			return this.$store.state.lang
		}
  },
  watch: {
    showChart(n, o) {
      if (n.oldEdb) {
        console.log("更新");
        if (n.oldEdb != o.oldEdb) {
          this.$refs.chartInfo.chartInfo.ChartType = 1;
        }
        //this.getChartInfo();
      }
    },
    rulesArr: {
      handler(newval) {
        this.isNeedWatch && this.formData.oldEdb && this.getChartInfo();
      },
      deep: true
    }
  },
  data() {
    return {
      formData: {
        edb_id: "",
        classify: "",
        oldEdb: "",
        edbName: "",
        frequency: "",
        newdata: "",
        lasetDate: "",
        dateType: '交易日',
      },
      formRules: {
        classify: [
          { required: true, message: /* "分类不能为空" */this.$t('Edb.Valids.classify_msg'), trigger: "blur" },
        ],
        oldEdb: [{ required: true, message: /* "指标不能为空" */this.$t('Edb.Valids.no_edb'), trigger: "blur" }],
        edbName: [
          { required: true, message: /* "指标名称不能为空" */this.$t('Edb.Valids.name_msg'), trigger: "blur" },
        ],
      },
      classifyArr: [],
      /* predictTypeOptions:[], */
      /* rulesTip: this.$t('PredictEditPage.rule_tip'), */
      rulesArr: [{ 
        endDate: "",
        predict_type: 1,
        fixedValue: "",
        edbarr:[],
        season_way: 1,
        season_years: [],
        season_type: '公历',
        n_value:'',
        move_average_year: '',
        self_target: '',
        fit_date:['',this.$moment().format('YYYY-MM-DD')],
        distribute_type: 1,
        on_year: ''
      }],
      activeNames: [0],

      searchOptions: [],
      search_page: 1,
      search_have_more: false,
      current_search: "",

      edbData: {
        DataList: null,
        EdbInfo: {},
      },

      DateType: 10, //年份选择项 默认全部

      isNeedWatch: true,

      /* 动态环差弹窗 */
      isOpenDialog: false,
      dynamicDifferList: [],//依赖指标
      dynamicDifferInfo: '',
      click_rule_index: -1,
      
      select_year: '',

      edbFromType: 0,//标准指标

      /* 查看历史弹窗 */
			isLookHistory: false,
			lookEdbId: 0,
      
      isAsideShow:true,
    };
  },
  created() {
    if (this.$route.path == "/editpredictEdb") {
      this.formData.edb_id = Number(this.$route.query.id);
      this.getEditInitData();
    }
    this.getClassifyOne();
    this.setRulesArr()
  },
  methods: {
    // 获取详情
    getEditInitData() {
      this.isNeedWatch = false; //控制编辑进来调用多次watch

      preDictEdbInterface
        .edbDetail({
          EdbInfoId: this.formData.edb_id,
        })
        .then((res) => {
          if (res.Ret !== 200) return;
          const {
            ClassifyId,
            ClassifyList,
            EdbName,
            EdbNameEn,
            Frequency,
            LatestValue,
            RuleList,
            EdbInfoId,
            LatestDate,
            DataDateType
          } = res.Data;
          const classifyArr = ClassifyList.length&&ClassifyList.map(item=>item.ClassifyId).reverse()
          this.formData = {
            edb_id: EdbInfoId,
            classify: classifyArr||[],
            oldEdb: res.Data.CalculateList[0].FromEdbInfoId,
            oldEdbName: res.Data.CalculateList[0].FromEdbName,
            edbName: this.currentLang==='en'?EdbNameEn:EdbName,
            frequency: Frequency,
            newdata:  res.Data.CalculateList[0].EndValue,
            lasetDate: res.Data.CalculateList[0].EndDate,
            dateType: DataDateType
          };

          this.rulesArr = RuleList.map(_ => ({
            endDate: this.$moment(_.EndDate).format('YYYY-MM-DD'),
            predict_type: _.RuleType,
            fixedValue: _.RuleType === 14 
              ? JSON.parse(_.Value).MoveDay
              : _.RuleType === 16
              ? JSON.parse(_.Value).Value
              : _.Value,
            edbarr: _.RuleType === 9 
              ? _.CalculateList.map(item => ({ target:item.FromEdbInfoId,tag:item.FromTag,name:item.FromEdbName,start_date: item.StartDate,end_date:item.EndDate })) 
              : [],
            season_way:[11,15].includes(_.RuleType) ? JSON.parse(_.Value).YearType : '',
            season_years: [11,15].includes(_.RuleType) ? JSON.parse(_.Value).YearList.map(_ =>_.toString()) : [],
            season_type: _.RuleType === 11 ? JSON.parse(_.Value).Calendar : '',
            n_value: [11,12,15].includes(_.RuleType) ? JSON.parse(_.Value).NValue : '',
            move_average_year: _.RuleType === 12 ? JSON.parse(_.Value).Year.toString() : '',
            self_target: _.RuleType === 14 ? JSON.parse(_.Value).EdbInfoId : '',
            fit_date: _.RuleType === 14 ? [JSON.parse(_.Value).StartDate,JSON.parse(_.Value).EndDate] : [],
            distribute_type: _.RuleType === 16?JSON.parse(_.Value).Type:1,
            on_year: _.RuleType === 16?JSON.parse(_.Value).Year.toString():'',
            nullValueWay: _.EmptyType,
            maxNullWay: _.MaxEmptyType
          }))

          this.searchOptions = RuleList.map(item => ({
            EdbInfoId: item.CalculateList[0] ? item.CalculateList[0].FromEdbInfoId : '',
            EdbName: item.CalculateList[0] ? item.CalculateList[0].FromEdbName : ''
          }));

          this.edbData.EdbInfo = {
            ...res.Data,
            ChartColor: "",
            ChartStyle: "",
            ChartType: 0,
            ChartWidth: 0,
            MaxData: res.Data.MaxValue,
            MinData: res.Data.MinValue,
            EdbInfoCategoryType: 1,
            EdbInfoType: 1,
            EdbName: this.formData.edbName,
            IsAxis: 1,
          };
        });
    },
    // 递归改变目录结构
		filterNodes(arr) {
			arr.length &&
				arr.forEach((item) => {
					item.Children.length && this.filterNodes(item.Children);
					if (!item.Children.length) {
						delete item.Children;
					}
				});
		},
    getClassifyOne() {
      preDictEdbInterface.classifyListV2().then((res) => {
        if (res.Ret !== 200) return;
        this.filterNodes(res.Data.AllNodes || [])
        this.classifyArr = res.Data.AllNodes || [];

        // if (this.$route.path == "/editpredictEdb") {
        //   //将formData.classify转为数组的格式
        //   this.formData.classify = this.findParentNodeHandle(this.classifyArr,this.formData.classify).reverse()
        // } 

      });
    },
    findParentNodeHandle(arr, id) {
      // 遍历取父级code push数组
      for (let i of arr) {
        if (i.ClassifyId === id) {
          return [i.ClassifyId];
        }
        if (i.Children) {
          let node = this.findParentNodeHandle(i.Children, id);
          if (node) {
            return node.concat(i.ClassifyId);
          }
        }
      }
    },

    searchLoad() {
      if (!this.search_have_more) return;
      this.searchApi(this.current_search, ++this.search_page);
    },

    async searchApi(query, page = 1) {
      let params = {
        KeyWord: query,
        CurrentIndex: page,
      }

      const res = (this.edbFromType === 1 && this.current_type==='self_target')
				? await preDictEdbInterface.edbSearch(params)
				: await dataBaseInterface.targetSearchByPage(params)

      if (res.Ret !== 200) return;

      const { List, Paging } = res.Data;
      this.search_have_more = page < Paging.Pages;
      this.searchOptions = page === 1 ? List : this.searchOptions.concat(List);
    },

    /* 聚焦获取当前检索 */
    inputFocusHandle(e,type='') {
      this.search_page = 1;
      this.current_search = e.target.value;
      this.current_type = type;
      this.searchApi(this.current_search);
    },

    /* 选择指标  同步名称频度最新值*/
    async selectEdbHandle(val) {
      if (val) {
        const { Data } = await dataBaseInterface.targetDetail({
          EdbInfoId: val,
        });
        this.formData.edbName = `${this.currentLang==='en'?Data.EdbNameEn:Data.EdbName}(预测)`;
        this.formData.frequency = Data.Frequency;
        this.formData.newdata = Data.LatestValue;
        this.formData.lasetDate = Data.LatestDate;
        this.edbData.EdbInfo = {
          ...Data,
          ChartColor: "",
          ChartStyle: "",
          ChartType: 0,
          ChartWidth: 0,
          // MaxData: Data.MaxValue,
          // MinData: Data.MinValue,
          EdbInfoCategoryType: 1,
          EdbInfoType: 1,
          EdbName: this.formData.edbName,
          IsAxis: 1
        };
        this.setRulesArr()
        this.getChartInfo()
      } else {
        this.formData.edbName = "";
        this.formData.frequency = "";
        this.formData.newdata = "";
        this.formData.lasetDate = "";
      }
    },

    /* 搜索 */
    searchHandle(query) {
      this.search_page = 1;
      this.current_search = query;
      this.searchApi(this.current_search);
    },

    // 获取图表数据
    async getChartInfo() {
      console.log(this.rulesArr)
      let rules_params = this.rulesArr.filter(_ => (
          (_.predict_type === 1 && _.endDate)
          || [11,12,15].includes(_.predict_type) && _.endDate && (_.n_value||_.season_years.length)
          || (_.predict_type===14 &&_.endDate &&  _.fit_date[0] && _.fit_date[1] && _.self_target)
          || ![1,11,12,14,15].includes(_.predict_type) && _.endDate && _.fixedValue
        )).map(_ =>{

          let dynamic_params = {};
          switch(_.predict_type) {
            case 11: 
            case 15:
              dynamic_params = {
                Calendar:  _.season_type,
                YearType: _.season_way,
                NValue: Number(_.n_value),
                YearList: _.season_years.map(_ =>Number(_)),
              }
              break
            case 12:
              dynamic_params = {
                Year: Number(_.move_average_year),
                NValue: Number(_.n_value)
              }
              break
            case 14: 
              dynamic_params = {
                StartDate: _.fit_date[0],
                EndDate: _.fit_date[1],
                MoveDay: Number(_.fixedValue),
                EdbInfoId: _.self_target
              }
              break
            case 16: 
              dynamic_params = {
                Type: _.distribute_type,
                Value: Number(_.fixedValue),
                Year:  Number(_.on_year)
              }
              break
          }  

          return {
            RuleType: _.predict_type,
            EndDate: _.endDate,
            Value: [11,12,14,15,16].includes(_.predict_type) ? JSON.stringify(dynamic_params) : _.fixedValue,
            EdbInfoIdArr: _.predict_type === 9 
              ? _.edbarr.map(item => ({ EdbInfoId:item.target,FromTag:item.tag })) 
              : _.predict_type === 14
              ? [{EdbInfoId: _.self_target,FromTag: ''}]
              :[],
            EmptyType: _.predict_type===9 ? _.nullValueWay : 0,
            MaxEmptyType: _.predict_type===9 ? _.maxNullWay : 0
          }
        })

      let dateArray=[]
      let DateType,StartYear;
      
      if(this.$refs.chartInfo.chartInfo.ChartType==2){
          DateType=this.$refs.chartInfo.year_select_season
          StartYear=this.$refs.chartInfo.count_year_season
          if(!(this.$refs.chartInfo.season_year && this.$refs.chartInfo.season_year.length>0)){
              // 初始化日期显示
              let latestYear = parseInt(this.$refs.chartInfo.tableData[0].LatestDate.substring(0,4))
              this.$refs.chartInfo.season_year = [`${latestYear-StartYear+1}-01-01`,`${latestYear}-12-31`];
          }
          dateArray = this.$refs.chartInfo.season_year
      }else{
          DateType=this.$refs.chartInfo.year_select
          StartYear=this.$refs.chartInfo.count_year
          dateArray = this.$refs.chartInfo.select_date
      }
      
      let params = {
        SourceEdbInfoId: this.formData.oldEdb,
        DateType,
        StartDate: dateArray[0] || "",
        EndDate: dateArray[1] || "",
        Calendar: this.$refs.chartInfo.calendar_type,
        ChartType: this.$refs.chartInfo.chartInfo.ChartType,
        // ETA1.0.5 去除了这两个参数
        // SeasonStartDate: this.$refs.chartInfo.season_year[0] || "",
        // SeasonEndDate: this.$refs.chartInfo.season_year[1] || "",
        DataDateType: this.formData.dateType,
        StartYear:StartYear || 0
      }

      const res = await preDictEdbInterface.edbChartDataForAdd(rules_params.length ? {...params,RuleList: rules_params} : params);
      if (res.Ret != 200) return;
      this.edbData.DataList = res.Data.DataList;
      this.edbData.EdbInfo.MaxData = this.edbData.EdbInfo.MaxData || res.Data.MaxValue;
      this.edbData.EdbInfo.MinData = this.edbData.EdbInfo.MinData || res.Data.MinValue;

      this.isNeedWatch = true; //控制编辑进来调用多次watch
    },

    /* 保存 */
    async saveHandle() {
      
      await this.$refs.formRef.validate();
      // 规则填写是否完整
      let isRulesComplete = this.rulesArr.every(item => {
        return item.predict_type === 1 && item.endDate
          || [11,12,15].includes(item.predict_type) && item.endDate && (item.n_value||item.season_years.length)
          || (item.predict_type===14 && item.endDate && item.fit_date[0] && item.fit_date[1] && item.self_target)
          || ![1,11,12,14,15].includes(item.predict_type) && item.endDate && item.fixedValue
      })
      if(!isRulesComplete) return this.$message.warning(/* '请填写完整的规则' */this.$t('PredictEditPage.vaild_full_rule'))
      
      const { edb_id,classify,oldEdb,edbName,dateType } = this.formData;

      //规则参数
      let RuleList = this.rulesArr.map(_ => {
        let dynamic_params = {};
        switch(_.predict_type) {
          case 11: 
          case 15: 
            dynamic_params = {
              Calendar:  _.season_type,
              YearType: _.season_way,
              NValue: Number(_.n_value),
              YearList: _.season_years.map(_ =>Number(_)),
            }
            break
          case 12:
            dynamic_params = {
                Year: Number(_.move_average_year),
              NValue: Number(_.n_value)
            }
            break
          case 14: 
            dynamic_params = {
              StartDate: _.fit_date[0],
              EndDate: _.fit_date[1],
              MoveDay: Number(_.fixedValue),
              EdbInfoId: _.self_target
            }
            break
          case 16: 
              dynamic_params = {
                Type: _.distribute_type,
                Value: Number(_.fixedValue),
                Year:  Number(_.on_year)
              }
              break
        }

        return {
          RuleType: _.predict_type,
          EndDate: _.endDate,
          Value: [11,12,14,15,16].includes(_.predict_type) ? JSON.stringify(dynamic_params) : _.fixedValue,
          EdbInfoIdArr: _.predict_type === 9 
            ? _.edbarr.map(item => ({ EdbInfoId:item.target,FromTag:item.tag })) 
            : _.predict_type === 14
            ? [{EdbInfoId: _.self_target,FromTag: ''}]
            :[],
          EmptyType: _.predict_type===9 ? _.nullValueWay : 0,
          MaxEmptyType: _.predict_type===9 ? _.maxNullWay : 0
        }
      })
      let params = {
        ClassifyId: classify[classify.length-1],
        EdbName: edbName,
        MaxValue: Number(this.$refs.chartInfo.tableData[0].MaxData),
				MinValue: Number(this.$refs.chartInfo.tableData[0].MinData),
        DataDateType: dateType,
        RuleList
      };

      const { Ret, Data } = edb_id
        ? await preDictEdbInterface.edbEdit({ ...params, EdbInfoId: edb_id })
        : await preDictEdbInterface.edbAdd({
            ...params,
            SourceEdbInfoId: oldEdb,
          });

      if (Ret !== 200) return;

      // this.$message.success("保存成功");
      this.$message.success(this.$t('MsgPrompt.saved_msg'));
      //编辑的话更新图
      edb_id && this.$nextTick(() => {
        this.setChartImage();
      });

      if (!edb_id) {
        const obj = {
          code: Data.UniqueCode,
          id: Data.EdbInfoId,
        };
        sessionStorage.setItem("predictEdbTreeData", JSON.stringify(obj));
      }

      setTimeout(() => {
        this.$router.back();
      }, 1500);
    },

    /* 关联图片 */
    setChartImage() {
      let svg = this.$refs.chartInfo.$refs.chartRef.chart.getSVG({
        chart: {
          width: 340,
          height: 230,
        },
      });
      let form = new FormData();
      form.append("Img", svg);
      this.setImageHandle(form);
    },

    async setImageHandle(form) {
      // let { Data } = await dataBaseInterface.uploadImgSvg(form);
      // await preDictEdbInterface.setImg({
      //   EdbInfoId: this.formData.edb_id,
      //   ImageUrl: Data.ResourceUrl,
      // });
      form.append("EdbInfoId", this.formData.edb_id);
      await preDictEdbInterface.setThumbnail(form)
    },

    refreshData() {
      this.getChartInfo();
    },

    /* 添加新规则 */
    addRuleHandle() {
      const newItem = {
        endDate: "",
				predict_type: 1,
        fixedValue: "",
        edbarr: [],
        season_way: 1,
        season_years: [],
        season_type: '公历',
        n_value: '',
        move_average_year: '',
        self_target: '',
        fit_date:['',this.$moment().format('YYYY-MM-DD')],
        distribute_type: 1
      };

      this.rulesArr.push(newItem);
    },

    /* 切换预测规则 重置value */
    initRule(e,item) {
      item.fixedValue = '';
      item.edbarr=[];
      item.season_way=1;
      item.season_years=[];
      item.season_type='公历';
      item.n_value='';
      item.move_average_year='';
      item.self_target = '';
      item.fit_date = ['',this.$moment().format('YYYY-MM-DD')];
      item.distribute_type=1;
    },

    /* 设置预测规则数组 */
    setRulesArr(){
      const {frequency} = this.formData
      let filterKey=[]
      //如果是年度，则不显示环比、环差、动态环差、季节性、移动平均同比的选项
      if(frequency==='年度'){
        filterKey = [5,6,11,12]
      }
      //this.predictTypeOptions = this.predictTypeSetting.filter(item=>{return !filterKey.includes(item.key)})
     /*  this.predictTypeOptions = this.predictTypeSetting */
      //年度指标时，将不支持的规则类型重置
      this.isNeedWatch = false
      this.rulesArr.forEach(item=>{
        if(filterKey.length&&filterKey.includes(item.predict_type)){
          this.initRule(_,item)
          item.predict_type = 1
        }
      })
      this.$nextTick(()=>{
        this.isNeedWatch=true
      })
    },

    /* 删除规则 */
    removeRuleHandle(item, index) {
      if(this.rulesArr.length===1) return this.$message.warning(/* '请至少保留一条预测规则' */this.$t('PredictEditPage.vaild_last_rule'));
      this.rulesArr.splice(index, 1);
      // this.$message.success("删除成功");
      this.$message.success(this.$t('MsgPrompt.delete_msg'));
    },

    /* 选择日期时提示不能小于上个日期 */
    changeDateHandle(value,index) {
      console.log(value,index)
      let isDateRepeat = this.rulesArr.some((_,_index) => _index!==index&&this.$moment(_.endDate).valueOf()===this.$moment(value).valueOf())
      if(isDateRepeat) {
          this.rulesArr[index].endDate = '';
          return this.$message.warning('所选日期不能和其他规则重复')
          
      }
      // if(index > 0) {
      //   let prev_date = this.rulesArr[index-1].endDate;
      //   if(this.$moment(prev_date).valueOf() >= this.$moment(value).valueOf()){
      //     this.$message.warning('所选日期不能小于上个规则的日期')
      //     this.rulesArr[index].endDate = '';
      //   }
      // }
      this.rulesArr[index].predict_type===16 && this.rulesArr[index].endDate && this.checkReverseYearDate(index)
    },

    // n年倒推 校验日期时同一年份
    checkReverseYearDate(index) {
      let selectDateYear = new Date(this.rulesArr[index].endDate).getFullYear();
      let prevRuleDateYear = '';
      if(this.rulesArr.length === 1) {
        prevRuleDateYear = new Date(this.formData.lasetDate).getFullYear();
      } else {
        let sortRuleArr = [...this.rulesArr].sort((x,y) => new Date(x.endDate)-new Date(y.endDate));
        let newIndex = sortRuleArr.findIndex(_ => _.endDate===this.rulesArr[index].endDate);
        prevRuleDateYear = newIndex === 0 ? new Date(this.formData.lasetDate).getFullYear() : new Date(sortRuleArr[newIndex-1].endDate).getFullYear()
      }
      
      if(selectDateYear !== prevRuleDateYear) {
        this.rulesArr[index].endDate = ''
        return this.$message.warning('年度值倒推不支持跨年预测')
      } 
      
    },

    changePredictType(e,item,index) {
      e===16&&item.endDate&&this.checkReverseYearDate(index); 
      this.initRule(e,item)
    },

    /* 拟合选择日期 */
    changeFitDate(item) {
			if(item.fit_date[0] && item.fit_date[1]) {
				let differ = this.$moment(item.fit_date[1]).diff(
					this.$moment(item.fit_date[0]),
					'days',
					true
				)
				if(differ < 2) {
					item.fit_date = [];
					this.$message.warning(`${differ<0?'开始日期不能晚于结束日期':'日期间隔不得少于两天'}`)
				}
			}
    },

    /* 设置环比增加值 */
    setRingAddHandle({edbarr,fixedValue,nullValueWay,maxNullWay},index) {
      this.click_rule_index = index;
      this.dynamicDifferList = edbarr;
      this.dynamicDifferInfo =  {
        formulaList: fixedValue,
        nullValueWay,
        maxNullWay
      };
      this.isOpenDialog = true;
    },
    

    /* 规则动态环差信息 */
    saveDynamicDifferRule({arr,formula,nullValueWay,maxNullWay}) {
      this.rulesArr[this.click_rule_index].edbarr = arr;
      this.rulesArr[this.click_rule_index].fixedValue = formula;
      this.rulesArr[this.click_rule_index].nullValueWay = nullValueWay;
      this.rulesArr[this.click_rule_index].maxNullWay = maxNullWay;
      console.log(this.rulesArr)
    },

    /* 追加年份 */
    pushYear(e,item) {
      this.select_year = '';
      if(item.season_years.includes(e)) return this.$message.warning('年份已存在')

      item.season_years.push(e)
    },

    /* 删除年份 */
    removeYear(year,item) {
      item.season_years.splice(item.season_years.findIndex(_ => _===year),1)
    },

    /*小数点*/
    filterCode(item) {
      item.fixedValue=item.fixedValue.replace('.','');
    },
  },
};
</script>

<style lang="scss">
.add-predicedb-page {
    overflow-y: auto;
  .aside-warp {
    /* .el-form-item {
      margin-bottom: 0;
    } */
    .el-form-item__content {
      line-height: 1;
    }
  }
  .el-collapse-item__header {
    background-color: #F0F2F5;
    margin-bottom: 0;
    border-bottom: 1px solid #dcdfe6;
    padding: 0 30px;
    .el-collapse-item__arrow {
      position: absolute;
      left: 8px;
    }
  }
  .el-collapse-item__content {
    padding-bottom: 10px;
  }
  .el-collapse-item.is-disabled .el-collapse-item__header {
    color: #333;
  }
}
</style>

<style lang="scss" scoped>
div {
  box-sizing: border-box;
}
.add-predicedb-page {
  display: flex;
  min-height: calc(100vh - 150px);
  position: relative;
  .aside-warp {
    flex-shrink: 0;
    width: 300px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #ececec;
    margin-right: 20px;
    .btn-box {
      height: 80px;
      background: #ffffff;
      box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.06);
      border-radius: 4px 4px 0px 0px;
      opacity: 1;
      border-bottom: 1px solid #ececec;
      padding-top: 20px;
      padding-left: 15px;
    }
    .con {
      padding: 20px;
      max-height: calc(100vh - 200px);
      overflow-y: auto;
      .item {
        margin-bottom: 20px;
        font-size: 14px;
        .label {
          margin-bottom: 10px;
          display: block;
        }
        .season-year-cont {
          padding: 10px;
          margin-top: 15px;
          border: 1px dashed #AAB4CC;
        }
      }
      .tip-wrap {
        color: #999;
        margin-top: 30px;
      }
    }
  }
  .main-wrap {
    flex: 1;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #ececec;
    overflow-x: auto;
  }

  .slide-icon{
    position: absolute;
    &.slide-left {
        left: 290px;
    }
    &.slide-right {
        left: 0px;
    }
  }
  .rules-ul {
    border: 1px solid #dcdfe6;
    .del-icon {
      position: absolute;
      right: 10px;
      font-size: 16px;
      color: #f00;
      cursor: pointer;
    }
    .wrap {
      padding: 20px 20px 0;
      li {
        padding-bottom: 20px;
        margin-bottom: 20px;
        border-bottom: 1px solid #dcdfe6;
        &:last-child {
          padding-bottom: 0;
          margin-bottom: 0;
          border-bottom: none;
        }
      }
    }
  }
  .rules-add {
    margin-top: 10px;
    display: flex;
    align-items: center;
    color: #409eff;
    color: pointer;
  }
}
.main-wrap {
  .empty-box {
    padding-top: 200px;
    color: #aab4cc;
    text-align: center;
    img {
      width: 150px;
    }
  }
  .con-box {
    .top-title {
      height: 80px;
      background: #ffffff;
      box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.06);
      border-radius: 4px 4px 0px 0px;
      border-bottom: 1px solid #ececec;
      font-size: 18px;
      display: flex;
      padding-left: 30px;
      align-items: center;
    }
    .chart-wrap{
        box-sizing: border-box;
        padding:30px;
    }
  }
}
</style>
