<template>
  <div class="tpl-edit-container">
    <!-- title -->
    <ifbp-breadcrumb name="搜索模板明细"></ifbp-breadcrumb>
    <div class="page-operators">
      <el-button type="primary" @click="tplSave">保存</el-button>
      <el-button type="primary" @click="goBack">取消</el-button>
    </div>

    <!-- 主体区域 -->
    <div class="form-container">
      <!-- 基本信息 -->
      <div class="form-title"><i class="ifbp-icon-create-square"></i>基本信息</div>
      <ifbp-template ref="basicInfoForm"
        :pk-temp="formTplPk"
        show-type="form"
        :tpl-data="formTplData"
        :editable="true">
      </ifbp-template>

      <!-- 搜索条件配置 -->
      <div class="form-title"><i class="ifbp-icon-menu"></i>关键字配置</div>
      <!-- 关键字 -->
      <el-form label-width="150px">
        <el-form-item label="关键字搜索" style="width: 400px;">
          <el-select
            v-model="selectedKeywords"
            multiple
            :multiple-limit="5"
            placeholder="支持最多五个文本型字段"
          >
            <el-option
              v-for="(item, index) in keywordsToChoose"
              :key="index"
              :label="item.fieldname"
              :value="item.fieldcode">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 搜索条件配置 -->
      <div class="form-title"><i class="ifbp-icon-menu"></i>搜索条件配置</div>
      <!-- 条件 -->
      <el-row class="condition-row condition-title-row">
        <el-col :span="3">元数据条件</el-col>
        <el-col :span="3">条件显示名称</el-col>
        <el-col :span="15">条件选项</el-col>
        <el-col :span="3">操作列</el-col>
      </el-row>
      <el-row class="condition-row"
        v-for="(condition, conditionIndex) in currentTpl.conditionList"
        :key="conditionIndex">
        <!-- 高级选项开始时展示的分隔行 -->
        <el-row
          v-if="conditionIndex === conditionsBeforeAdvance"
          class="advanced-label">高级选项</el-row>
        <!-- 条件名 -->
        <el-col :span="3">
          <el-select
            class="condition-name"
            v-model="condition.fieldcode"
            @change="selectedConditionChange"
            placeholder="请选择条件"
            v-if="condition.ifcustom"
            title="自定义条件"
            disabled
          >
            <el-option :label="condition.fieldname" :value="condition.fieldcode"></el-option>
          </el-select>
          <el-select
            class="condition-name"
            v-model="condition.fieldcode"
            @change="selectedConditionChange"
            placeholder="请选择条件"
            v-else
            :disabled="condition.ifcustom"
          >
            <el-option
              v-for="(item, indexToChoose) in conditionsToChoose"
              :key="indexToChoose"
              v-if="(selectedConditions.indexOf(item.fieldcode) === -1) || (condition.fieldcode === item.fieldcode)"
              :label="item.fieldname"
              :value="item.fieldcode"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-input v-model="condition.fieldname"
            placeholder="条件显示名"
            class="condition-name"></el-input>
        </el-col>
        <!-- 条件内容 -->
        <el-col class="options" :span="15">
          <!-- 自定义多选且非Boolean, 显示新增按钮 -->
          <i
            class="ifbp-icon-create-square"
            v-if="condition.fieldcode && (condition.ctrltype !== 'Select' || (condition.ifcustom && condition.ctrltype === 'Select' && condition.fieldtype !== 'tinyint'))"
            @click="editOption(condition, null, $event)"
          ></i>

          <!-- 添加系统变量 -->
          <el-button
            v-if="condition.ctrltype === 'DateTime'"
            class="fr btn-system-variable"
            type="primary"
            @click="addSystemVariable(condition)"
          >添加系统变量</el-button>

          <div class="option-container"
            v-for="(option, optionIndex) in condition.optionList.options"
            :key="optionIndex"
          >
            <!-- select 类型仅展示 -->
            <!-- <div class="option" v-if="condition.ctrltype === 'Select'">{{ option.name }}</div> -->
            <!-- datetime 中系统变量仅支持删除 -->
            <!-- <div
              class="option"
              v-if="condition.ctrltype === 'DateTime' && option.value && option.issysflag"
              title="系统变量不可修改"
            >
              {{ option.name }}
              <i class="ifbp-icon-power-off"
                v-if="condition.ctrltype !== 'Select'"
                @click.stop="removeOption(condition.optionList.options, optionIndex)"
              ></i>
            </div> -->
            <!-- 非系统变量的选项可以修改 -->
            <div
              class="option"
              :class="{
                'editable': !option.issysflag
              }"
              @click="editOption(condition, option, $event, option.issysflag)"
            >
              {{ option.name }}
              <!-- 除Boolean和非自定义多选外, 显示删除按钮 -->
              <i class="ifbp-icon-power-off"
                v-if="condition.ctrltype !== 'Select' || (condition.ifcustom && condition.ctrltype === 'Select' && condition.fieldtype !== 'tinyint')"
                @click.stop="removeOption(condition.optionList.options, optionIndex, option.issysflag)"
              ></i>
            </div>
          </div>
        </el-col>
        <!-- 操作区 -->
        <el-col :span="3" class="condition-oprators">
          <el-tooltip placement="top">
            <div slot="content">上移</div>
            <i class="ifbp-icon-caret-up" @click="conditionMoveUp(conditionIndex)"></i>
          </el-tooltip>
          <el-tooltip placement="top">
            <div slot="content">下移</div>
            <i class="ifbp-icon-caret-down" @click="conditionMoveDown(conditionIndex)"></i>
          </el-tooltip>
          <el-tooltip placement="top">
            <div slot="content">删除</div>
            <i class="ifbp-icon-close" @click="conditionDelete(conditionIndex)"></i>
          </el-tooltip>
        </el-col>
      </el-row>
      <el-row class="condition-row">
        <!-- <el-col :span="3" v-if="currentTpl.conditionList.length < conditionsToChoose.length"> -->
        <el-col :span="6">
          <!-- <el-tooltip placement="top">
            <div slot="content">新增条件</div>
            <i class="ifbp-icon-plus-square" @click="conditionAdd"></i>
          </el-tooltip> -->
          <el-button
            type="primary"
            @click="conditionAdd"
          >新增预置条件</el-button>

          <!-- 添加自定义条件 -->
          <el-button
            type="primary"
            @click="addCustomCondition"
          >新增自定义条件</el-button>
        </el-col>
      </el-row>
    </div>

    <div id="optionEdittingArea" class="option-editting-area">
      <el-form label-width="100px" v-if="edittingOption" inline>
        <el-form-item label="候选项名称:">
          <el-input v-model="edittingOption.name" placeholder="请输入"></el-input>
        </el-form-item>
        <template v-if="edittingCondition.ctrltype === 'NumberComponent'">
          <el-form-item label="区间最小值:">
            <el-input v-model="edittingOption.min_value" type="number" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="区间最大值:">
            <el-input v-model="edittingOption.max_value" type="number" placeholder="请输入"></el-input>
          </el-form-item>
        </template>
        <template v-if="edittingCondition.ctrltype === 'DateTime'">
          <el-form-item label="区间最小值:">
            <el-date-picker
              v-model="edittingOption.min_value"
              @change="handleDateChange('min_value', $event)"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="区间最大值:">
            <el-date-picker
              v-model="edittingOption.max_value"
              @change="handleDateChange('max_value', $event)"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </template>
        <template v-if="edittingCondition.ctrltype === 'Reference'">
          <span class="form-tips" v-if="edittingCondition.refcode === 'ERROR'">当前参照未配置refcode, 请配置其他条件</span>
          <el-form-item v-else label="参照值:">
            <el-ref
              :is-muti-select="true"
              :ref-code="edittingCondition.refcode"
              field="value"
              :template-value="edittingOption"
              width="300px"
              :is-edit="true"
              @trigger="handleRefTrigger"
              ref="edittingRef"
            >
            </el-ref>
          </el-form-item>
        </template>
        <template v-if="edittingCondition.ctrltype === 'Select'">
          <el-form-item label="候选项值:">
            <el-input v-model="edittingOption.value"
              placeholder="请输入"
              :disabled="edittingCondition.fieldtype === 'tinyint' || (!edittingCondition.ifcustom && edittingCondition.ctrltype === 'Select')"
            ></el-input>
          </el-form-item>
        </template>
      </el-form>
      <el-row class="option-operators">
        <i class="ifbp-icon-success confirm" @click="optionConfirm"></i>
        <i class="ifbp-icon-power-off cancel" @click="optionCancel"></i>
      </el-row>
    </div>

    <!--条件删除确认 Dialog-->
    <ifbp-del-dialog
      v-model="delDialogVisible"
      message="确认删除该条件？"
      @click="deleteConfirm"
      >
    </ifbp-del-dialog>

    <!-- 添加系统变量 Dialog -->
    <el-dialog title="添加系统变量" :modal="false" v-model="sysVarDialogVisible" @close="sysVarCancel">
      <el-form label-width="100px" ref="editForm" v-if="edittingOption">
        <el-form-item label="系统变量:">
          <el-select
            v-model="edittingOption.value"
            placeholder="请选择"
            @change="sysVarSelected"
          >
            <!-- 筛除已选择系统变量 -->
            <el-option
              v-for="(sysVar, sysVarIndex) in sysVarOptions"
              v-if="sysVar.code === edittingOption.value || (edittingCondition && edittingCondition._fe_selectedSysVars && edittingCondition._fe_selectedSysVars.indexOf(sysVar.code) === -1)"
              :key="sysVarIndex"
              :label="sysVar.name"
              :value="sysVar.code"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sysVarCancel">取 消</el-button>
        <el-button type="primary" @click="sysVarConfirm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加自定义条件 Dialog -->
    <el-dialog title="添加自定义条件" :modal="false" v-model="customConditionDialogVisible" @close="customConditionCancel">
      <el-form :model="customCondition" :rules="customConditionRules" ref="customConditionForm" label-width="100px">
        <el-form-item label="条件编码" prop="fieldcode">
          <el-input v-model="customCondition.fieldcode"></el-input>
        </el-form-item>
        <el-form-item label="条件名" prop="fieldname">
          <el-input v-model="customCondition.fieldname"></el-input>
        </el-form-item>
        <el-form-item label="条件类型" prop="fieldtype">
          <el-select v-model="customCondition.fieldtype"
            placeholder="请选择条件类型"
            @change="getSysRefOptions">
            <el-option label="日期" value="datetime"></el-option>
            <el-option label="数值" value="decimal"></el-option>
            <el-option label="布尔" value="tinyint"></el-option>
            <el-option label="枚举" value="varchar"></el-option>
            <el-option label="参照" value="ref"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参照类型" prop="refcode" v-if="Array.isArray(sysRefOptions) && sysRefOptions.length && customCondition.fieldtype === 'ref'">
          <el-select v-model="customCondition.refcode" placeholder="请选择refcode">
            <el-option v-for="ref in sysRefOptions"
              :key="ref.pk_ref"
              :label="ref.refname + ' ' + ref.refcode"
              :value="ref.refcode"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="customConditionCancel">取 消</el-button>
        <el-button type="primary" @click="customConditionConfirm">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>


