<!--
 * @Author: 一日看尽长安花
 * @since: 2019-10-12 16:14:37
 * @LastEditTime: 2020-08-16 21:41:57
 * @LastEditors: 一日看尽长安花
 * @Description:
 -->
<template>
  <div class="filter-container">
    <!-- 取消表单的提交动作 -->
    <el-form
      ref="filterForm"
      :size="size"
      :model="slots.filterData"
      @submit.native.prevent
    >
      <el-row
        v-for="(items, idx) in visibleMetadatas"
        :key="idx + 'row'"
        type="flex"
        justify="start"
        align="bottom"
      >
        <el-col
          v-for="(item, i) in items"
          :key="i + 'col'"
          :span="item.type === 'date' ? 10 : 6"
        >
          <el-form-item>
            <el-row
              v-if="judgeType(item.type, 'string')"
              type="flex"
              justify="start"
              align="bottom"
            >
              <el-col :span="24">
                <el-input
                  v-model="slots.filterData[item.key]"
                  :placeholder="item.name"
                  :clearable="true"
                ></el-input>
              </el-col>
            </el-row>
            <el-row
              v-else-if="judgeType(item.type, 'dict')"
              type="flex"
              justify="start"
              align="bottom"
            >
              <el-col :span="24">
                <sp-tree-select
                  v-model="treeObj[item.key + 'Value']"
                  :data="treeObj[item.key + 'Data']"
                  :props="treeObj[item.key + 'Props']"
                  :filterable="true"
                ></sp-tree-select>
              </el-col>
            </el-row>
            <el-row
              v-else-if="judgeType(item.type, 'date')"
              type="flex"
              justify="start"
              align="bottom"
            >
              <el-col :span="12">
                <el-date-picker
                  v-model="slots.filterData[item.key + '_start']"
                  type="datetime"
                  value-format="timestamp"
                  :placeholder="item.name + '开始时间'"
                >
                </el-date-picker>
              </el-col>
              <el-col :span="12">
                <el-date-picker
                  v-model="slots.filterData[item.key + '_end']"
                  type="datetime"
                  value-format="timestamp"
                  :placeholder="item.name + '结束时间'"
                >
                </el-date-picker>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 用于面板中的自定义表单，例如级联选择器，并通过作用域插槽的方式将数据传递给自定义表单 -->
      <slot name="filter-condition" :filter-data="slots"> </slot>
      <div class="sp-search-btn-container">
        <el-button
          ref="searchButton"
          :size="size"
          class="sp-search-btn-item"
          type="primary"
          icon="el-icon-search"
          @click="filterSearch"
        >
          搜索
        </el-button>
      </div>
    </el-form>

    <div class="filter-btn-group">
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        :size="size"
        @click="handleCreate"
      >
        添加
      </el-button>
      <!-- 用于面板中的自定义功能按钮，例如导入导出按钮等，并通过作用域插槽的方式将数据传递给自定义表单 -->
      <slot name="operation-btn-group" :filter-data="slots"> </slot>
    </div>
  </div>
</template>

<script>
import SpTreeSelect from '@/components/Wrapper/SpTreeSelect';

import { equalsIgnoreCase } from '@/utils/str-util';
import { getDictTree } from '@/api/core_dict';

export default {
  name: 'SearchPane',
  components: { SpTreeSelect },
  props: {
    metadatas: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      size: 'mini',
      slots: {
        filterData: {}
      },
      // 树组件的options 和props挂载对象
      treeObj: {
        job_type1Data: [],
        stateData: []
      }
    };
  },
  computed: {
    // 计算属性的 getter
    visibleMetadatas: function() {
      // `this` 指向 vm 实例
      let allowTypes = ['string', 'date', 'datetime', 'dict'];
      let _metadataPartition = []; //二维数组，每行对应四列
      let count = 0,
        tempArr = [];
      for (let i = 0; i < this.metadatas.length; i++) {
        const v = this.metadatas[i];
        if (v.is_show_search_panel && allowTypes.includes(v.type)) {
          tempArr.push(v);
          count++;
          if (count % 4 === 0) {
            _metadataPartition.push(tempArr);
            tempArr = [];
          }
        }
      }
      if (tempArr.length !== 0) {
        _metadataPartition.push(tempArr);
        tempArr = [];
      }
      return _metadataPartition;
    }
  },
  watch: {
    metadatas: {
      handler: function(a, b) {
        // 解决数据变动监控
        const _that = this;
        const params = [];
        _that.metadatas
          .filter(
            (item, i) => item.is_show_search_panel && item.type === 'dict'
          )
          .forEach((v, i) => {
            const obj = {};
            obj.key = v.key;
            obj.dict_type = v.dict_type;
            obj.dict_parent_id = v.dict_parent_id;
            params.push(obj);
          });
        this.recursiveHanldTree(params, this);
      },
      deep: true
    }
  },
  mounted() {},
  methods: {
    recursiveHanldTree(paramArr, _that) {
      if (paramArr.length) {
        const item = paramArr.shift();
        getDictTree({
          type: item.dict_type,
          parent_id: item.dict_parent_id
        }).then(res => {
          const { code, message, data } = { ...res };
          _that.treeObj[item.key + 'Data'] = data;
          console.log(data);
          _that.recursiveHanldTree(paramArr, _that);
        });
      }
    },
    judgeType(str1, type) {
      return equalsIgnoreCase(str1, type);
    },
    filterSearch(event) {
      this.$refs['filterForm'].validate(valid => {
        if (valid) {
          this.$emit('filter-search', this.slots.filterData);
        } else {
          this.$notify({
            title: 'Faild',
            message: 'Search Failded!',
            type: 'error',
            duration: 2000
          });
        }
      });
    },
    handleCreate() {
      this.$emit('handle-create');
    }
  }
};
</script>
