<template>
  <div v-dialogDrag v-if="isShow" >
    <div class="calculate-edb-value-dialog el-dialog" >
      <div class="header el-dialog__header">
        <span>{{info.label}}</span>
        <i class="el-icon-close" @click="cancelHandle"/>
      </div>

      <div class="main">

        <section class="main-top">

          <template v-if="info.fromEdbKey===5">
            <el-radio-group 
              v-model="formData.source"
              @change="changeSource"
            >
              <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="info.fromEdbKey===62"> 
            <el-radio-group 
              v-model="formData.source"
              @change="changeSource"
            >
              <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="edb-list">
              <el-tag 
                :effect="selectEdbInfo&&selectEdbInfo.EdbInfoId===item.EdbInfoId?'dark':'plain'" 
                v-for="(item,index) in edbArrFromTable" 
                :key="index"
                @click="selectTableEdbHandle(item)"
              >{{ item.ShowValue }}</el-tag>
          </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="info.fromEdbKey === 22" prop="moveVal">
							<el-select
								v-model="formData.moveType"
								style="width: 100px"
								placeholder=""
								size="mini"
								@change="changeParams"
							>
								<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)"
                @change="changeParams"
							></el-input>
							<el-select
								v-model="formData.moveUnit"
								size="mini"
								placeholder=""
								style="width: 100px"
                @change="changeParams"
							>
								<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(info.fromEdbKey)">
							<el-input
								v-model="formData.nNum"
								style="width: 200px"
								:placeholder="$t('ETableChildren.enter_n_value')"
								type="number"
								@change="changeParams"
							/>
						</el-form-item>

						<el-form-item :label="$t('OnlineExcelPage.label_calendar')" prop="calendarType" v-if="info.fromEdbKey===35">
							<el-select
								v-model="formData.calendarType"
								:placeholder="$t('OnlineExcelPage.select_calendar_pld')"
								style="width: 200px"
								@change="changeParams"
							>
								<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
                @change="changeParams"
							>
								<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="info.fromEdbKey===51">
							<el-select
								v-model="formData.valueType"
								:placeholder="$t('OnlineExcelPage.select_data_type')"
								style="width: 200px"
                @change="changeParams"
							>
								<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="info.fromEdbKey==='alpha'">
              <el-input 
                v-model="formData.alphaValue" 
                :placeholder="$t('Edb.InputHolderAll.input_alpha_val')"
                style="width: 200px"
                @change="changeParams"
              />
						</el-form-item>
					</el-form>
        </section>

        <!-- 计算结果 -->
        <section class="result-section" v-if="showResult">
          <label>{{$t('ETableChildren.calculate_result')}}:</label>
          <ul class="data-cont" v-if="calculateShowData.length">
              <li 
                v-for="(item,index) in calculateShowData" 
                :key="index" 
                :class="[{'choose': item.DataTime===chooseItem.Date || (!chooseItem.Date&&index===0)},'data-li']"
              >
                <span>{{item.DataTime}}</span>
                <span style="min-width:150px">{{item.Value}}</span>
              </li>
          </ul>

          <tableNoData :text="$t('ETableChildren.no_corresponding_data')" size="mini" v-else/>
        </section>

        <section class="bot">
          <el-button type="primary" @click="insertData" v-if="showResult">{{$t('OnlineExcelPage.insert_value_btn')}}</el-button>
          <el-button type="primary" @click="calculateHandle" v-else>{{$t('ETableChildren.calculation_btn')}}</el-button>
          <el-button type="primary" plain @click="cancelHandle">{{$t('ETable.Btn.cancel_btn')}}</el-button>

        </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 { resetDialogCellStyle } from "../common/customTable";