<script>
import searchTplObj from './testSearchTemplate.json';

export default {
  data() {
    var currentTplId = this.$route.params.id;
    var treeCode = this.$route.params.treecode;
    var refCode = this.$route.params.refcode;
    var refId = this.$route.params.refid;
    var isCreate = false;

    var currentPath = this.$route.path; // 当前 router path
    if (currentPath.indexOf('searchTplCreate') !== -1) {
      isCreate = true;
    }

    return {
      /**
       * UI 模板相关
       */
      formTplPk: 'e42aba51-e0d7-494f-a606-4377932ab4b9',
      formTplData: {
        SMQueryTemplateEntity: {},
        rules: {
          code: [{
            required: true,
            message: "编码不能为空",
            trigger: "blur"
          }],
          name: [{
            required: true,
            message: "名称不能为空",
            trigger: "blur"
          }]
        }
      },
      /**
       * 页面传参相关
       */
      // 是否新建
      isCreate: isCreate,
      // 当前编辑模板id
      currentTplId: currentTplId,
      // 树节点对应的code
      treeCode: treeCode,
      // 参照对应的code
      refCode: refCode,
      // 参照对应的id
      refId: refId,


      // 数据对象
      currentTpl: {
        template: null,
        keyword: {
          value: null,
          fields: []
        },
        schema: null,
        conditionList: []
      },

      /**
       * 搜索先关配置
       */
      // 高级搜索前展示的条数, 默认3
      conditionsBeforeAdvance: 3,
      // 关键字相关
      // 可选关键字
      keywordsToChoose: [],
      // 已选中搜索关键字的 model
      selectedKeywords: [],
      // 条件相关
      // 已添加条件
      selectedConditions: [],
      // 可选择条件
      conditionsToChoose: [],
      // 选项相关
      // 当前编辑中的
      edittingCondition: null,
      // 当前编辑中的选项
      // 当前编辑选项的序号, 新增为new, 修改为对应选项的 dispsequence
      edittingConditionIndex: null,
      edittingOption: null,
      // 当前编辑选项的序号, 新增为new, 修改为对应选项的 dispsequence
      edittingOptionIndex: null,

      // 删除相关
      // 删除提示框
      delDialogVisible: false,
      // 需要删除的序号
      delIndex: null,

      // 添加系统变量相关
      // 添加系统变量对话框是否显示
      sysVarDialogVisible: false,
      // 系统变量选项mock数据
      sysVarOptions: [],

      /**
       * 自定义条件相关
       */
      // dialog
      customConditionDialogVisible: false,
      // 所有参照列表
      sysRefOptions: [],
      // 自定义条件对象
      customCondition: {},
      customConditionRules: {
        fieldcode: [
          {
            required: true, trigger: 'change',
            validator(rule, value, callback) {
              if (!value) {
                callback(new Error('refcode 不能为空'));
              }
              if (value.length > 20) {
                callback(new Error('refcode 不能超过 20 位'));
              }
              if (/^[a-zA-Z0-9_.]+$/.test(value)) {
                callback();
              } else {
                callback(new Error('refcode 只能包含英文数字下划线和点'));
              }
            }
          }
        ],
        fieldname: [
          { required: true, message: 'fieldname 不能为空', trigger: 'change' }
        ],
        fieldtype: [
          { required: true, message: '请选择 fieldtype', trigger: 'change' }
        ],
        refcode: [
          { required: true, message: '请选择 refcode', trigger: 'change' }
        ],
      },
    };
  },
  computed: {
    sysConditionCount() {

    }
  },
  methods: {

    // 获取模板
    requestSearchTpl() {
      this.selectedKeywords = [];
      this.selectedConditions = [];
      this.conditionsToChoose = [];

      if (this.isCreate) { // 新建
        var requestUrl = '/ifbp-app-sm-qt-web/quyerTemplate/toCreate';
        var requestData = {
          busicode: this.treeCode,
          sceneCode: this.refCode,
          pkScene: this.refId
        };

        this.$http({
          url: requestUrl,
          method: 'post',
          data: requestData,
          dataType: 'json'
        })
          .then(res => {
            if (res.data.success) {
              var resData = res.data.data;
              if (resData) {
                if (resData.template) {
                  this.formTplData.SMQueryTemplateEntity = resData.template;
                  this.$nextTick(() => {
                    if (this.$refs.basicInfoForm) {
                      this.$refs.basicInfoForm.setFormData(this.formTplData.SMQueryTemplateEntity);
                    } else {
                      this.$set(this.basicInfoForm, 'SMQueryTemplateEntity', this.formTplData.SMQueryTemplateEntity);
                    }
                  });
                }
                if (resData.keyword) {
                  this.keywordsToChoose = resData.keyword.fields;
                  this.currentTpl.keyword.value = resData.keyword.value;
                }
                if (resData.candidateConditionList) {
                  this.conditionsToChoose = resData.candidateConditionList;
                }
              }
            }
            this.showError(res, '新建搜索模板失败: ');
          })
          .catch(() => {
            this.$message({
              message: '新建搜索模板失败',
              type: 'error'
            });
          });

      } else { // 修改
        // request { id: currentTplId }
        var requestUrl = '/ifbp-app-sm-qt-web/quyerTemplate/toUpdate';
        this.$http({
          url: requestUrl,
          method: 'post',
          data: this.currentTplId,
          dataType: 'json',
          headers: {
            'Content-Type': 'application/json'
          }
        })
          .then(res => {
            if (res.data.success) {
              var resData = res.data.data;
              if (resData) {
                if (resData.template) {
                  this.formTplData.SMQueryTemplateEntity = resData.template;
                  this.$nextTick(() => {
                    if(this.$refs.basicInfoForm) {
                      this.$refs.basicInfoForm.setFormData(this.formTplData.SMQueryTemplateEntity);
                    } else {
                      this.$set(this.basicInfoForm, 'SMQueryTemplateEntity', this.formTplData.SMQueryTemplateEntity);
                    }
                  });
                }
                if (resData.keyword) {
                  this.keywordsToChoose = resData.keyword.fields;
                  this.currentTpl.keyword.value = resData.keyword.value;
                  for (let i = 0; i < this.keywordsToChoose.length; i++) {
                    let keyword = this.keywordsToChoose[i];
                    if (keyword.iskeyword) {
                      this.selectedKeywords.push(keyword.fieldcode);
                    }
                  }
                }
                if (resData.candidateConditionList) {
                  this.conditionsToChoose = resData.candidateConditionList;
                }
                if (resData.conditionList && resData.conditionList.length) {
                  for (let i = 0; i < resData.conditionList.length; i++) {
                    var condition = resData.conditionList[i];
                    if (condition.fieldcode) {
                      this.selectedConditions.push(condition.fieldcode);
                    }
                    if (!condition.optionList) {
                      condition.optionList = {
                        def_min_value: null,
                        def_max_value: null,
                        options: []
                      };
                    } else if (!condition.optionList.options) {
                      condition.optionList.options = [];
                    }
                  }
                  this.currentTpl.conditionList = resData.conditionList;
                }
              }
            }
            this.showError(res, '获取模板信息失败: ');
          })
          .catch(() => {
            this.$message({
              message: '获取模板信息失败',
              type: 'error'
            });
          });
      }

    },

    // 条件名变化
    selectedConditionChange(val) {
      if (!this.selectedConditions || this.selectedConditions.indexOf(val) !== -1) { // fix 条件行上下移时 bug
        return;
      }
      var tempCondition;
      for (var i = 0; i < this.conditionsToChoose.length; i++) {
        var condition = this.conditionsToChoose[i];
        if (condition.fieldcode === val) {
          tempCondition = condition;
          if (condition.ctrltype === 'Reference' && condition.refcode === 'ERROR') {
            this.$message({
              message: condition.fieldname + '字段未配置 refcode, 请配置其他条件',
              type: 'error'
            });
          }
          break;
        }
      }

      // 重置所在条件行的内容
      this.selectedConditions = [];
      for (let i = 0; i < this.currentTpl.conditionList.length; i++) {
        var condition = this.currentTpl.conditionList[i];
        // 重置已选条件数组
        this.selectedConditions[i] = condition.fieldcode;
        if (condition.fieldcode === val) {
          condition.optionList.options = [];
          condition.optionList.def_min_value = null;
          condition.optionList.def_max_value = null;
          for (let key in tempCondition) {
            if (key !== 'optionList' && key !== 'dispsequence') {
              condition[key] = tempCondition[key];
            }
          }
          if (tempCondition.ctrltype === 'Select') {
            condition.optionList.options = tempCondition.optionList.options;
          }
        }
      }
    },

    // 上移行
    conditionMoveUp(index) {
      if (!this.checkUnfinishedCondition()) {
        return;
      }
      this.optionCancel();
      if (index === 0) {
        return;
      }
      var conditionToMove = this.currentTpl.conditionList.splice(index, 1)[0];
      this.currentTpl.conditionList.splice(index - 1, 0, conditionToMove);
      this.reorderConsitions();
    },

    // 下移行
    conditionMoveDown(index) {
      if (!this.checkUnfinishedCondition()) {
        return;
      }
      this.optionCancel();
      if (index === this.currentTpl.conditionList.length - 1) {
        return;
      }
      var conditionToMove = this.currentTpl.conditionList.splice(index, 1)[0];
      this.currentTpl.conditionList.splice(index + 1, 0, conditionToMove);
      this.reorderConsitions();
    },

    // 删除行
    conditionDelete(index) {
      this.optionCancel();
      this.delDialogVisible = true;
      this.delIndex = index;
    },

    // 确认删除行
    deleteConfirm() {
      // 防止编辑区被删除
      $('.form-container').append($('#optionEdittingArea'));
      this.currentTpl.conditionList.splice(this.delIndex, 1);
      this.reorderConsitions();
      this.delIndex = null;
      this.delDialogVisible = false;
    },

    // 添加条件行
    conditionAdd() {
      if (!this.checkUnfinishedCondition()) {
        return;
      }
      var conditionToAdd = {
        fieldcode: null,
        fieldname: null,
        fieldtype: null,
        ctrltype: null,
        dispsequence: this.currentTpl.conditionList.length,
        ifmust: false,
        ifdatapower: false,
        refcode: null,
        enumname: null,
        iskeyword: false,
        optionList: {
          def_min_value: null,
          def_max_value: null,
          options: []
        }
      };
      this.currentTpl.conditionList.push(conditionToAdd);
    },

    // 检查是否有未编辑的条件
    checkUnfinishedCondition() {
      var tConditions = this.currentTpl.conditionList;
      var lastCondition = tConditions[tConditions.length - 1];
      if (lastCondition && !lastCondition.fieldcode) {
        this.$message('当前有空条件未编辑, 请先编辑或删除该条件');
        return false;
      }
      return true;
    },

    // 修改条件的排序值 (并重置已选条件数组)
    reorderConsitions() {
      if (!this.currentTpl) {
        return;
      }
      var conditions = this.currentTpl.conditionList;
      this.selectedConditions = [];
      for (var i = 0; i < conditions.length; i++) {
        conditions[i].dispsequence = i;
        this.selectedConditions[i] = conditions[i].fieldcode;
      }
    },

    // 修改条件选项
    editOption(condition, option, event, issysflag) {
      if (issysflag) {
        return;
      }
      this.edittingCondition = condition;
      if (condition.ctrltype === 'DateTime') {
        this.setSelectedSysVars();
      }
      this.edittingConditionIndex = condition.dispsequence;

      this.edittingOption = {
        min_value: null,
        max_value: null,
        value: null,
        name: null,
        dispsequence: condition.optionList.options.length + '',
        selected: false,
        issysflag: false,
        beanMap: {
          value_ref: {}
        }
      };

      if (option) { // 修改
        for (let key in option) {
          if (key === 'beanMap' && option[key] && option[key].value_ref) {
            this.edittingOption.beanMap.value_ref = option.beanMap.value_ref;
          } else {
            this.edittingOption[key] = option[key];
          }
        }
        this.edittingOptionIndex = +option.dispsequence;
      } else { // 新增
        if (this.$refs.edittingRef && this.$refs.edittingRef.reset) {
          this.$refs.edittingRef.reset();
        }
        this.edittingOptionIndex = 'new';
      }
      if (event && event.target) {
        // append editting area
        $(event.target).parents('.condition-row').append($('#optionEdittingArea'));
        // show editting area
        $('#optionEdittingArea').show();
      }
    },

    // 删除条件选项
    removeOption(optionList, index, issysflag) {
      if (issysflag) {
        return;
      }
      optionList.splice(index, 1);
      for (var i = 0; i < optionList.length; i++) {
        if (optionList[i]) {
          optionList[i].dispsequence = i + '';
        }
      }
      this.optionCancel();
    },

    // 确认选项编辑
    optionConfirm() {
      if (!this.edittingOption.name) {
        this.$message('请输入备选项名称');
        return;
      }
      if (this.edittingCondition.refcode === 'ERROR') {
        this.$message({
          message: '该字段未配置 refcode, 请配置其他条件',
          type: 'error'
        });
        this.optionCancel();
        return;
      }
      if (this.edittingOptionIndex === 'new') {
        this.edittingCondition.optionList.options.push(JSON.parse(JSON.stringify(this.edittingOption)));
      } else {
        this.edittingCondition.optionList.options.splice(this.edittingOptionIndex, 1, JSON.parse(JSON.stringify(this.edittingOption)));
      }
      this.optionCancel();
    },

    // 取消选项编辑
    optionCancel() {
      $('#optionEdittingArea').hide();
      this.edittingCondition = null;
      this.edittingConditionIndex = null;
      this.edittingOption = null;
      this.edittingOptionIndex = null;
    },

    // 处理参照事件
    handleRefTrigger(type, data) {
      if (this.edittingCondition.ctrltype !== 'Reference') {
        return;
      }
      if (type === 'change' && data && data.value && data.value.length) {
        const refArr = data.value;
        this.edittingOption.beanMap.value_ref = {};
        for (let i = 0; i < refArr.length; i++) {
          const refCode = refArr[i].id;
          const refName = refArr[i].refname;
          this.edittingOption.beanMap.value_ref[refCode] = {
            id: refCode,
            name: refName
          };
        }
      }
    },

    // 日期变化
    handleDateChange(key, val) {
      this.edittingOption[key] = val;
    },

    // 保存编辑
    tplSave() {
      var basicInfoFormValid = false;
      this.$refs.basicInfoForm.getFormComp().validate(valid => {
        if (valid) {
          basicInfoFormValid = true;
          this.currentTpl.template = this.$refs.basicInfoForm.comp.SMQueryTemplateEntity;
        }
      });
      if (!basicInfoFormValid) {
        return;
      }
      // 校验关键字
      var allKeywords = this.keywordsToChoose;
      var selectedKeywords = this.selectedKeywords;

      // 添加不配置关键字时的情况
      // if (!this.selectedKeywords.length) {
      //   this.$message({
      //     message: '搜索关键字不能为空',
      //     type: 'error'
      //   });
      //   return;
      // }

      // 设置选中关键字
      for (let i = 0; i < allKeywords.length; i++) {
        var keyword = allKeywords[i];
        if (this.selectedKeywords && this.selectedKeywords.indexOf(keyword.fieldcode) !== -1) {
          keyword.iskeyword = true;
          this.currentTpl.keyword.fields.push(keyword);
        }
      }

      // 检查 pk_scene
      if (this.isCreate && typeof this.currentTpl.template.pk_scene !== undefined) {
        delete this.currentTpl.template.pk_scene;
      }

      // 删除条件选项中的 beanMap
      var conditions = this.currentTpl.conditionList;
      for (let i = 0; i < conditions.length; i++) {
        var condition = conditions[i];
        delete condition._fe_selectedSysVars;
        // if (condition.ctrltype !== 'Reference') {
          var keywords = condition.optionList.options;
          for (let j = 0; j < keywords.length; j++) {
            if (keywords[j].beanMap) {
              delete keywords[j].beanMap;
            }
          }
        // }
      }

      // 如果最后一条条件什么都没配置, 那么去除该条件
      if (conditions && conditions.length) {
        var lastCondition = conditions[conditions.length - 1];
        if (!lastCondition.fieldcode) {
          conditions.splice(conditions.length - 1, 1);
        }
      }

      var requestUrl = '/ifbp-app-sm-qt-web/quyerTemplate/save';
      var requestData = this.currentTpl;

      this.$http({
        url: requestUrl,
        method: 'post',
        data: requestData,
        dataType: 'json'
      })
        .then(res => {
          if (res.data.success) {
            this.goBack();
          }
          this.showError(res, '保存搜索模板失败: ');
        })
        .catch(() => {
          this.$message({
            message: '保存搜索模板失败',
            type: 'error'
          });
        });
    },

    // 返回
    goBack() {
      this.$router.push({
        path: '/searchTplMgr',
        params: {
          treeCode: this.treeCode
        }
      });
    },

    // 系统变量相关
    // 显示 dialog
    addSystemVariable(condition) {
      // 设置当前编辑项
      this.editOption(condition);
      this.edittingOption.issysflag = true;
      // 如果已经存在系统变量选项, 则不进行重复请求
      if (this.sysVarOptions && this.sysVarOptions.length) {
        this.sysVarDialogVisible = true;
        return;
      }
      const requestUrl = '/ifbp-app-sm-qt-web/sysVariable/queryAll';
      this.$http({
        url: requestUrl,
        method: 'post',
        dataType: 'json'
      })
        .then(res => {
          if (res.data.success) {
            this.sysVarOptions = res.data.data;
            this.sysVarDialogVisible = true;
          }
          this.showError(res, '获取系统变量失败: ');
        })
        .catch(() => {
          this.$message({
            message: '获取系统变量失败',
            type: 'error'
          });
        });
    },

    // 改变系统变量事件
    sysVarSelected(val) {
      for (let i = 0; i < this.sysVarOptions.length; i++) {
        let option = this.sysVarOptions[i];
        if (val === option.code) {
          this.edittingOption.name = option.name;
          break;
        }
      }
    },

    // dialog 确认事件
    sysVarConfirm() {
      this.sysVarDialogVisible = false;
      this.edittingCondition._fe_selectedSysVars.push(this.edittingOption.value);
      this.optionConfirm();
    },

    // dialog 取消事件
    sysVarCancel() {
      this.sysVarDialogVisible = false;
      this.optionCancel();
    },

    // 设置已选中系统变量
    setSelectedSysVars() {
      let selectedSysVars = [];
      this.edittingCondition.optionList.options.forEach(option => {
        let optionVal = option.value;
        if (option.issysflag && optionVal && selectedSysVars.indexOf(optionVal) === -1) {
          selectedSysVars.push(optionVal);
        }
      });
      this.edittingCondition._fe_selectedSysVars = selectedSysVars;
    },

    // 错误提示信息
    showError(res, prefix) {
      const resData = res.data;
      if (resData.success || (typeof resData.error === 'undefined') || !res.error.errorMessage) {
        return;
      }
      prefix = prefix || '';
      console.log(prefix, JSON.stringify(resData.error));
      this.$message({
        message: prefix + resData.error.errorMessage,
        type: 'error'
      });
    },

    /**
     * 自定义条件相关
     */
    // 显示 dialog
    addCustomCondition() {
      if (!this.checkUnfinishedCondition()) {
        return;
      }
      this.customCondition = {
        fieldcode: null,
        fieldname: null,
        fieldtype: null,
        ctrltype: null,
        dispsequence: this.currentTpl.conditionList.length,
        ifmust: false,
        ifdatapower: false,
        refcode: null,
        enumname: null,
        iskeyword: false,
        ifcustom: true,
        optionList: {
          def_min_value: null,
          def_max_value: null,
          value: null,
          options: []
        }
      };
      if (this.$refs.customConditionForm) {
        this.$refs.customConditionForm.resetFields();
      }
      this.customConditionDialogVisible = true;
    },
    // fieldtype change, 获取参照选项
    getSysRefOptions(val) {
      if (val !== 'ref') {
        return;
      }
      if (Array.isArray(this.sysRefOptions) && this.sysRefOptions.length) {
        return;
      }
      const requestUrl = '/uitemplate_web/uitemplate_ctr/uitemplate_design_ctr/queryRef';
      this.$http({
        url: requestUrl,
        method: 'post',
        dataType: 'json'
      })
        .then(res => {
          if (res.data) {
            this.sysRefOptions = res.data;
          }
        })
        .catch(() => {
          this.$message({
            message: '获取参照列表失败',
            type: 'error'
          });
        });
    },
    // dialog 确认
    customConditionConfirm() {
      let conditionValid = true;
      this.$refs.customConditionForm.validate((valid) => {
        if (!valid) {
          conditionValid = false;
        }
      });
      if (!conditionValid) {
        return;
      }
      let customCondition = this.customCondition;
      switch (customCondition.fieldtype) {
        case 'datetime':
          customCondition.ctrltype = 'DateTime';
          break;
        case 'decimal':
          customCondition.ctrltype = 'NumberComponent';
          break;
        case 'tinyint':
          // boolean 类型添加默认选项
          customCondition.optionList.options = [
            {
              'min_value': null,
              'max_value': null,
              'value': 'true',
              'name': '是',
              'dispsequence': 0,
              'selected': false,
              'issysflag': false
            },
            {
              'min_value': null,
              'max_value': null,
              'value': 'false',
              'name': '否',
              'dispsequence': 1,
              'selected': false,
              'issysflag': false
            }
          ];
        case 'varchar':
          customCondition.ctrltype = 'Select';
          break;
        case 'ref':
          customCondition.ctrltype = 'Reference';
          customCondition.fieldtype = 'varchar';
          break;
        default:
          break;
      }
      this.currentTpl.conditionList.push(JSON.parse(JSON.stringify(customCondition)));
      this.customConditionCancel();
    },
    // dialog 取消
    customConditionCancel() {
      this.customConditionDialogVisible = false;
    }
  },
  mounted() {
    this.requestSearchTpl();
  }
};
</script>

