<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">累计值转月</el-radio>
              <el-radio :label="2">累计值转季值</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">累计值</el-radio>
              <el-radio :label="14">年初至今累计值</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="移动方式" 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"
									:label="item"
									:value="item"
								>
								</el-option>
							</el-select>
						</el-form-item>

						<el-form-item label="N等于" prop="nNum" v-if="[8,12,13,35].includes(info.fromEdbKey)">
							<el-input
								v-model="formData.nNum"
								style="width: 200px"
								placeholder="请输入N数值"
								type="number"
								@change="changeParams"
							/>
						</el-form-item>

						<el-form-item label="日历" prop="calendarType" v-if="info.fromEdbKey===35">
							<el-select
								v-model="formData.calendarType"
								placeholder="请选择日历"
								style="width: 200px"
								@change="changeParams"
							>
								<el-option
									v-for="item in calendarOptions"
									:key="item.key"
									:label="item.label"
									:value="item.label"
								>
								</el-option>
							</el-select>
						</el-form-item>

            <el-form-item label="频度" prop="frequency" v-if="[9,13].includes(formData.source)">
							<el-select
								v-model="formData.frequency"
								placeholder="请选择频度"
								style="width: 200px"
								clearable
                @change="changeParams"
							>
								<el-option
									v-for="item in frequencyArr"
									:key="item"
									:label="item"
									:value="item"
								>
								</el-option>
							</el-select>
						</el-form-item>

						<el-form-item label="数据取值" prop="valueType" v-if="info.fromEdbKey===51">
							<el-select
								v-model="formData.valueType"
								placeholder="请选择数据取值类型"
								style="width: 200px"
                @change="changeParams"
							>
								<el-option key="期末值" label="期末值" value="期末值"/>
								<el-option key="平均值" label="平均值" value="平均值"/>
							</el-select>
						</el-form-item>

						<el-form-item label="alpha值" prop="alphaValue" v-if="info.fromEdbKey==='alpha'">
              <el-input 
                v-model="formData.alphaValue" 
                placeholder="请选择alpha值"
                style="width: 200px"
                @change="changeParams"
              />
						</el-form-item>
					</el-form>
        </section>

        <!-- 计算结果 -->
        <section class="result-section" v-if="showResult">
          <label>计算结果:</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="无对应的数据" size="mini" v-else/>
        </section>

        <section class="bot">
          <el-button type="primary" @click="insertData" v-if="showResult">插入值</el-button>
          <el-button type="primary" @click="calculateHandle" v-else>计算</el-button>
          <el-button type="primary" plain @click="cancelHandle">取消</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
    }
  },
  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,
      frequencyArr: ['日度', '周度','旬度', '月度', '季度', '年度'],

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

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

      moveTypeOpions: [
				{
					label: '领先',
					key: 1
				},
				{
					label: '滞后',
					key: 2
				},
			],
      fre_options: ['天','周','月','季','年'],
      calendarOptions: [
				{label: '公历',key: 1},
				{label: '农历',key: 2},
			],
    }
  },
  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.$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('只能选择月度指标')
      else if(this.formData.source===2&&Frequency!=='季度') return this.$message.warning('不能选择季度指标')
      else if(this.formData.source===8&&Frequency==='日度') return this.$message.warning('不能选择日度指标')
      else if(this.formData.source===14&&Frequency==='年度') return this.$message.warning('不能选择年度指标')


      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>
