<template>
  <!--搜索组件-->
  <div id="search">
    <a-form class="search-form" :form="form" @submit="handleSearch">
      <a-row :gutter="24">
        <a-col
          v-for="(item, index) of searchList"
          :key="index"
          :md="colmd"
          :sm="colsm"
          :style="{ display: index < count ? 'block' : 'none' }"
        >
          <a-form-item
            v-if="item.inputType=== 'input'"
            :label="item.label"
            v-bind="item.itemLayout ? item.itemLayout : formItemLayout"
          >
            <a-input v-decorator="[...item.props, {
            rules: []
            }]" :placeholder="item.placeholder"
            @change="wordipt(item.props)"
            />
          </a-form-item>

          <a-form-item
            v-if="item.inputType=== 'doubleTimePick'"
            :label="item.label"
            v-bind="item.itemLayout ? item.itemLayout : formItemLayout"
          >
            <a-time-picker :default-value="zerotime" :minute-step="item.mStep||5" v-model="startTime" :second-step="item.sStep||5" :placeholder="item.placeholder" style="width:48%"/>
            <a-input
                style=" width:6%;padding:8px; border-left: 0;border-right:0; text-align:center;pointer-events: none; backgroundColor: #fff;border:0"
                placeholder="—"
                disabled
              />
            <a-time-picker :default-value="lastTime" :minute-step="item.mStep||5" v-model="endTime" :second-step="item.sStep||5" :placeholder="item.placeholder" style="width:44%"/>
          </a-form-item>

          <a-form-item
            v-if="item.inputType=== 'inputGroup'"
            :label="item.label"
            v-bind="item.itemLayout ? item.itemLayout : formItemLayout"
          >
            <a-input-group compact>
              <a-input
                style="width:35%;border-right:0"
                v-decorator="[...item.props, {
                rules: []
                }]" :placeholder="item.placeholder[0]"
              />
              <a-input
                style=" width: 10%; border-left: 0;border-right:0; text-align:center;pointer-events: none; backgroundColor: #fff"
                placeholder="—"
                disabled
              />
              <a-input
                style="width: 35%; border-left: 0;border-right:0;"
                v-decorator="[...item.props2, {
                rules: []
                }]" :placeholder="item.placeholder[1]"
              />
              <a-input
                style=" width: 20%; border-left: 0;text-align:center; pointer-events: none; backgroundColor: #fff"
                :placeholder="item.suflabel"
                disabled
              />
            </a-input-group>
          </a-form-item>

          <a-form-item
            v-if="item.inputType=== 'switch'"
            :label="item.label"
            v-bind="item.itemLayout ? item.itemLayout : formItemLayout"
          >
            <a-switch v-decorator="[...item.props, {
            rules: []
            }]" :placeholder="item.placeholder"/>
          </a-form-item>

          <a-form-item
            v-if="item.inputType=== 'select'"
            :label="item.label"
            v-bind="item.itemLayout ? item.itemLayout : formItemLayout"
          >
            <a-select  @change="(e) => {item.handle && item.handle(e)}"
              @search="selectSearch(item, $event)"
              @popupScroll="selectScroll(item, $event)"
              :default-active-first-option="false"
              :filterOption="filterOption" v-decorator="item.props" showSearch allowClear :placeholder="item.placeholder">
              <a-select-option v-for="(el, i) of item.options" :key="i" :value="el.value">{{el.label}}</a-select-option>
            </a-select>
          </a-form-item>


          <a-form-item
            v-if="item.inputType=== 'treeSelect'"
            :label="item.label"
            v-bind="item.itemLayout ? item.itemLayout : formItemLayout"
          >
            <a-tree-select
              @change="(e) => {item.handle && item.handle(e)}"
              style="width: 100%"
              showSearch
              allowClear
              :treeCheckable="item.treeCheckable"
              :tree-data="item.options"
              treeNodeFilterProp="title"
              v-decorator="item.props"
              :placeholder='item.placeholder'
              :disabled="item.disabled"
              :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
            >
            </a-tree-select>

          </a-form-item>

          <a-form-item
            v-if="item.inputType=== 'treeSelectMultiple'"
            :label="item.label"
            v-bind="item.itemLayout ? item.itemLayout : formItemLayout"
          >
            <a-tree-select
              v-decorator="item.props"
              style="width: 100%"
              tree-node-filter-prop="title"
              :tree-data="item.options"
              tree-checkable
              :placeholder='item.placeholder'
              :show-checked-strategy="SHOW_PARENT"
              search-placeholder="Please select"
              :expandTrigger="item.expandTrigger || 'hover'"
            />
          </a-form-item>

          <a-form-item
            v-if="item.inputType=== 'cascader'"
            :label="item.label"
            v-bind="item.itemLayout ? item.itemLayout : formItemLayout"
          >
            <a-cascader
              @change="e => {item.handle && item.handle(e);}"
              :showSearch="{filter}"
              :loadData="item.loadData"
              v-decorator="item.props"
              :options="item.options"
              :expandTrigger="item.expandTrigger || 'hover'"
              :placeholder="item.placeholder"
              :fieldNames="item.fieldNames || {label: 'label', value: 'value', children: 'children'}"
              :changeOnSelect="item.changeOnSelect"
              notFoundContent="无匹配结果"
              change-on-select
            />
          </a-form-item>

          <a-form-item
            v-if="item.inputType=== 'datePick'"
            :label="item.label"
            v-bind="item.itemLayout ? item.itemLayout : formItemLayout"
          >
            <a-range-picker v-decorator="item.props" @change="item.change" :disabled-date="item.disabledDate" :placeholder="item.placeholder" :format="item.formate?item.formate:'YYYY-MM-DD'" :picker="item.picker" :mode="item.mode" /></a-form-item>

          <a-form-item
            v-if="item.inputType=== 'datePickMonth'"
            :label="item.label"
            v-bind="item.itemLayout ? item.itemLayout : formItemLayout"
          >
            <a-range-picker v-decorator="item.props" :defaultPickerValue='defaultPanelMonth' @change="item.change" :disabled-date="item.disabledDate" :placeholder="item.placeholder" :format="item.formate?item.formate:'YYYY-MM-DD'" :picker="item.picker" :mode="item.mode"  @panelChange="handlePanelChange"/></a-form-item>

           <a-form-item
            v-if="item.inputType=== 'singleDatePick'"
            :label="item.label"
            v-bind="item.itemLayout ? item.itemLayout : formItemLayout"
          >
            <a-date-picker v-decorator="item.props" :disabled-date="item.disabledDate" :placeholder="item.placeholder" format="YYYY-MM-DD"/></a-form-item>


          <a-form-item
            v-if="item.inputType=== 'dateTimePick'"
            :label="item.label"
            v-bind="item.itemLayout ? item.itemLayout : formItemLayout"
          >
            <a-range-picker v-decorator="item.props" :placeholder="item.placeholder" showTime :format="item.formate?item.formate:'YYYY-MM-DD HH:mm:ss'"/></a-form-item>

          <a-form-item
            v-if="item.inputType=== 'singleDateTimePick'"
            :label="item.label"
            v-bind="item.itemLayout ? item.itemLayout : formItemLayout"
          >
            <a-date-picker v-decorator="item.props" :placeholder="item.placeholder" showTime format="YYYY-MM-DD HH:mm"/></a-form-item>
        </a-col>

        <a-col v-if="searchList.length" class="search-btns" :class="{'is-expand': expand}" :span="expand ? 24 : 8">
          <a-button type="primary" html-type="submit">查询</a-button>
          <a-button class="reset" @click="handleReset">重置</a-button>
          <a v-if="searchList.length > 2" @click="changeFold">
            {{expand ? '收起' : '展开'}}<a-icon :type="expand ? 'up' : 'down'"/>
          </a>
        </a-col>
      </a-row>
    </a-form>

    <div class="table-opt" v-if="tableOptList.length">
      <a-button
        v-for="(item, index) of tableOptList"
        :key="index"
        @click.native="dispatchBtns(item)"
        :loading="item.loading || false"
        type="primary"
        :icon="item.icon"
        :disabled="item.disabled"
        v-hasPermi="item.permi"
      >{{item.text}}
      </a-button>
    </div>
  </div>