import selectTarget from '@/views/chartRelevance_manage/components/selectTarget.vue';
import edbDetailSection from './edbDetailSection.vue';
import { formRules } from '@/views/dataEntry_manage/databaseComponents/util';
export default {
  props: {
    isShow: {
      type: Boolean
    },
    info: {
      type: Object
    }
  },
  components: { selectTarget,edbDetailSection },
  computed: {
    edbArrFromTable() {
      let arr = this.$parent.config.data.flat().filter(_ =>_.DataType === 2);
      let filterArr =  []
      
      arr.forEach(item => {
        if(filterArr.findIndex(_ => _.EdbInfoId===item.EdbInfoId)===-1) {
          filterArr.push(item)
        }
      })
      
       return filterArr
    },
    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: '农历'},
			]
    },
  },
  watch: {
    isShow(nval) {
      if(!nval) return
      console.log(this.info)
      const { source,formStr } = this.info;

      this.formData.source = source;
      //回显
      if(formStr) {
        const {
          Source,
          Frequency,
          Formula,
          EdbInfoId,
          MoveFrequency,
          MoveType, 
          Calendar 
        } = JSON.parse(formStr);

        this.formData = {
          source: Source,
          frequency: Frequency,
          nNum: Formula,
          moveType: MoveType,
          moveUnit: MoveFrequency,
          moveVal: Formula,
          calendarType: Calendar,
          valueType: Formula,
          alphaValue: Formula,
        }
        this.selectTableEdbHandle({EdbInfoId})
      }
    }
  },
  data() {
    return {
      isCalculateDia: true,
      formData: {
        source: this.info.fromEdbKey,
        frequency: '',
        nNum: 1,
				moveType: 1,
				moveUnit: '天',
				moveVal: '',
				calendarType: '公历',
				valueType: '期末值',
        alphaValue: 0,
      },
      formRules,


      showResult: false,
      calculateShowData: [], //计算全部数据
      chooseItem: {
        Date: ''
      },//要插入表格的项

      search_edb: '',
      searchOptions: [],
      selectEdbInfo: null,



    }
  },
  mounted(){

  },
  methods:{
    /* 计算结果 */
    async calculateHandle() {
      await this.$refs.form.validate();
      
      const {  
        source,
        nNum,
				moveType,
				moveUnit,
				calendarType,
        frequency
      } = this.formData;

      const valueMap = {
        22: 'moveVal',
        51: 'valueType',
        'alpha': 'alphaValue'
      }

      let DataTime = this.$parent.selectCell.DataType === 1 ? this.$parent.selectCell.ShowValue : ''

      let params = {
        DataTime,
        Source: source,
        Frequency: frequency,
        Formula: valueMap[this.info.fromEdbKey] ? String(this.formData[valueMap[this.info.fromEdbKey]]) : String(nNum),
        EdbInfoId: this.selectEdbInfo.EdbInfoId,
        MoveFrequency: moveUnit,
        MoveType: moveType, 
        Calendar: calendarType
      }

      const res = await sheetInterface.getMixedCalculateData(params)
      if(res.Ret!==200) return 

      this.showResult = true;
      this.calculateShowData = res.Data.List || [];

      // if(!this.calculateShowData.length && DataTime) return this.$message.warning('所选指标所选日期无值')

      let InsertValue = this.calculateShowData.length 
        ? (this.calculateShowData.find(_ => _.DataTime===DataTime) ? this.calculateShowData.find(_ => _.DataTime===DataTime).Value.toString() : this.calculateShowData[0].Value.toString()) 
        : ''
      this.chooseItem = {
          Date:DataTime,
          EdbInfoId: this.selectEdbInfo.EdbInfoId,
          InsertValue,
          Str: JSON.stringify(params)
        }
      
    },

    /* 已计算过改参数重新计算 */
    changeParams() {
      this.showResult && this.calculateHandle()
    },

    /* 插入值 */
    insertData() {

      // if(this.$parent.selectCell.DataType !== 1) return this.$message.warning('请在表格中选择日期')
        
      if(!this.calculateShowData.length) return this.$message.warning(this.$t('OnlineExcelPage.there_data_no_msg') )
      
      this.$emit('insert',this.chooseItem)
      this.cancelHandle();
    },

    /* 选择指标 */
    async selectTargetHandle(e) {
      this.changeSource();
      if(!e) {
        this.selectEdbInfo = null
        return
      }

      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,SourceName,PredictDataList,DataList } = res.Data.Item;
      this.selectEdbInfo = {
        EdbCode,EdbName,Frequency,Unit,StartDate,ModifyTime,SourceName,EdbInfoId,
        DataList: PredictDataList ? [...PredictDataList,...DataList].slice(0,5) : DataList.slice(0,5)
      };
    },

    /* 选择表格指标 */
    async selectTableEdbHandle(item) {
      const res = await dataBaseInterface.targetDetail({EdbInfoId:item.EdbInfoId})
      if(res.Ret !== 200) return

      const { EdbInfoId,EdbInfoType,EdbName,Frequency } = res.Data;

      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.no_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.search_edb = EdbName;
      this.selectTargetHandle({EdbInfoId,EdbInfoType,EdbName})
    },

    /*  */
    changeSource() {
      this.showResult = false;
      this.calculateShowData = [];
      this.chooseItem = { Date: '' };
    },

    initData() {
      this.search_edb='';
      this.selectEdbInfo = null;
      this.showResult = false;
      this.calculateShowData = [];
      this.chooseItem = { Date: '' };
      this.formData = {
        source: this.formData.source, 
        frequency: '',
        nNum: 1,
				moveType: 1,
				moveUnit: '天',
				moveVal: '',
				calendarType: '公历',
				valueType: '期末值'
      }
    },

    cancelHandle() {
      this.initData();
      this.$emit('update:isShow',false);
      resetDialogCellStyle();
    }
  },
}
</script>
<style scoped lang='scss'>
@import "~@/styles/theme-vars.scss";
.calculate-edb-value-dialog {
  background: #fff;
  position: fixed;
  top: 20%;
  left: 50%;
  width: 750px;
  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: 20px;
    max-height: calc(100vh - 350px);
    min-height: 300px;
    overflow-y: auto;
    .main-top {
      margin-bottom: 20px;
    }
    .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;
    }
    .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;
        }
      }
    }
  }
}  
</style>
