<template>
		<!-- :modal-append-to-body='false' -->
  <el-dialog
		:visible.sync="show"
		:close-on-click-modal="false"
    :append-to-body="true"
		@close="cancelHandle"
		custom-class="satter-series-dialog"
		center
		width="1200px"
		v-dialogDrag
    top="8vh"
    title="系列1配置"
  >

    <div class="target-wrapper">
      <div class="tags-cont">
        <div class="tag-title">标签</div>
        <div class="tip">
          <i class="el-icon-s-opportunity"/>
          标签默认取X轴指标名称，可修改
        </div>
        <ul class="tag-ul">
          <li class="tag-item" v-for="(item,index) in targetInfo.xEdbs" :key="index">
            <el-input
              v-model="item.name"
              class="tag-input"
              style="width:90%"
              clearable
              size="mini"
            />
          </li>
        </ul>
      </div>

      <div class="x-target-cont">
        <div class="tag-title">
          <div>
            X轴指标 
            <span style="color:#999">{{targetInfo.xEdbs.length}}项</span> 
          </div>
          <el-radio-group v-model="selectObj.xEdbFromType">
            <el-radio :label="0" style="margin-right: 15px">ETA指标</el-radio>
            <el-radio :label="1">ETA预测指标</el-radio>
          </el-radio-group>
        </div>
        <div class="targets-cont">
          <el-select
            v-model="search_txt"
            v-loadMore="searchLoad"
            ref="searchRef"
            :filterable="!search_txt"
            remote
            clearable
            placeholder="指标ID/指标名称"
            style="width:90%;display:block;margin:0 auto;"
            :remote-method="searchHandle"
            @click.native="inputFocusHandle('x',$event)"
            @change="selectTarget"
          >
            <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>
          <ul class="targets-ul">
            <li class="target-item" v-for="(item,index) in targetInfo.xEdbs" :key="index">
              <el-popover
                placement="top"
                title=""
                trigger="hover"
              >
                <span>{{item.target_name}}</span>
                <div slot="reference">
                  <div class="text_oneLine" style="width: 180px">
                    <i class="el-icon-edit-outline editsty" @click="replaceTarget(item,index,'x')"/>
                    {{index+1}}：{{item.target_name}}
                  </div>
                </div>
              </el-popover>
              <div>
                <span>{{item.date}}</span>
                <span style="margin: 0 5px;">{{item.value}}</span>
                <i class="el-icon-circle-close" style="color: #C54322;cursor:pointer;" @click="removeTarget('x',index)"/>
              </div>
            </li>
          </ul>
        </div>
      </div>

      <div class="x-target-cont">
         <div class="tag-title">
          <div>
            Y轴指标 
            <span style="color:#999">{{targetInfo.yEdbs.length}}项</span> 
          </div>
          <el-radio-group v-model="selectObj.yEdbFromType">
            <el-radio :label="0" style="margin-right: 15px">ETA指标</el-radio>
            <el-radio :label="1">ETA预测指标</el-radio>
          </el-radio-group>
        </div>
        <div class="targets-cont">
          <el-select
            v-model="search_txt"
            v-loadMore="searchLoad"
            ref="searchRef"
            :filterable="!search_txt"
            remote
            clearable
            placeholder="指标ID/指标名称"
            style="width:90%;display:block;margin:0 auto;"
            :remote-method="searchHandle"
            @click.native="inputFocusHandle('y',$event)"
            @change="selectTarget"
          >
            <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>
          <ul class="targets-ul">
            <li class="target-item" v-for="(item,index) in targetInfo.yEdbs" :key="index">
              
              <el-popover
                placement="top"
                title=""
                trigger="hover"
              >
                <span>{{item.target_name}}</span>
                <div slot="reference">
                  <div class="text_oneLine" style="width: 180px">
                    <i class="el-icon-edit-outline editsty" @click="replaceTarget(item,index,'y')"/>
                    {{index+1}}：{{item.target_name}}
                  </div>
                </div>
              </el-popover>
              <div>
                <span>{{item.date}}</span>
                <span style="margin: 0 5px;">{{item.value}}</span>
                <i class="el-icon-circle-close" style="color: #C54322;cursor:pointer;" @click="removeTarget('y',index)"/>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <el-form
      inline
      label-position="left"
      label-width="80px"
      ref="formRef"
      :model="form"
      :rules="formRules"
    >
      <el-form-item label="X轴" prop="x_title" style="margin-bottom: 20px;">
        <el-input
          v-model="form.x_title"
          style="width: 350px;"
          placeholder="请输入x轴名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="" prop="x_unit">
        <selectUnit 
          v-model="form.x_unit" 
          style="width: 150px"
          placeholder="请输入单位"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-select 
          v-model="form.x_date_type"
          placeholder="请选择日期添加方式"
          style="width:150px;"
          @change="()=>{ form.x_date_value=0,form.x_date='' }"
        >
          <el-option v-for="item in $parent.dateOptions" :key="item.key" :label="item.label" :value="item.key"/>
        </el-select>
        <span v-if="form.x_date_type === 2">
          <el-input
            type="number" 
            v-model="form.x_date_value"
            style="width:100px;"
          />
          天
        </span>
        <el-date-picker
          v-else-if="form.x_date_type === 3"
          v-model="form.x_date"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期"
          style="width: 150px"
        />
      </el-form-item>
      <el-form-item label="Y轴" prop="y_title" style="margin-bottom: 20px;">
        <el-input
          v-model="form.y_title"
          style="width: 350px;"
          placeholder="请输入y轴名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="" prop="y_unit">
        <selectUnit 
          v-model="form.y_unit" 
          style="width: 150px"
          placeholder="请输入单位"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-select 
          v-model="form.y_date_type"
          placeholder="请选择日期添加方式"
          style="width:150px;"
          @change="()=>{ form.y_date_value=0,form.y_date='' }"
        >
          <el-option v-for="item in $parent.dateOptions" :key="item.key" :label="item.label" :value="item.key"/>
        </el-select>
        <span v-if="form.y_date_type === 2">
          <el-input
            type="number" 
            v-model="form.y_date_value"
            style="width:100px;"
          />
          天
        </span>
        <el-date-picker
          v-else-if="form.y_date_type === 3"
          v-model="form.y_date"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期"
          style="width: 150px"
        />
      </el-form-item>
      <el-form-item label="系列名称" prop="series_name" style="margin-right: 40px">
        <el-input
          v-model="form.series_name"
          style="width: 350px"
          placeholder="请输入系列名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="系列颜色" prop="color">
        <el-color-picker
          v-model="form.color"
          size="mini"
          show-alpha
          :predefine="predefineColors"
          style="vertical-align: middle"
        ></el-color-picker>
      </el-form-item>
    </el-form>
    <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>


    <!-- 替换指标弹窗 -->
    <m-dialog
      :show.sync="openReplaceDialog"
      width="700px"
      title="指标替换"
      @close="cancelReplace"
    >
      <div>
        <el-form
					label-position="left"
					label-width="80px"
					:model="replaceForm"
				>
					<el-form-item label="指标名称" prop="name">
						<span>{{replaceForm.oldEdbName}}</span>
					</el-form-item>
          <el-form-item label="替换为">
            <el-radio-group v-model="edbFromType">
							<el-radio :label="0" style="margin-right: 15px">ETA指标</el-radio>
							<el-radio :label="1">ETA预测指标</el-radio>
						</el-radio-group>
            <el-select
              v-model="replaceForm.searchTxt"
              v-loadMore="searchLoad"
              ref="searchRef"
              :filterable="!replaceForm.searchTxt"
              remote
              clearable
              placeholder="指标ID/指标名称"
              style="width:90%;margin-top: 10px;display: block;"
              :remote-method="searchHandle"
              @click.native="inputFocusHandle('',$event)"
              @change="replaceEdbChange"
            >
              <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="数据日期">
            <el-date-picker
                v-model="replaceForm.item.date"
                type="date"
                style="width: 200px"
                :clearable="false"
              />
          </el-form-item> -->
        </el-form>
        <div style="display: flex;justify-content: center;margin-top:50px;">
          <el-button
            type="primary"
            style="margin-right: 60px"
            @click="saveReplace"
            >保存</el-button
          >
          <el-button type="primary" plain @click="cancelReplace"
            >取消</el-button
          >
        </div>
      </div>
    </m-dialog>

  </el-dialog>
