<template>
  <el-dialog
		:visible.sync="isShow"
		:close-on-click-modal="false"
		:modal-append-to-body="false"
    :title="title"
		@close="cancelHandle"
		custom-class="predictEdb-dialog"
		center
		width="990px"
		top="5vh"
		v-dialogDrag
	>
		<div class="dialog-main">
			<el-form
        ref="formRef"
				label-position="right"
				hide-required-asterisk
				label-width="100px"
				:model="formData"
				:rules="formRules"
      >
        <el-form-item label="添加到分类" prop="classify">
          <el-select
            v-model="formData.classify"
            placeholder="请选择分类"
            style="width: 90%"
            clearable
          >
            <el-option
              v-for="item in classifyArr"
              :key="item.ClassifyId"
              :label="item.ClassifyName"
              :value="item.ClassifyId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择指标" prop="oldEdb" v-if="title==='添加指标'">
          <el-select
            v-model="formData.oldEdb"
            v-loadMore="searchLoad"
            style="width: 90%"
            :filterable="!formData.oldEdb"
            remote
            clearable
            placeholder="指标ID/指标名称"
            :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="item.EdbName"
              :value="item.EdbInfoId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预测指标名称" prop="edbName">
          <el-input
          v-model="formData.edbName"
          style="width: 90%"
          placeholder="指标名称"/>
        </el-form-item>
        <el-form-item label="频度" class="small-item" prop="frequency">
          <span>{{formData.frequency}}</span>
        </el-form-item>
        <el-form-item label="最新值" class="small-item" prop="newdata">
          <span>{{formData.newdata}}</span>
        </el-form-item>
        <el-form-item label="最新日期" class="small-item" prop="lasetDate">
          <span>{{formData.lasetDate}}</span>
        </el-form-item>
        <el-form-item label="预测截止日期" prop="endDate">
          <el-date-picker
            v-model="formData.endDate"
            type="date"
            style="width: 90%"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期"
            :picker-options="{
              disabledDate(time) {
                return time.getTime() < Date.now();
              }
            }">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预测规则" prop="predict_type">
          <el-select
            v-model="formData.predict_type"
            placeholder="请选择分类"
            style="width: 90%"
          >
            <el-option
              v-for="item in predictTypeOptions"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="固定值" prop="fixedValue" v-if="formData.predict_type===2">
          <el-input
          v-model="formData.fixedValue"
          style="width: 90%"
          placeholder="请输入值"/>
        </el-form-item>
      </el-form>
      <div class="tip-wrap" v-html="tipTxt"></div>
		</div>
		<div class="dia-bot">
			<el-button
				type="primary"
				style="margin-right: 20px"
				@click="saveHandle"
				>保存</el-button
			>
			<el-button type="primary" plain @click="cancelHandle">取消</el-button>
		</div>

	</el-dialog>
</template>

<script>
import * as preDictEdbInterface from '@/api/modules/predictEdbApi.js';
import { dataBaseInterface } from '@/api/api.js';
export default {
  props: {
    isShow: Boolean,
    title: String,
    edbForm: Object
  },
  watch: {
    isShow(newval) {
      if(newval) {
        this.getClassifyOne();
        const {ClassifyId,EdbName,Frequency,LatestValue,EndDate,RuleType,FixedValue,EdbInfoId,LatestDate} = this.edbForm;
        EdbInfoId 
          ? this.formData = {
            edb_id: EdbInfoId,
            classify: ClassifyId,
            oldEdb: '',
            edbName: EdbName,
            frequency: Frequency,
            newdata: LatestValue,
            lasetDate: LatestDate,
            endDate: EndDate,
            predict_type: RuleType,
            fixedValue: FixedValue
          } 
          : null
      }
    }
  },
  data() {
    return {
      formData: {
        edb_id: '',
        classify: '',
        oldEdb:'',
        edbName:'',
        frequency: '',
        newdata:'',
        lasetDate: '',
        endDate:'',
        predict_type: 1,
        fixedValue: ''
      },
      formRules: {
        classify:[
					{ required: true, message: '分类不能为空', trigger: 'blur' },
				],
        oldEdb: [
					{ required: true, message: '指标不能为空', trigger: 'blur' },
				],
        edbName: [
					{ required: true, message: '指标名称不能为空', trigger: 'blur' },
				],
        endDate: [
					{ required: true, message: '预测截止日期不能为空', trigger: 'blur' },
				],
        predict_type: [
					{ required: true, message: '预测规则不能为空', trigger: 'blur' },
				],
        fixedValue: [
					{ required: true, message: '固定值不能为空', trigger: 'blur' },
				],
      },
      classifyArr: [],
      predictTypeOptions:[
        { key: 1, label: '最新' },
        { key: 2, label: '固定值' }
      ],//预测规则

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

      tipTxt: `规则说明：1、“最新”规则，预测值全部等于最新值；<br>
        2、“固定值”规则，手动设定一个常数，预测值默认全部等于常数值；`
    }
  },
  methods: {
    getClassifyOne() {
      preDictEdbInterface.classifyOne().then(res => {
        if(res.Ret !== 200) return

        this.classifyArr = res.Data.AllNodes || [];
      }) 
    },

    /* 选择指标  同步名称频度最新值*/
    async selectEdbHandle(val) {
      if(val) {
        const { Data } = await dataBaseInterface.targetDetail({ EdbInfoId: val });

        this.formData.edbName = `${Data.EdbName}(预测)`;
        this.formData.frequency = Data.Frequency;
        this.formData.newdata = Data.LatestValue;
        this.formData.lasetDate = Data.LatestDate;

      }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)
		},

		searchApi(query,page=1) {
			dataBaseInterface.targetSearchByPage({
				KeyWord:query,
				CurrentIndex: page
			}).then(res => {
				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) {
			this.search_page = 1;
			this.current_search = e.target.value;
			this.searchApi(this.current_search);
		},

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

    /* 保存 */
    async saveHandle() {
      await this.$refs.formRef.validate();

      const {
        edb_id,
        classify,
        oldEdb,
        edbName,
        endDate,
        predict_type,
        fixedValue 
      } = this.formData;
      let params = {
        ClassifyId: classify,
        EdbName: edbName,
        EndDate: endDate,
        RuleType: predict_type,
        FixedValue: Number(fixedValue)
      }

      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.$emit('successHandle',edb_id ? null : {
        code: Data.UniqueCode,
          id: Data.EdbInfoId
      })
      this.cancelHandle();

    },
    cancelHandle() {
      this.formData = {
        classify: '',
        oldEdb:'',
        edbName:'',
        frequency: '',
        newdata:'',
        endDate:'',
        predict_type: '',
        fixedValue: ''
      }

      this.$refs.formRef.resetFields();
      this.$emit('update:isShow',false)
    }
  },
  mounted() {

  },
}
</script>
<style scoped lang='scss'>
.dia-bot {
  display: flex;
  justify-content: center;
  margin: 40px 0;
}
</style>
<style lang="scss">
  .predictEdb-dialog {
    .small-item {
      margin-bottom: 10px;
    }
    .tip-wrap {
      color: #999;
      padding-left: 30px;
      text-indent: -70px;
      margin-left: 70px;
    }
  }
</style>