<style scoped>
  .tpl-edit-container {
    padding: 15px 24px;
  }
  .form-container {
    background: #ffffff;
    padding: 16px 16px 40px;
  }
  .form-title, .condition-row {
    font-size: 14px;
  }
  .form-title {
    position: relative;
    margin-bottom: 16px;
    padding-bottom: 10px;
  }
  .form-title i {
    margin-right: 6px;
    vertical-align: middle;
  }
  .form-title::after {
    position: absolute;
    bottom: -1px;
    left: 0;
    display: block;
    content: "";
    width: 30%;
    height: 1px;
    background-color: #d7d7d7;
  }
  .form-tips {
    padding-left: 20px;
    font-size: 12px;
    line-height: 30px;
  }

  .condition-row {
    margin: 0;
    border: 1px solid #898989;
    margin-top: -1px;
    position: relative;
    display: flex;
    flex-wrap: wrap;
  }
  .condition-title-row {
    text-align: center;
  }
  .condition-row .el-col {
    margin: -1px;
    padding: 10px;
    float: none;
    border-left: 1px solid #898989;
  }
  .condition-row .options {
    /* border-left: 1px solid #898989; */
    /* border-right: 1px solid #898989; */
    min-height: 64px;
  }
  .condition-row .advanced-label {
    width: 100%;
    padding: 16px;
    border-bottom: 1px solid #898989;
  }
  .condition-row .condition-oprators {
    padding-top: 22px;
    text-align: center;
  }
  .condition-oprators i,
  .option-operators i {
    font-size: 24px;
  }
  .condition-oprators i {
    margin-right: 16px;
  }

  .options .ifbp-icon-create-square {
    margin-top: 15px;
    cursor: pointer;
  }
  .options .option-container {
    display: inline-block;
    position: relative;
    margin: 5px 0 5px 12px;
    color: #999999;
  }
  .condition-name {
    margin-top: 4px;
  }
  .options .option {
    padding: 6px 16px;
    border: 1px dotted #cccccc;
    cursor: default;
  }
  .options .option.editable {
    cursor: pointer;
  }
  .options .option.editable:hover {
    border-color: #20a0ff;
  }
  .options .option-container i {
    position: absolute;
    left: 0;
    top: 0;
    transform: translate(-50%, -50%);
  }
  .options .option-container i:hover {
    color: red;
  }
  .option-operators {
    text-align: right;
    font-size: 24px;
  }
  .option-operators .confirm {
    color: green;
    margin-right: 12px;
  }
  .option-operators .cancel {
    color: red;
  }

  .option-editting-area {
    box-sizing: border-box;
    padding: 12px;
    background: #ffffff;
    position: absolute;
    top: 100%;
    left: -1px;
    width: 100%;
    z-index: 1;
    border: 1px solid #898989;
    box-shadow: 5px 5px 10px #888888;
    display: none;
  }
  .btn-condition-add-container {
    text-align: center;
  }
  .btn-condition-add-container i {
    font-size: 30px;
    cursor: pointer;
  }
  .btn-system-variable {
    margin-top: 3px;
  }
  .page-operators {
    background-color: #fff;
    height: 56px;
    line-height: 56px;
    padding: 0 16px;
    margin: 5px 0;
  }
</style>
