<template>
  <div>
    <div class="group">
      <div class="name">过滤器</div>
      <div
        :class="{ btn: 1, active }"
        @click="$emit('onFieldSetSwitch', 'filter')"
      >
        选择字段 <i class="el-icon-d-arrow-right"></i>
      </div>
    </div>
    <draggable
      v-model="config.filter"
      :animation="150"
      :class="{ 'item-box': 1, active }"
    >
      <div
        :class="['item', field.dimensionType]"
        v-for="(field, i) of config.filter"
        :key="i"
      >
        <div class="name">{{ field.columnTitle }}</div>
        <i
          class="el-icon-setting"
          style="margin-right: 5px; cursor: pointer"
          @click="onEditFilter(field)"
        ></i>
        <i class="el-icon-close" @click="onFieldDel(i)"></i>
      </div>
    </draggable>
    <!-- 过滤器编辑框 -->
    <el-dialog
      append-to-body
      :visible.sync="showEditFilter"
      title="编辑过滤器"
      custom-class="bigdata-filter"
      width="560px"
    >
      <div v-if="nowFilter">
        <el-form size="mini" label-width="80px">
          <el-form-item label="当前字段">
            <div :class="['now-filter', nowFilter.dimensionType]">
              <div class="name">{{ nowFilter.columnTitle }}</div>
              <div style="color: #999">
                {{ datatypeMap[nowFilter.viewDataType] }}
              </div>
            </div>
          </el-form-item>
          <el-form-item label="作为筛选">
            <el-switch v-model="nowFilter.asFilter"></el-switch>
          </el-form-item>
          <el-form-item label="过滤时机">
            <el-radio-group v-model="nowFilter.connectTime">
              <el-radio label="where">聚合前(where)</el-radio>
              <el-radio label="having" :disabled="countFilterTime()">
                聚合后(having)
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="连接方式">
            <el-radio-group v-model="nowFilter.connectType">
              <el-radio label="and">且</el-radio>
              <el-radio label="or">或</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="枚举来源" v-show="countEnumShow()">
            <el-radio-group v-model="nowFilter.enumSource">
              <el-radio label="1">原始数据聚合</el-radio>
              <el-radio label="2">api</el-radio>
            </el-radio-group>
            <el-button
              size="mini"
              icon="el-icon-share"
              plain
              type="success"
              @click="getEnumData"
              style="margin-left: 20px"
            >
              获取
            </el-button>
          </el-form-item>
          <el-form-item
            label="选择api"
            v-if="countEnumShow() && nowFilter.enumSource == '2'"
          >
            <el-cascader
              v-model="nowFilter.enumId"
              :options="apiList"
              :props="{ expandTrigger: 'hover', emitPath: false }"
              filterable
              popper-class="bigdata-data-selector"
              :show-all-levels="false"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="过滤条件">
            <div
              class="filter-item"
              v-for="(condition, i) of nowFilter.conditions"
              :key="i"
            >
              <el-select
                size="mini"
                v-model="condition.function"
                style="width: 100px; margin-right: 10px"
                placeholder="选择条件"
                @change="onFunctionChange"
              >
                <el-option
                  v-for="func of functions[nowFilter.viewDataType]"
                  :key="func.function"
                  :value="func.function"
                  :label="func.label"
                ></el-option>
              </el-select>
              <!-- 日期类型 -->
              <template v-if="nowFilter.viewDataType == 'DATETIME'">
                <el-select
                  v-model="condition.timeType"
                  style="width: 95px; margin-right: 5px"
                  @change="onTimeTypeChange(condition)"
                >
                  <el-option label="绝对时间" value="absolute"></el-option>
                  <el-option label="相对时间" value="relative"></el-option>
                </el-select>
                <template v-if="condition.timeType == 'relative'">
                  <el-input
                    style="width: 120px; margin-right: 5px"
                    v-model="condition.values[0]"
                  >
                    <template slot="append">
                      {{ timeTypeMap[nowFilter.timeDataFormat] }}
                    </template>
                  </el-input>
                  <el-select v-model="condition.countType" style="width: 60px">
                    <el-option label="前" value="left"></el-option>
                    <el-option label="后" value="right"></el-option>
                  </el-select>
                </template>
                <template v-else>
                  <template v-if="nowFilter.dateType == 'time'">
                    <el-date-picker
                      style="width: 200px"
                      v-model="condition.values[0]"
                      type="datetime"
                      placeholder="选择日期时间"
                      :value-format="nowFilter.dateFormat"
                    >
                    </el-date-picker>
                    <el-date-picker
                      v-if="condition.function == 'between'"
                      style="width: 200px"
                      v-model="condition.values[1]"
                      type="datetime"
                      placeholder="选择日期时间"
                      :value-format="nowFilter.dateFormat"
                    >
                    </el-date-picker>
                  </template>
                  <template
                    v-else-if="
                      ['year', 'month', 'date'].includes(nowFilter.dateType)
                    "
                  >
                    <el-date-picker
                      style="width: 200px"
                      v-model="condition.values[0]"
                      :type="nowFilter.dateType"
                      placeholder="选择日期"
                      :value-format="nowFilter.dateFormat"
                    >
                    </el-date-picker>
                    <el-date-picker
                      v-if="condition.function == 'between'"
                      style="width: 200px"
                      v-model="condition.values[1]"
                      :type="nowFilter.dateType"
                      placeholder="选择日期"
                      :value-format="nowFilter.dateFormat"
                    >
                    </el-date-picker>
                  </template>
                  <template v-else>
                    <el-time-select
                      style="width: 200px"
                      v-model="condition.values[0]"
                      placeholder="选择时间"
                      :value-format="nowFilter.dateFormat"
                    >
                    </el-time-select>
                    <el-time-select
                      v-if="condition.function == 'between'"
                      style="width: 200px"
                      v-model="condition.values[1]"
                      placeholder="选择时间"
                      :value-format="nowFilter.dateFormat"
                    >
                    </el-time-select>
                  </template>
                </template>
              </template>
              <template v-else>
                <template v-if="['in', 'notIn'].includes(condition.function)">
                  <el-cascader
                    v-model="condition.values"
                    :options="nowFilter.options"
                    :props="{
                      expandTrigger: 'hover',
                      emitPath: false,
                      multiple: true,
                      label: 'VALUE',
                      value: 'VALUE',
                    }"
                    filterable
                    :show-all-levels="false"
                    collapse-tags
                    clearable
                  ></el-cascader>
                  <el-button
                    size="mini"
                    @click="onEnumSelectAll(nowFilter)"
                    type="primary"
                  >
                    全选
                  </el-button>
                </template>
                <el-input
                  v-else
                  style="width: 200px"
                  size="mini"
                  v-model="condition.values[0]"
                  placeholder="输入值"
                ></el-input>
              </template>
              <i
                class="el-icon-delete"
                v-show="nowFilter.conditions.length > 1"
                @click="onConditionDel(i)"
              ></i>
            </div>
            <el-button
              size="mini"
              type="success"
              plain
              @click="onConditionAdd"
              v-show="canAddCondition"
            >
              添加条件
            </el-button>
          </el-form-item>
          <div
            class="btns"
            style="
              display: flex;
              justify-content: space-evenly;
              margin-top: 30px;
            "
          >
            <el-button
              type="primary"
              size="small"
              @click="showEditFilter = false"
              style="width: 100px"
            >
              确定
            </el-button>
            <el-button
              size="small"
              @click="showEditFilter = false"
              style="width: 100px"
            >
              取消
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { VueDraggableNext as draggable} from "vue-draggable-next";
import { optionList } from "../../../api/newbi/bigdata";
import { dataapiDetail, openurl } from "../../../api/report/report";
import { functions, timeTypeMap } from "../dict";
export default {
  components: { draggable },
  props: ["config", "active", "modalSet", "apiList"],
  data() {
    return {
      nowFilter: null,
      showEditFilter: false,
      functions,
      timeTypeMap,
      datatypeMap: { NUMBER: "数字", STRING: "字符串", DATETIME: "时间" },
    };
  },
  computed: {
    selectedFields() {
      let list = [];
      this.modalSet.forEach((set) => {
        list = list.concat(this.config[set.key]);
      });
      return list;
    },
    // 能否添加过滤条件
    canAddCondition() {
      if (!this.nowFilter) return false;
      let func = this.nowFilter.conditions[0].function;
      if (func == "in" || func == "notIn") return false;
      return true;
    },
  },
  methods: {
    getOptionValue(arr, item) {
      if (item.children) {
        item.children.forEach((i) => {
          this.getOptionValue(arr, i);
        });
      } else {
        arr.push(item.VALUE);
      }
    },
    onEnumSelectAll(filter) {
      let options = filter.options;
      let arr = [];
      options.forEach((i) => this.getOptionValue(arr, i));
      filter.conditions[0].values = arr;
    },
    onTimeTypeChange(condition) {
      if (condition.timeType == "relative") {
        condition.values = [1];
      } else {
        condition.values = [""];
      }
    },
    // 获取枚举可选值
    getEnumData() {
      let { enumSource, enumId } = this.nowFilter;
      if (enumSource == "1") {
        this.nowFilter.loading = true;
        let { tableName, columnName } = this.nowFilter;
        optionList({
          tableName,
          columnName,
          cubeDataId: this.config.dataId,
        }).then((res) => {
          this.nowFilter.options = res.data.data.map((i) => ({
            VALUE: i[columnName],
          }));
          this.nowFilter.loading = false;
        });
      } else {
        if (!enumId) {
          return this.$message({ message: "请选择api", type: "warning" });
        }
        this.nowFilter.loading = true;
        dataapiDetail(enumId).then((res) => {
          let { apiKey } = res.data.data;
          openurl(apiKey).then((res) => {
            this.nowFilter.loading = false;
            let data = res.data.data;
            if (!data.length) {
              this.nowFilter.options = [];
              return;
            }
            if (data[0].ID) {
              let tree = this.countTreeOptions(data);
              tree.forEach(this.clearChildren);
              this.nowFilter.options = tree;
            } else {
              this.nowFilter.options = data;
            }
          });
        });
      }
    },
    countTreeOptions(originData) {
      originData.forEach((i) => (i.children = []));
      let parents = [...originData];
      let res = [],
        childrens = [];
      originData.forEach((i) => {
        if (i.PID == "0") {
          res.push(i);
        } else {
          childrens.push(i);
        }
      });
      childrens.forEach((i) => {
        let parent = parents.find((j) => j.ID == i.PID);
        if (parent) {
          parent.children.push(i);
        }
      });
      return res;
    },
    // 去掉为空的children
    clearChildren(node) {
      if (!node.children) return;
      if (!node.children.length) {
        delete node.children;
      } else {
        node.children.forEach(this.clearChildren);
      }
    },
    // 判断是否展示枚举选项
    countEnumShow() {
      let func = this.nowFilter.conditions[0].function;
      if (func == "in" || func == "notIn") return true;
      return false;
    },
    // 计算函数变化时
    async onFunctionChange(func) {
      if (func == "in" || func == "notIn") {
        this.nowFilter.conditions = [
          {
            function: func,
            values: [],
            timeType: "absolute",
            countType: "left",
          },
        ];
      }
    },
    // 判断过滤项是否可选择having方式
    countFilterTime() {
      let id = this.nowFilter.cubeColumnId;
      return !this.selectedFields.find((i) => i.cubeColumnId == id);
    },
    // 过滤器添加条件
    onConditionAdd() {
      this.nowFilter.conditions.push({
        function: "eq",
        values: ["", ""],
        timeType: "absolute",
        countType: "left",
      });
    },
    // 过滤器删除条件
    onConditionDel(i) {
      this.nowFilter.conditions.splice(i, 1);
    },
    // 编辑某过滤器时
    onEditFilter(field) {
      this.nowFilter = field;
      this.showEditFilter = true;
      let func = this.nowFilter.conditions[0].function;
      if (func == "in" || func == "notIn") {
        if (!this.nowFilter.options.length) {
          this.getEnumData();
        }
      }
    },
    onFieldDel(index) {
      this.config.filter.splice(index, 1);
    },
  },
};
</script>
<style lang="scss">
.bigdata-filter {
  width: 660px;
  .el-form-item {
    margin-bottom: 10px;
  }
  .now-filter {
    display: inline-block;
    font-size: 12px;
    padding: 0 10px;
    line-height: 28px;
    width: 260px;
    display: flex;
    .name {
      margin-right: 5px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      flex: 1;
    }
    &.WEIDU {
      border: 1px solid #1d54d5;
    }
    &.ZHIBIAO {
      border: 1px solid #00b375;
    }
  }
  .filter-item {
    padding-bottom: 10px;
    .el-icon-delete {
      font-size: 14px;
      margin-left: 5px;
      color: #f56c6c;
    }
  }
}
</style>