</template>
<script>
import { TreeSelect } from 'ant-design-vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
import { inputSearch } from '../utils/mixins';
import { empty } from '../utils/empty';
import moment from 'moment';
export default {
  mixins: [inputSearch],
  name: 'search',
  props: {
    searchList: {
      type: Array,
      default: () => []
    },
    tableOptList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      SHOW_PARENT,
      defaultPanelMonth:[moment().subtract(1, 'month').format('YYYY-MM'),moment().format('YYYY-MM')],
      zerotime:moment('00:00:00', 'HH:mm:ss'),
      lastTime:moment('23:00:00', 'HH:mm:ss'),
      startTime:moment('00:00:00', 'HH:mm:ss'),
      endTime:moment('23:00:00', 'HH:mm:ss'),
      colmd: 8,
      colsm: 24,
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 }
      },
      expand: false,
      isFetched:false,
      selectCurrentPage: 1
    };
  },
  computed: {
    count () {
      return this.expand ? this.searchList.length : 2;
    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this);
  },
  created () {
    this.assignSearchValue();
    empty.$on('resetForm', (key) => {
      if (key && Array.isArray(key) && key.length) {
        this.form.resetFields(key);

        this.searchList.forEach((el) => {
          key.forEach((item) => {
            let props = el.props;
            if (props && props[0] === item) {
              el.options = [];
            }
          });
        });
      } else {
        this.form.resetFields();
      }
    });
  },
  updated () {
    this.changePickerStyle();
  },
  mounted () {
    this.changePickerStyle();
  },
  methods: {
    wordipt(v){
      setTimeout(() => {
        this.form.validateFields((error, values) => {
          let newWord=values[v[0]].replace(/(^\s*)|(\s*$)/g,''),obj = {}
          obj[v[0]] = newWord
          this.form.setFieldsValue(obj)
        })
      }, 0);
    },
    handlePanelChange(value, mode){
      if(value[0] >  moment().endOf('month')){
         this.$message.error('起始月不能超过当前月份，请重新选择');
         return
      }
      if(value[1] >  moment().endOf('month')){
         this.$message.error('终止月不能超过当前月份，请重新选择');
         return
      }

      if (value[1].diff(value[0], 'month') > 5) {
        this.$message.error('起止月份最大跨度6个月，请重新选择');
        value[1] = undefined;
        value[0] = undefined;
        return
      }
      this.form.setFieldsValue({
        "month": value
      })
    },
    // 当选择器为小区时 作分页展示
    selectScroll (item, e) {
      if (!item.fetchOptions) { return; }
      const { target } = e;
      const { scrollTop, scrollHeight, clientHeight } = target;
      if (scrollTop + 2 + clientHeight >= scrollHeight) {
        if (this.isFetched) { return; }
        if (item.totalPage === undefined || this.selectCurrentPage < item.totalPage) {
          this.isFetched = true;
          this.selectCurrentPage += 1;
          item.fetchOptions(this.selectCurrentPage, item.searchValue, item, true).then((data) => { // 第四个参数判断是否为滚动
            item.paginationTotal = data.total;
            item.totalPage = data.totalPage;
            setTimeout(() => {
              this.isFetched = false;
            }, 150);
          });
        }
      }
    },
    selectSearch (item, e) {
      item.searchValue = e; // 搜索值
      this.selectCurrentPage = 1;
      if (this.isFetched) { return; }
      this.isFetched = true;

      typeof item.fetchOptions === 'function' && item.fetchOptions(undefined, e, item).then((data) => {
        item.paginationTotal = data.total;
        item.totalPage = data.totalPage;

        setTimeout(() => {
           this.isFetched = false;
        }, 100);
      });
    },
    assignSearchValue () {
      empty.$on('setSearchValue', (formVal) => {
        this.$nextTick(() => {
          if (formVal) {
            this.form.setFieldsValue(formVal);
          }
        });
      });
    },
    changeFold () {
      this.expand = !this.expand;
    },
    /** 修改日期选择默认样式 */
    changePickerStyle () {
      this.$nextTick(() => {
        let picker = document.getElementsByClassName('ant-calendar-picker');
        for (let i = 0; i < picker.length; i++) {
          picker[i].style && (picker[i].style.width = '100%');
        }
      });
    },
    /* 分发btn事件 */
    dispatchBtns (item) {
      this.$emit('btnsHandler', item);
    },
    /* 查询 */
    handleSearch  (e) {
      e && e.preventDefault();
      this.form.validateFields((error, values) => {
        if (error) { return; }
        let newValue = {...values};
        let dateProps = [];
        let singleDateProps = [];

        this.searchList.forEach((ele) => {
          if(ele.inputType == "doubleTimePick"){
            let startTimeStr = this.startTime&&this.startTime.format('HH:mm:ss')
            let endTimeStr = this.endTime&&this.endTime.format('HH:mm:ss')
            let timestr= this.startTime&&this.endTime? startTimeStr + ',' + endTimeStr : startTimeStr||endTimeStr
            newValue[ele.props] = timestr;
          }

        });
        this.searchList.forEach((el) => {
          if (el.inputType === 'datePick' || el.inputType === 'dateTimePick' || el.inputType === 'datePickMonth') {
            dateProps.push({
              props: el.props[0],
              inputType: el.inputType
            });
          }
          if (el.inputType ==='singleDateTimePick' || el.inputType ==='singleDatePick') {
            singleDateProps.push({
              props: el.props[0],
              inputType: el.inputType
            });
          }
        });

        dateProps.forEach((ele) => {
          let date = newValue[ele.props];
          if (date && date.length) {
            let format = ele.inputType === 'datePick' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss';
            if(ele.props == 'month'){
              format = 'YYYY-MM'
            };
            let startDate = date[0].format(format);
            let endDate = date[1].format(format);
            newValue[ele.props] = `${startDate},${endDate}`;
          }
        });
        singleDateProps.forEach((ele) => {
          let date = newValue[ele.props];
          if (date) {
            let format = ele.inputType === 'singleDatePick' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm';
            let singleDate = date.format(format);
            newValue[ele.props] = `${singleDate}`;
          }
        });

        for (let item in newValue) {
          if (Array.isArray(newValue[item])) {
            newValue[item] = newValue[item].join(',');
          }
        }
        this.$emit('searchHandle', newValue);
      });
    },
    /* 清空 */
    handleReset () {
      this.startTime = '';
      this.endTime = '';
      this.$emit('resetHandle');
      this.form.resetFields();
    }
  }
};
</script>

<style lang="scss">
/*S- 更多搜索*/
#search {
  margin-bottom: 16px;
  .search-form  {
    transition: all 0.2s;
    .ant-form-item {
      display: flex;
      .ant-form-item-control-wrapper {
        flex: 1;
      }
    }
    .ant-calendar-picker {
      width: 100%;
    }
    .search-btns {
      line-height: 40px;
      .reset {
        margin-left: 8px;
      }
      a {
        margin-left: 8px;
        font-size: 14px;
      }
    }
    .is-expand {
      text-align: right;
    }
  }
  .table-opt {
    .ant-btn-primary {
      margin-right: 8px;
      margin-top: 8px
    }
  }
}
/*E- 更多搜索*/
</style>
