<template>
    <div v-dialogDrag v-if="isShow">
      <div class="calculate-edb-value-dialog el-dialog">
        <div class="header el-dialog__header">
          <span>{{ calculationItem.label }}</span>
          <i class="el-icon-close" @click="cancelHandle" />
        </div>
  
        <div class="main">
          <section class="main-top">
            <template v-if="calculationItem.fromEdbKey === 5">
              <el-radio-group
                v-model="formData.source"
                @change="handleRadioGroup"
              >
                <el-radio :label="1">{{
                  $t("Edb.CalculateBtns.to_month")
                }}</el-radio>
                <el-radio :label="2">{{
                  $t("Edb.CalculateBtns.to_quarter")
                }}</el-radio>
              </el-radio-group>
            </template>
  
            <template v-else-if="calculationItem.fromEdbKey === 62">
              <el-radio-group
                v-model="formData.source"
                @change="handleRadioGroup"
              >
                <el-radio :label="13">{{
                  $t("Edb.CalculateBtns.cumulate")
                }}</el-radio>
                <el-radio :label="14">{{
                  $t("Edb.CalculateBtns.cumulate_oneyear")
                }}</el-radio>
              </el-radio-group>
            </template>
  
            <selectTarget
              :defaultId="search_edb"
              :defaultOpt="searchOptions"
              ref="selectRef"
              @select="selectTargetHandle"
              :filter="false"
              style="margin: 20px 0"
            />
  
            <div class="link-box-tags">
              <div
                class="link-box-tag"
                v-for="(item, index) in edbList"
                :key="item.RId"
                :class="{
                  'unchoose-tag': item.Id != edbActive.Id,
                  'choosed-tag': item.Id == edbActive.Id,
                }"
              >
                <span
                  @dblclick.stop="editLinkName(item)"
                  v-if="!item.editing"
                  @click="linkClick(item)"
                  :style="{
                    color: item.Id == edbActive.Id ? '#0052D9' : '#666666',
                  }"
                  >{{ item.Name }}</span
                >
                <el-input
                  v-else
                  @blur="editLinkNameFinish(item)"
                  v-model.trim="editingLabel"
                  class="label-edit-input"
                  ref="labelEditInput"
                />
                <img
                  src="~@/assets/img/sand_new/delete_outline_1.png"
                  @click="linkDelete(item, index)"
                />
              </div>
            </div>
          </section>
          <!-- 指标详情 -->
          <edbDetailSection :tableData="selectEdbInfo ? [selectEdbInfo] : []" />
  
          <section class="form-section">
            <el-form
              ref="form"
              label-position="left"
              inline
              label-width="80px"
              :model="formData"
              :rules="formRules"
            >
              <el-form-item
                :label="$t('OnlineExcelPage.label_move_way')"
                style="display: block"
                v-if="calculationItem.fromEdbKey === 22"
                prop="moveVal"
              >
                <el-select
                  v-model="formData.moveType"
                  style="width: 100px"
                  placeholder=""
                  size="mini"
                >
                  <el-option
                    v-for="item in moveTypeOpions"
                    :key="item.key"
                    :label="item.label"
                    :value="item.key"
                  >
                  </el-option>
                </el-select>
                <el-input
                  style="width: 80px"
                  type="number"
                  min="0"
                  size="mini"
                  v-model="formData.moveVal"
                  @keyup.native="filterCode(formData)"
                ></el-input>
                <el-select
                  v-model="formData.moveUnit"
                  size="mini"
                  placeholder=""
                  style="width: 100px"
                >
                  <el-option
                    v-for="item in fre_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
  
              <el-form-item
                :label="$t('OnlineExcelPage.label_n_val')"
                prop="nNum"
                v-if="[8, 12, 13, 35].includes(calculationItem.fromEdbKey)"
              >
                <el-input
                  v-model="formData.nNum"
                  style="width: 200px"
                  :placeholder="$t('ETableChildren.enter_n_value')"
                  type="number"
                />
              </el-form-item>
  
              <el-form-item
                :label="$t('OnlineExcelPage.label_calendar')"
                prop="calendarType"
                v-if="calculationItem.fromEdbKey === 35"
              >
                <el-select
                  v-model="formData.calendarType"
                  :placeholder="$t('OnlineExcelPage.select_calendar_pld')"
                  style="width: 200px"
                >
                  <el-option
                    v-for="item in calendarOptions"
                    :key="item.key"
                    :label="item.label"
                    :value="item.key"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
  
              <el-form-item
                :label="$t('ETableChildren.frequentness_lable')"
                prop="frequency"
                v-if="[9, 13].includes(formData.source)"
              >
                <el-select
                  v-model="formData.frequency"
                  :placeholder="$t('OnlineExcelPage.please_select_frequency')"
                  style="width: 200px"
                  clearable
                >
                  <el-option
                    v-for="item in frequencyArr"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
  
              <el-form-item
                :label="$t('OnlineExcelPage.label_val_type')"
                prop="valueType"
                v-if="calculationItem.fromEdbKey === 51"
              >
                <el-select
                  v-model="formData.valueType"
                  :placeholder="$t('OnlineExcelPage.select_data_type')"
                  style="width: 200px"
                >
                  <el-option
                    key="期末值"
                    :label="$t('ETableChildren.final_value_lable')"
                    value="期末值"
                  />
                  <el-option
                    key="平均值"
                    :label="$t('ETableChildren.average_value_lable')"
                    value="平均值"
                  />
                </el-select>
              </el-form-item>
  
              <el-form-item
                :label="$t('ETableChildren.alpha_value_lable')"
                prop="alphaValue"
                v-if="calculationItem.fromEdbKey === 'alpha'"
              >
                <el-input
                  v-model="formData.alphaValue"
                  :placeholder="$t('Edb.InputHolderAll.input_alpha_val')"
                  style="width: 200px"
                />
              </el-form-item>
            </el-form>
          </section>
  
          <section>
            <!-- 依赖日期选择方式 -->
            <ul class="date-select-cont">
              <li class="flex">
                <div class="flex">
                  <el-radio v-model="dateSelectForm.Type" :label="1">{{
                    $t("ETableChildren.latest_date_indicator")
                  }}</el-radio>
                  <div>
                    <label class="el-form-item__label">{{
                      $t("ETableChildren.lagging_period_label")
                    }}</label>
                    <el-input
                      v-model="dateSelectForm.MoveForward"
                      type="number"
                      :min="0"
                      style="margin-right: 10px; width: 80px"
                      @change="
                        (e) => {
                          dateSelectForm.MoveForward = Number(e);
                        }
                      "
                    />{{ $t("ETableChildren.term_ipt") }}
                  </div>
                </div>
              </li>
              <li>
                <dateMoveWaySec ref="dateMoveWayRef" />
              </li>
            </ul>
          </section>
  
          <section class="bot">
            <el-button
              type="primary"
              @click="calculateHandle"
              style="width: 120px; margin-right: 30px"
              >{{ $t("ETableChildren.calculation_btn") }}</el-button
            >
            <el-button
              type="primary"
              plain
              @click="cancelHandle"
              style="width: 120px"
              >{{ $t("ETable.Btn.cancel_btn") }}</el-button
            >
            <el-popover width="300" trigger="hover" placement="right">
              <div v-html="formulaTipContent"></div>
              <el-button class="tips-btn" type="text" slot="reference">{{
                $t("Edb.formula_instru")
              }}</el-button>
            </el-popover>
          </section>
        </div>
      </div>
    </div>
  </template>
  <script>
  import { dataBaseInterface } from "@/api/api.js";
  import * as sheetInterface from "@/api/modules/sheetApi.js";
  import * as preDictEdbInterface from "@/api/modules/predictEdbApi.js";
  import selectTarget from "@/views/chartRelevance_manage/components/selectTarget.vue";
  import edbDetailSection from "@/views/datasheet_manage/components/edbDetailSection.vue";
  import dateMoveWaySec from "@/views/datasheet_manage/components/dateMoveWaySection.vue";
  import {
    formRules,
    formulaTip,
  } from "@/views/dataEntry_manage/databaseComponents/util";
  export default {
    components: {
      selectTarget,
      edbDetailSection,
      dateMoveWaySec,
    },
    props: {
      isShow: {
        type: Boolean,
      },
      calculationItem: {
        //传入的计算种类
        type: Object,
      },
      linkList: {
        //指标列表
        type: Array,
        default: [],
      },
      activeLink: {
        //选中的指标
        type: Object,
        default: {},
      },
    },
    computed: {
      frequencyArr() {
        return [
          { label: this.$t("ETable.Date.day_lable"), value: "日度" },
          { label: this.$t("ETable.Date.week_lable"), value: "周度" },
          { label: this.$t("ETable.Date.dekad_lable"), value: "旬度" },
          { label: this.$t("ETable.Date.month_lable"), value: "月度" },
          { label: this.$t("ETable.Date.quarter_lable"), value: "季度" },
          { label: this.$t("ETable.Date.year_lable"), value: "年度" },
        ];
      },
      moveTypeOpions() {
        return [
          {
            label: this.$t("ETableChildren.ahead_lable"),
            key: 1,
          },
          {
            label: this.$t("ETableChildren.lagging_lable"),
            key: 2,
          },
        ];
      },
      fre_options() {
        return [
          { label: this.$t("ETable.Date.day"), value: "天" },
          { label: this.$t("ETable.Date.week_min"), value: "周" },
          { label: this.$t("ETable.Date.month"), value: "月" },
          { label: this.$t("ETable.Date.quarter_min"), value: "季" },
          { label: this.$t("ETable.Date.year"), value: "年" },
        ];
      },
      calendarOptions() {
        return [
          { label: this.$t("ETable.Date.calendar_gre"), key: "公历" },
          { label: this.$t("ETable.Date.calendar_lunar"), key: "农历" },
        ];
      },
  
      currentLang() {
        return this.$store.state.lang;
      },
    },
    watch: {
      isShow(newv) {
        if (!newv) return;
        this.formData.source = +this.calculationItem.source;
        this.edbList = _.cloneDeep(this.linkList);
        this.edbActive = _.cloneDeep(this.activeLink);
        this.selectEdbInfo = null;
        this.linkClick(this.edbActive);
        this.handleFormulaTipContent()
      },
      edbActive:{
        deep:true,
        handler(){
          this.handleEditData();
        },
      }
    },
    data() {
      return {
        isCalculateDia: true,
        formData: {
          source: + this.calculationItem.source,
          frequency: "",
          nNum: 1,
          moveType: 1,
          moveUnit: "天",
          moveVal: "",
          calendarType: "公历",
          valueType: "期末值",
          alphaValue: 0,
        },
        formRules,
        formulaTip,
        formulaTipContent:'',
  
        edbList: [], //指标标签列表
        edbActive: {}, //目前选中的标签
        editingLabel: "", //编辑标签名称
  
        search_edb: "",
        searchOptions: [],
        selectEdbInfo: null,
  
        dateSelectForm: {
          Type: 1,
          MoveForward: 0,
        },
      };
    },
    methods: {
      async handleEditData(){
        await this.$nextTick();
        let v = this.linkList.find(_=>_.Id == this.edbActive.Id);
        if(!v || !v.calculationMethod || !v.calculationMethod.length) return this.clearFormValue();
        let item = v.calculationMethod.find(_=>_.source == this.formData.source);
        if(!item) return this.clearFormValue();
        // 累计值有问题
        //处理编辑数据
        this.formData = {
          source:+item.source,
          frequency:item.frequency || '',
          moveUnit:item.moveFrequency || '天',
          moveType:item.moveType || 1,
          calendarType:item.calendar || "公历",
          nNum:1,
          moveVal:'',
          valueType:'期末值',
          alphaValue:0,
        };
        const valueMap = {
          22: "moveVal",
          51: "valueType",
          alpha: "alphaValue",
        };
        this.formData[[22,51,'alpha'].includes(this.calculationItem.fromEdbKey) ? valueMap[this.calculationItem.fromEdbKey] : 'nNum'] = +item.formula || item.formula;
        
        this.dateSelectForm = {
          Type: 1,
          MoveForward: item.moveForward || 0,
        };
        this.$refs.dateMoveWayRef.dateChangeArr = item.dateChange || [];
      },
      handleFormulaTipContent(){
         this.formulaTipContent = this.formulaTip.get(this.calculationItem.fromEdbKey);
         if(this.formData.source == 2) this.formulaTipContent = this.formulaTip.get(61); //积累季度
         if(this.formData.source == 14) this.formulaTipContent = this.formulaTip.get(63); //年初至今计算
      },
      handleRadioGroup() {
        this.handleEditData()
        this.$refs.selectRef.targetTypeChange();
        this.handleFormulaTipContent()
        this.selectEdbInfo = null;
        this.edbActive = null;
        let firstEdb = this.edbList[0];
        if (firstEdb) {
          this.edbActive = firstEdb;
          this.$emit("changeActiveEdb", { item: firstEdb });
          this.linkClick(firstEdb);
        }
      },
      async calculateHandle() {
        await this.$refs.form.validate();
        if (!this.selectEdbInfo)
          return this.$message.warning(
            this.$t("SandboxManage.SandFlow.select_indicator_criteria")
          );
        const { source, nNum, moveType, moveUnit, calendarType, frequency } =
          this.formData;
        const valueMap = {
          22: "moveVal",
          51: "valueType",
          alpha: "alphaValue",
        };
  
        let params = {
          DataTime: "",
          Source: +source,
          Frequency: frequency,
          Formula: valueMap[this.calculationItem.fromEdbKey]
            ? String(this.formData[valueMap[this.calculationItem.fromEdbKey]])
            : String(nNum),
          EdbInfoId: this.selectEdbInfo.EdbInfoId,
          MoveFrequency: moveUnit,
          MoveType: moveType,
          Calendar: calendarType,
          MoveForward: this.dateSelectForm.MoveForward,
          DateChange: this.$refs.dateMoveWayRef.dateChangeArr,
        };
        const res = await sheetInterface.getMixedCalculateData(params);
        if (res.Ret !== 200) return;
        let value = res.Data.ShowValue || "";
        const tips = {
          5: `N=${params.Formula}`,
          6: `N=${params.Formula}`,
          7: `N=${params.Formula}`,
          10: `移动方式${params.MoveType == 1 ? "领先" : "滞后"}${
            params.Formula
          }${params.MoveFrequency}`,
          11: `N=${params.Formula} ${params.Calendar}`,
          9: `数据取值${params.Formula} 频度${params.Frequency}`,
          15: `alpha值=${params.Formula}`,
        };
        let calculation = {
          fromEdbKey: this.calculationItem.fromEdbKey,
          label: this.calculationItem.label,
          source: +this.formData.source,
          value,
          calendar: params.Calendar,
          dateChange: params.DateChange,
          edbInfoId: params.EdbInfoId,
          formula: params.Formula,
          frequency: params.Frequency,
          moveForward: params.MoveForward,
          moveFrequency: params.MoveFrequency,
          moveType: params.MoveType,
          dataTime: params.DataTime,
          tip: tips[params.Source] || "",
        };
        this.$emit("addCalculation", { item: calculation });
        this.cancelHandle();
      },
      /* 过滤负数 小数点*/
      filterCode(item) {
        item.moveVal = item.moveVal.replace(/[^\.\d]/g, "").replace(".", "");
      },
      editLinkName(item) {
        this.search_edb = "";
        this.editingLabel = item.Name;
        item.editing = true;
        this.$nextTick(() => {
          this.$refs.labelEditInput[0].focus();
        });
      },
      editLinkNameFinish(item) {
        this.search_edb = "";
        if (this.editingLabel) {
          item.editing = false;
          item.Name = this.editingLabel;
          this.$emit("editEdbName", { item });
        } else {
          this.$message.warning("不能为空");
        }
      },
      async linkClick(item) {
        this.search_edb = "";
        const res = await dataBaseInterface.targetDetail({ EdbInfoId: item.Id });
        if (res.Ret !== 200) return;
        const { EdbInfoId, EdbInfoType, EdbName, Frequency, HaveOperaAuth } =
          res.Data;
        if (!HaveOperaAuth)
          return this.$message.warning(this.$t("MsgPrompt.no_edb_auth"));
        if (this.formData.source === 1 && Frequency !== "月度")
          return this.$message.warning(this.$t("ETableChildren.only_select_msg"));
        else if (this.formData.source === 2 && Frequency !== "季度")
          return this.$message.warning(
            this.$t("ETableChildren.only_quarterly_msg")
          );
        else if (this.formData.source === 8 && Frequency === "日度")
          return this.$message.warning(this.$t("ETableChildren.no_day_msg"));
        else if (this.formData.source === 14 && Frequency === "年度")
          return this.$message.warning(this.$t("ETableChildren.no_year_msg"));
        this.selectTargetHandle({ EdbInfoId, EdbInfoType, EdbName }, "change");
        this.edbActive = item;
        this.$emit("changeActiveEdb", { item });
      },
      linkDelete(item, index) {
        this.search_edb = "";
        this.edbList.splice(index, 1);
        this.$emit("edbDelete", { item });
        if (this.edbActive.RId == item.RId) {
          let firstEdb = this.edbList[0];
          if (firstEdb) {
            this.edbActive = firstEdb;
            this.$emit("changeActiveEdb", { item: firstEdb });
            this.selectEdbInfo = null;
            this.linkClick(firstEdb);
          } else {
            this.edbActive = {};
            this.$emit("changeActiveEdb", { item: null });
            this.selectEdbInfo = null;
          }
        }
      },
      /* 选择指标 */
      async selectTargetHandle(e, type = "add") {
        //add添加  change标签切换
        if (!e) {
          this.selectEdbInfo = null;
          return;
        }
        if (this.edbList.find((_) => _.Id == e.EdbInfoId) && type == "add") {
          return this.$message.warning(
            this.$t("SandboxManage.SandFlow.data_already_exists")
          );
        }
        if (type == "add") {
          let activeItem = {
            RId: 1 + "-" + e.EdbInfoId,
            Id: e.EdbInfoId,
            Name:
              this.currentLang === "en" ? e.EdbNameEn || e.EdbName : e.EdbName,
            Type: 1,
            editing: false,
            databaseType: e.EdbInfoType, //0 普通指标 | 1 预测指标
            detailParams: {
              code: e.UniqueCode,
              id: e.EdbInfoId,
              classifyId: e.ClassifyId,
            },
            calculationMethod: [],
          };
          this.edbActive = activeItem;
          this.edbList.push(activeItem);
          this.$emit("addEdbItem", { item: activeItem });
        }
  
        const res =
          e.EdbInfoType === 1
            ? await preDictEdbInterface.edbDataInfo({
                EdbInfoId: e.EdbInfoId,
                CurrentIndex: 1,
              })
            : await dataBaseInterface.targetList({
                EdbInfoId: e.EdbInfoId,
                CurrentIndex: 1,
              });
  
        if (res.Ret !== 200) return;
  
        const {
          EdbInfoId,
          EdbCode,
          EdbName,
          Frequency,
          Unit,
          StartDate,
          ModifyTime,
          PredictDataList,
          DataList,
          HaveOperaAuth,
        } = res.Data.Item;
  
        this.selectEdbInfo = {
          EdbCode,
          EdbName,
          Frequency,
          Unit,
          StartDate,
          ModifyTime,
          EdbInfoId,
          HaveOperaAuth,
          DataList: PredictDataList
            ? [...PredictDataList, ...DataList].slice(0, 5)
            : DataList.slice(0, 5),
        };
      },
      cancelHandle() {
        this.initData();
        this.$emit('handleCloseDialog')
        this.$emit("update:isShow", false);
      },
      clearFormValue(){
        this.formData = {
          source: +this.formData.source,
          frequency: "",
          nNum: 1,
          moveType: 1,
          moveUnit: "天",
          moveVal: "",
          calendarType: "公历",
          valueType: "期末值",
          alphaValue: 0,
        };
        this.dateSelectForm = {
          Type: 1,
          MoveForward: 0,
        };
        this.$refs.dateMoveWayRef && this.$refs.dateMoveWayRef.initData();
      },
      initData() {
        this.clearFormValue();
        this.search_edb = "";
        this.selectEdbInfo = null;
        this.edbList = [];
        this.edbActive = {};
        this.editingLabel = "";
      },
    },
  };
  </script>
  <style scoped lang="scss">
  @import "~@/styles/theme-vars.scss";
  
  .calculate-edb-value-dialog {
    background: #fff;
    position: fixed;
    top: 5vh;
    left: 50%;
    transform: translateX(-50%);
    width: 1058px;
    border-radius: 2px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
    z-index: 9999;
  
    .header {
      font-size: 16px;
      background: $theme-color;
      color: #fff;
      padding: 15px;
      display: flex;
      align-content: center;
      justify-content: space-between;
  
      .el-icon-close {
        font-size: 20px;
        cursor: pointer;
      }
    }
  
    .main {
      padding: 30px;
      max-height: 75vh;
      min-height: 300px;
      overflow-y: auto;
      position: relative;
  
     
  
      .main-top {
        margin-bottom: 20px;
      }
  
      .link-box-tags {
        display: flex;
        align-items: center;
        overflow-x: auto;
        margin-bottom: 20px;
  
        .unchoose-tag {
          border: 1px solid #c8cdd9;
        }
  
        .choosed-tag {
          border: 1px solid #0052d9;
          background: rgba(236, 242, 254, 1);
        }
  
        .link-box-tag {
          display: flex;
          align-items: center;
          padding: 0 8px;
          height: 40px;
          max-width: 250px;
          margin-right: 30px;
          border-radius: 4px;
          cursor: pointer;
  
          &:last-child {
            margin-right: 0;
          }
  
          span {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
  
          img {
            height: 16px;
            width: 16px;
            margin-left: 8px;
          }
        }
      }
  
      .edb-list {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
  
        .el-tag {
          cursor: pointer;
        }
      }
  
      .form-section {
        margin: 20px 0;
      }
  
      .bot {
        display: flex;
        justify-content: center;
        margin: 30px 0;
        position: relative;
      }
  
      .tips-btn {
        position: absolute;
        bottom: -10px;
        right: 40px;
      }
  
      .data-cont {
        margin: 15px 0;
        border: 1px solid #dcdfe6;
  
        .data-li {
          display: flex;
          padding: 15px;
          text-align: center;
          justify-content: space-around;
  
          &.choose {
            background: #ecf5ff;
          }
        }
      }
  
      .date-select-cont {
        li {
          margin: 20px 0;
        }
  
        .flex {
          display: flex;
          align-items: center;
        }
      }
    }
  }
  </style>
  