</template>

<script>
import mDialog from '@/components/mDialog.vue'
import { dataBaseInterface } from '@/api/api.js';
import { defaultOpts } from '@/utils/defaultOptions';
import * as preDictEdbInterface from '@/api/modules/predictEdbApi.js';
export default {
  props: {
    show: {
      type: Boolean
    },
    serieInfo: {
      type: Object
    }
  },
  components: { mDialog },
  watch: {
    show(newval) {
      if(!newval) return
      
      if(this.serieInfo.edbs) {
        const { x_title,x_unit,y_title,y_unit,series_name,color,edbs } = this.serieInfo;

        this.form = { 
          x_title,
          x_unit,
          y_title,
          y_unit,
          series_name,
          color,
          x_date_type: edbs[0].x_date_type,
          x_date_value: edbs[0].x_date_value,
          x_date: edbs[0].x_date,
          y_date_type: edbs[0].y_date_type,
          y_date_value: edbs[0].y_date_value,
          y_date: edbs[0].y_date, 
        };

        this.targetInfo = {
          xEdbs: edbs.map(_ => ({
            name: _.name,
            target_id: _.x_target_id,
            target_name: _.x_target_name,
            date: '',
            value: '',
            is_show: _.is_show,
          })).filter(_ =>_.target_id),

          yEdbs: edbs.map(_ => ({
            target_id: _.y_target_id,
            target_name: _.y_target_name,
            date: '',
            value: '',
          })).filter(_ =>_.target_id)
        }     

      }
    }
  },
  data() {
    return {
      search_type: '',//x y
      search_txt: '',
      selectObj: {
        xEdbFromType:0,
        yEdbFromType: 0,
      },
      searchOptions: [],
			search_have_more: true,
			search_page: 1,
			current_search:'',

      targetInfo: {
        xEdbs: [],
        yEdbs: []
      },

      form: {
        x_title:'',
        x_unit:'',
        y_title:'',
        y_unit: '',
        series_name:'',
        color: defaultOpts.colors[0],
        x_date_type: 1,
        x_date_value: 0,
        x_date: '',
        y_date_type: 1,
        y_date_value: 0,
        y_date: '',
      },
      predefineColors: defaultOpts.colors.slice(0, 2), 

      formRules: {
        x_title:[
					{ required: true, message: 'X轴名称不能为空', trigger: 'blur' },
				],
				x_unit:[
					{ required: true, message: 'X轴单位不能为空', trigger: 'blur' },
				],
        y_title:[
					{ required: true, message: 'Y轴名称不能为空', trigger: 'blur' },
				],
				y_unit:[
					{ required: true, message: 'Y轴单位不能为空', trigger: 'blur' },
				],
        series_name: [
          { required: true, message: '系列名称不能为空', trigger: 'blur' },
        ]
      },

      openReplaceDialog: false,
      edbFromType: 0,
      replaceForm: {
        oldEdbName: '',
        item: {
          target_id: '',
          target_name: '',
          date: '',
          value: '',
          name: '',
        },
        index: '',
        type: ''
      },
    }
  },
  methods: {

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

		async searchApi(query,page=1) {
			let params = {
				KeyWord:query,
				CurrentIndex: page,
			}
			const res = (this.search_type==='x' && this.selectObj.xEdbFromType===0) || (this.search_type==='y' && this.selectObj.yEdbFromType===0)
				? await dataBaseInterface.targetSearchByPage(params)
				: await preDictEdbInterface.edbSearch(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(type,e) {
			this.search_page = 1;
			this.current_search = e.target.value;
      this.search_type = type;
			this.searchApi(this.current_search);
		},

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

    /* 选择指标 */
    selectTarget(val) {
      let item = this.searchOptions.find(_ => _.EdbInfoId === val);
      if(val) {
        if(this.search_type === 'x') {
           this.targetInfo.xEdbs.push({
            target_id: item.EdbInfoId,
            target_name: item.EdbName,
            date: item.LatestDate,
            value: item.LatestValue,
            name: item.EdbName,
          })

          this.form.series_name = this.form.series_name || this.targetInfo.xEdbs[0].date;
          this.form.x_unit = this.form.x_unit || item.Unit;
        }else {
          this.targetInfo.yEdbs.push({
            target_id: item.EdbInfoId,
            target_name: item.EdbName,
            date: item.LatestDate,
            value: item.LatestValue
          })

          this.form.y_unit = this.form.y_unit || item.Unit;
        }
        this.search_txt = '';
      }
    },

    /* 删除指标 */
    removeTarget(type,index) {
      type === 'x' ? this.targetInfo.xEdbs.splice(index,1) : this.targetInfo.yEdbs.splice(index,1);
    },

    /* 保存 */
    async saveHandle() {
      await this.$refs.formRef.validate();
      const { xEdbs,yEdbs } = this.targetInfo;
      if(!yEdbs.length || !xEdbs.length) return this.$message.warning('请选择指标');
      if(yEdbs.length > xEdbs.length) return this.$message.warning('Y轴添加指标数量不能超过X轴已添加指标数量');

      if(yEdbs.length !== xEdbs.length) await this.$confirm("X轴指标与Y轴指标数量不一致，图上仅绘制数量对应的指标，确认画图吗?", "操作提示", {
        type: "warning"
      });

      const { 
        x_title,
        x_unit,
        y_title,
        y_unit,
        series_name,
        color,
        x_date_type,
        x_date_value,
        x_date,
        y_date_type,
        y_date_value,
        y_date
      } = this.form;

      //处理数据结构
      let arr = xEdbs.map((item,index) => {
        if(yEdbs[index]){
          return {
            name: item.name,
            is_show: item.is_show || false,
            x_target_id: item.target_id,
            x_target_name: item.target_name,
            x_date_type,
            x_date,
            x_date_value: Number(x_date_value),
            y_target_id: yEdbs[index].target_id,
            y_target_name: yEdbs[index].target_name,
            y_date_type,
            y_date,
            y_date_value: Number(y_date_value),
          }
        }else {
          return null
        }
      }).filter(_ => _);

      // 参数格式
      let params = {
        x_title, 
        x_unit,
        y_title,
        y_unit,
        series_name,
        color,
        edbs: arr
      }
      this.$emit('saveCallback',params)
      this.cancelHandle()
    },

    init() {
      this.form = {
        x_title:'',
        x_unit:'',
        y_title:'',
        y_unit: '',
        series_name:'',
        color: defaultOpts.colors[0],
        x_date_type: 1,
        x_date_value: 0,
        x_date: '',
        y_date_type: 1,
        y_date_value: 0,
        y_date: '',
      }
      this.targetInfo = {
        xEdbs: [],
        yEdbs: []
      }
      this.selectObj = {
        xEdbFromType:0,
        yEdbFromType: 0,
      }
      this.$refs.formRef.resetFields();
    },

    /* 替换指标 */
    replaceTarget(item,index,type) {
      this.replaceForm.oldEdbName = item.target_name;
      this.replaceForm.index = index;
      this.replaceForm.type = type;
      this.openReplaceDialog = true;
    },

    replaceEdbChange(e) {
      if(e) {
        let item = this.searchOptions.find(_ => _.EdbInfoId === e);

        this.replaceForm.item = this.replaceForm.type === 'x' ? {
          target_id: item.EdbInfoId,
          target_name: item.EdbName,
          date: item.LatestDate,
          value: '',
          name: item.EdbName,
        } : {
          target_id: item.EdbInfoId,
          target_name: item.EdbName,
          date: item.LatestDate,
          value: '',
        }
      }else {
        this.replaceForm.item = { date: '' }
      }
    },

    /* 确定替换 */
    saveReplace() {
      if(!this.replaceForm.item.target_id) return this.$message('请选择替换指标')
      const { index,type,item } = this.replaceForm;

      type==='x' ? this.targetInfo.xEdbs.splice(index,1,item) : this.targetInfo.yEdbs.splice(index,1,item);
      this.cancelReplace()
    },

    cancelReplace() {
      this.replaceForm = {
        oldEdbName: '',
        item: {
          date:''
        },
        index: '',
        type: ''
      }
      this.openReplaceDialog = false
    },

    cancelHandle() {
      
      this.$emit("update:show", false);
    },
  }
}
</script>

<style scope lang="scss">
.target-wrapper {
  display: flex;
  height: 400px;
  margin-bottom: 30px;

  .tags-cont {
    width: 24%;
    border: 1px solid #DCDFE6;
    .tag-title {
      padding: 15px;
      border-bottom: 1px solid #DCDFE6;
      padding: 15px;
    }
    .tip {
      color: #C0C4CC;
      padding: 20px 15px;
    }
    .tag-ul {
      padding: 15px;
      max-height: 230px;
      overflow-y: auto;
    }
    .tag-item {
      padding: 0 15px;
      margin-bottom: 10px;
    }
  }
  .x-target-cont {
    width: 38%;
    border: 1px solid #DCDFE6;
    margin: 0 20px;
    &:last-child {
      margin: 0;
    }
    .tag-title {
      border-bottom: 1px solid #DCDFE6;
      padding: 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .targets-cont {
      padding-top: 15px;
      .targets-ul{
        padding: 15px;
        max-height: 230px;
        overflow-y: auto;
        .target-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10px;
          height: 27px;
        }
      }
    }
  }
}
.dia-bot {
  margin: 52px 0 30px;
  display: flex;
  justify-content: center;
}
</style>

<style lang="scss">
.satter-series-dialog {
  .tag-input .el-input__inner{
    height: 27px !important;
    line-height: 27px !important;
    padding: 0 20px 0 4px !important;
  }
  .el-date-editor .el-input__inner {
    padding: 0 4px 0 26px !important;
  }
}
</style>