<template>
  <div>
    <div class="search-input-container">
      <el-input :placeholder="searchPlaceholder" v-model="searchTemplate.keyword.value" icon="search"  @keyup.enter.native="search" :on-icon-click="search"></el-input>
      <el-button type="text" @click="showSearchPanel">
        高级
        <i class="el-icon-arrow-up" v-if="this.panelShown"></i>
        <i class="el-icon-arrow-down" v-else></i>
      </el-button>
    </div>
    <div class="advanced-search-panel" v-show="this.panelShown">

      <!-- 已选参数展示 -->
      <div v-if="showSelectedTags" class="options-selected">
        <template v-for="condition in conditionList">
          <el-tag v-if="condition.ctrltype === 'DateComponent' && (condition.optionList.def_min_value || condition.optionList.def_max_value)"
            :key="condition.fieldcode"
            :closable="true"
            type="gray"
            @close="cancelConditionSelection(condition.optionList)">
            {{formatSelectedDate(condition.optionList.def_min_value, condition.optionList.def_max_value)}}
          </el-tag>
          <el-tag v-if="condition.ctrltype === 'NumberComponent' && (condition.optionList.def_min_value || condition.optionList.def_max_value)"
            :key="condition.fieldcode"
            :closable="true"
            type="gray"
            @close="cancelConditionSelection(condition.optionList)"
          >
            {{formatSelectedNumber(condition.optionList.def_min_value, condition.optionList.def_max_value)}}
          </el-tag>
          <el-tag
            v-for="option in condition.optionList.options"
            :key="option.value"
            v-if="option.selected"
            :closable="true"
            type="gray"
            @close="cancelConditionSelection(condition.optionList)">
            {{option.name}}
          </el-tag>
        </template>
      </div>

      <!-- 搜索参数 -->
      <div>

        <!-- 前三条平铺条件 -->
        <div
          class="condition-row"
          v-for="(condition, index) in conditionList"
          :key="condition.fieldcode"
          v-if="index < 3">
          <!-- 条件名 -->
          <span class="condition-label">{{condition.fieldname}}:</span>
          <!-- 条件选项 -->
          <div class="condition-options">

            <!-- 通用选项 -->
            <template v-if="condition.optionList.options.length">
              <span
                v-for="option in condition.optionList.options"
                :key="option.value"
                class="condition-option"
                :class="{selected: option.selected}"
                @click="selectConditionOption(condition.optionList, option, condition.ctrltype)"
              >{{option.name}}</span>
            </template>

            <!-- 数值字段 -->
            <template v-if="condition.ctrltype === 'NumberComponent'">
              <div class="option-num-container">
                <el-input
                  v-model="condition.optionList.def_min_value"
                  @change="selectConditionOption(condition.optionList, null, condition.ctrltype)"
                  size="small"
                  placeholder="最小值">
                </el-input>
              </div>
                -
              <div class="option-num-container">
                <el-input
                  v-model="condition.optionList.def_max_value"
                  @change="selectConditionOption(condition.optionList, null, condition.ctrltype)"
                  size="small"
                  placeholder="最大值">
                </el-input>
              </div>
            </template>

            <!-- 日期字段 -->
            <template v-else-if="condition.ctrltype === 'DateComponent'">
              <div class="option-date-container">
                <el-date-picker
                  v-model="condition.optionList.def_min_value"
                  @change="selectConditionOption(condition.optionList, null,'DateComponent')"
                  type="datetime"
                  size="small"
                  placeholder="选择日期时间">
                </el-date-picker>
              </div>
                -
              <div class="option-date-container">
                <el-date-picker
                  v-model="condition.optionList.def_max_value"
                  @change="selectConditionOption(condition.optionList, null,'DateComponent')"
                  type="datetime"
                  size="small"
                  placeholder="选择日期时间">
                </el-date-picker>
              </div>
            </template>
          </div>
        </div>

        <!-- 高级条件 -->
        <div class="condition-row">
          <span class="condition-label">高级:</span>
          <!-- 条件名 -->
          <div class="advanced-conditions">
            <span v-for="(condition, index) in conditionList"
              v-if="index >= 3"
              class="advanced-condition"
              :class="{
                current: currentConditionCode === condition.fieldcode,
                selected: condition.optionList.feOptionSelected
              }"
              :key="condition.fieldcode"
              @click="setCurrentCondition(condition)">
              {{condition.fieldname}}
              <i class="el-icon-arrow-up" v-if="currentConditionCode === condition.fieldcode"></i>
              <i class="el-icon-arrow-down" v-else></i>
            </span>
          </div>
        </div>
      </div>

      <!-- 按钮 -->
      <div class="advanced-search-btns">
        <el-button type="primary" class="button-no-radius" @click="search">搜索</el-button>
        <el-button class="button-no-radius" @click="clearSelectedOptions">清空</el-button>
      </div>

      <!-- 当前选中的条件选项 -->
      <div class="current-condition-options-container">
        <div class="current-condition-options" v-if="currentCondition">

          <!-- 通用选项 -->
          <template v-if="currentCondition.optionList.options.length">
            <span
              v-for="option in currentCondition.optionList.options"
              :key="option.value"
              class="condition-option"
              :class="{selected: option.selected}"
              @click="selectConditionOption(currentCondition.optionList, option, currentCondition.ctrltype)"
            >{{option.name}}</span>
          </template>

          <!-- 数值字段 -->
          <template v-if="currentCondition.ctrltype === 'NumberComponent'">
            <div class="option-num-container">
              <el-input
                v-model="currentCondition.optionList.def_min_value"
                @change="selectConditionOption(currentCondition.optionList, null, currentCondition.ctrltype)"
                size="small"
                placeholder="最小值">
              </el-input>
            </div>
              -
            <div class="option-num-container">
              <el-input
                v-model="currentCondition.optionList.def_max_value"
                @change="selectConditionOption(currentCondition.optionList, null, currentCondition.ctrltype)"
                size="small"
                placeholder="最大值">
              </el-input>
            </div>
          </template>

          <!-- 日期字段 -->
          <template v-else-if="currentCondition.ctrltype === 'DateComponent'">
            <div class="option-date-container">
              <el-date-picker
                v-model="currentCondition.optionList.def_min_value"
                @change="selectConditionOption(currentCondition.optionList, null,'DateComponent')"
                type="datetime"
                size="small"
                placeholder="选择日期时间">
              </el-date-picker>
            </div>
              -
            <div class="option-date-container">
              <el-date-picker
                v-model="currentCondition.optionList.def_max_value"
                @change="selectConditionOption(currentCondition.optionList, null,'DateComponent')"
                type="datetime"
                size="small"
                placeholder="选择日期时间">
              </el-date-picker>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'IfbpSearch',
  props: {
    // 搜索模板对象
    searchTemplate: Object,

    // 是否显示已选中标签
    showSelectedTags: {
      type: Boolean,
      default: false
    },
  },
  data(){
    return {
      // 搜索面板显示
      panelShown: false,
      // 搜索框 placeholder
      searchPlaceholder: '',
      // 条件列表
      conditionList: [],
      // 当前打开的高级条件编号
      currentConditionCode: '',
      // 当前打开的高级条件内容
      currentCondition: null
    }
  },
  created() {
    this.searchPlaceholder = this.formatPlaceholder(this.searchTemplate.keyword.fields);
    this.conditionList = this.searchTemplate.conditionList;
    this.initConditionListStatus();
  },
  mounted(){
    // $(this.$el.parentNode).after(this.$el.querySelector('.advanced-search-panel'));
    var el = this.$el;
    var searchPanel = el.querySelector('.advanced-search-panel');
    var container = el.parentNode;
    container.parentNode.insertBefore(searchPanel, container.nextSibling);
  },
  methods:{
    // 触发搜索事件
    search() {
      this.panelShown = false;
      this.$emit('search', this.searchTemplate);
    },
    // 切换高级搜索显示状态
    showSearchPanel(){
      this.panelShown = !this.panelShown;
    },
    // 搜索框 placeholder
    formatPlaceholder(fields) {
      var keywords = [];
      for (var i = 0; i < fields.length; i++) {
        var keyword = fields[i].fieldname;
        if (keyword) {
          keywords.push(keyword);
        }
      }
      return '请输入' + keywords.join('/');
    },

    /**
      * 高级搜索
      */

    //  获取数据后检查是否有选中选项, 用以高亮已选条件
    initConditionListStatus() {
      var conditionList = this.conditionList;
      for (var i = 3; i < conditionList.length; i++) { // 第四条开始
        var condition = conditionList[i];
        var optionList = condition.optionList;
        var options = optionList.options;
        this.$set(optionList, 'feOptionSelected', false);
        // optionList.feOptionSelected = false;
        if (!optionList) {
          continue;
        }
        if (optionList.def_min_value || optionList.def_max_value) {
          // console.log(optionList.def_min_value, optionList.def_max_value);
          optionList.feOptionSelected = true;
          continue;
        }
        for (var j = 0; j < options.length; j++) {
          var option = options[j];
          if (!option) {
            continue;
          }
          if (option.selected) {
            optionList.feOptionSelected = true;
            continue;
          }
        }
      }
    },

    // 设置选中
    selectConditionOption(optionList, option, ctrltype) {
      // console.log(arguments);
      var optionSelected = false;
      var options = optionList.options;
      if (option && option.selected) {
        optionSelected = true;
      }
      if (!optionList.def_min_value && !optionList.def_max_value && (!option || option.selected)) {
        optionList.feOptionSelected = false;
      } else {
        optionList.feOptionSelected = true;
      }
      if (ctrltype === 'DateComponent') {
        if (!optionList.def_min_value && !optionList.def_max_value && !option) { // 修复 el-date-picker 置空时引起的bug
          return;
        }
        if (optionList.def_min_value) {
          optionList.def_min_value = this.formatDate(optionList.def_min_value);
        }
        if (optionList.def_max_value) {
          optionList.def_max_value = this.formatDate(optionList.def_max_value);
        }
      }
      for (var i = 0; i < options.length; i++) {
        options[i].selected = false;
      }
      if (option) {
        option.selected = !optionSelected;
        optionList.def_min_value = null;
        optionList.def_max_value = null;
        this.setCurrentCondition();
      }
    },

    // 已选中日期格式整理
    formatSelectedDate(startDay, endDay) {
      var dateString = '';
      // 改到 el-date-picker@change 时修改
      // if (startDay) {
      //   startDay = this.formatDate(startDay);
      // }
      // if (endDay) {
      //   endDay = this.formatDate(endDay);
      // }
      if (startDay && endDay) {
        dateString = startDay + ' 至 ' + endDay;
      } else if (startDay) {
        dateString = startDay + '之后';
      } else {
        dateString = endDay + '之前';
      }
      return dateString;
    },

    // 已选中数值格式整理
    formatSelectedNumber(min, max) {
      if (min && max) {
        return min + '-' + max + '万元';
      } else if (min) {
        return min + '万元及以上';
      } else {
        return '低于' + max + '万元';
      }
    },

    // 整理date格式
    formatDate(time) {
      var date = new Date(time);
      return date.getFullYear() + '-' + ((date.getMonth()) >= 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1)) + '-' + (date.getDate() > 9 ? date.getDate() : ('0' + date.getDate())) + ' ' + (date.getHours() > 9 ? date.getHours() : ('0' + date.getHours())) + ':' + (date.getMinutes() > 9 ? date.getMinutes() : ('0' + date.getMinutes())) + ':' + (date.getSeconds() > 9 ? date.getSeconds() : ('0' + date.getSeconds()));
    },

    // 取消选中
    cancelConditionSelection(optionList) {
      var options = optionList.options;
      for (var i = 0; i < options.length; i++) {
        options[i].selected = false;
      }
      optionList.feOptionSelected = false;
      optionList.def_min_value = null;
      optionList.def_max_value = null;
      this.setCurrentCondition();
    },

    // 设置当前选中的高级条件
    setCurrentCondition(condition) {
      if (!condition || (this.currentConditionCode === condition.fieldcode)) {
        this.currentConditionCode = '';
        this.currentCondition = null;
      } else {
        this.currentConditionCode = condition.fieldcode;
        this.currentCondition = condition;
      }
    },

    // 点击清空按钮
    clearSelectedOptions() {
      var conditions = this.conditionList;
      for (var i = 0; i < conditions.length; i++) {
        this.cancelConditionSelection(conditions[i].optionList);
      }
    },
  }
};
</script>
<style>

  /* 搜索框 */
  .search-input-container {
    margin-right: 16px;
  }

  /* 高级搜索 */
  .advanced-search-panel {
    position: relative;
    padding: 0 16px 16px;
    background-color: #ffffff;
    border-top: 1px solid #e3e3e3;
  }
  .advanced-search-panel .condition-row {
    line-height: 40px;
    display: flex;
    margin-right: 150px;
  }
  .advanced-search-panel .condition-label {
    display: inline-block;
    width: 7em;
    text-align: right;
    margin-right: 8px;
    color: #888888;
    white-space: nowrap;
    font-size: 14px;
  }
  .advanced-search-panel .condition-options,
  .advanced-search-panel .advanced-conditions {
    text-align: left;
  }
  .advanced-search-panel .current-condition-options-container {
    padding: 0 16px;
    z-index: 2;
    position: absolute;
    top: 100%;
    left: 0;
    width: 100%;
    transform: translateY(-23px);
  }
  .advanced-search-panel .current-condition-options {
    padding: 10px 20px;
    border: 1px solid #20a0ff;
    background: #ffffff;
  }
  .advanced-search-panel .current-condition-options .condition-option {
    display: inline-block;
    height: 30px;
    padding: 0 6px;
    line-height: 30px;
  }

  .advanced-search-panel .condition-options,
  .advanced-search-panel .advanced-conditions {
    flex: 1;
    color: #666666;
    font-size: 14px;
  }
  .advanced-search-panel .condition-option,
  .advanced-search-panel .advanced-condition {
    margin-right: 16px;
    padding: 4px 8px;
    box-sizing: border-box;
    cursor: pointer;
  }
  .advanced-search-panel .advanced-conditions-container .el-col {
    margin-bottom: 0;
  }
  .advanced-search-panel .condition-option:hover,
  .advanced-search-panel .condition-option.selected {
    cursor: pointer;
    color: #ffffff;
    background: #20a0ff;
  }
  .advanced-search-panel .param-price-input {
    width: 5em;
  }
  .advanced-search-panel .option-num-container {
    display: inline-block;
    width: 5em;
  }
  .advanced-search-panel .option-date-container {
    display: inline-block;
    width: 180px;
  }
  .advanced-search-panel .options-selected {
    text-align: left;
  }
  .advanced-search-panel .options-selected .el-tag {
    margin-bottom: 5px;
    margin-right: 5px;
  }
  .advanced-search-panel .advanced-condition {
    word-break: keep-all;
  }
  .advanced-search-panel .advanced-condition.current {
    border: 1px solid #20a0ff;
    border-bottom-color: #ffffff;
    background: #ffffff;
    position: relative;
    z-index: 3;
    margin-left: -2px;
  }
  .advanced-search-panel .advanced-condition.selected,
  .advanced-search-panel .advanced-condition.selected i {
    color: #20a0ff;
  }
  .advanced-search-panel .advanced-condition i {
    color: #C8C8CD;
    transform: scale(0.7);
  }
  .advanced-search-panel .advanced-search-btns {
    position: absolute;
    right: 16px;
    bottom: 16px;
    text-align: right;
  }
</style>