<template>
  <div class="cms-form-magnifier">
    <div v-if="multiple" style="height: 40px; line-height: 40px;border: 1px solid #DCDFE6;" class="cms-tags">
      <div class="cms-tags-show">
        <el-tag
          v-for="tag in inputValue"
          closable
          :key="tag"
          :disable-transitions="false"
          @close="handleClose(tag)">
          {{ tag }}
        </el-tag>
      </div>
      <div class="cms-tags-input">
        <cms-form-input
          class="input-new-tag"
          v-bind="$attrs"
          @focus="handleFocus"
          :placeholder="placeholder"
          v-model="inputSearchValue"
          ref="saveTagInput"
          size="small">
          <template slot="suffix">
            <i class="el-icon-search"></i>
          </template>
        </cms-form-input>
      </div>
    </div>
    <cms-form-input
      v-bind="$attrs" v-else
      @focus="handleFocus"
      @clear="clearEvents"
      :value="inputValue"
      :style="'width: 100%'"
      :placeholder="placeholder">
      <i class="el-input__icon el-icon-search" slot="suffix"> </i>
    </cms-form-input>
    <cms-modal
      v-if="magnifierVisible"
      v-model="magnifierVisible"
      ref="CmsModalRef"
      @onCancel="handleCancel"
      @close="closeModal"
      @hide="closeModal"
      @show="showModal"
      @zoom="zoomModal"
      :modal-width="modalWidth"
      :show-footer="showFooter"
      :modal-height="modalHeight"
      :modal-title="magnifierTitle"
      :modal-config="{
        'show-zoom': false,
      }"
    >
      <cms-query-table
        ref="magnifierTable"
        size="medium"
        @cell-dblclick="cellDbClick"
        @checkbox-change="onCheckTable"
        @checkbox-all="onCheckTable"
        :custom-refresh-table="true"
        :columns="columns"
        :pagination="pagination"
        :height="inputHeight"
        :fixed-height="true"
        :constant-load="constantLoad"
        :form-item-config="formItems"
        :show-search-form="showSearchForm"
        :search-method="searchClick"
        :query-params="queryParams"
        :request-call="requestCall"
      >
        <template v-for="item in formItems" :slot="item.prop">
          <slot :name="item.prop"></slot>
        </template>
        <slot name="columns"/>
      </cms-query-table>
      <template slot="footer" v-if="showFooter">
        <slot name="buttons">
          <cms-button key="submit" type="primary" @click="handleOk"> 确定</cms-button>
          <cms-button key="back" @click="handleCancel"> 返回</cms-button>
        </slot>
      </template>
    </cms-modal>
  </div>
</template>

<script>
import { CmsModalMix } from '../CmsModal/CmsModalMix'

export default {
  mixins: [ CmsModalMix ],
  name: "CmsFormMagnifier",
  data() {
    return {
      inputSearchValue: '',
      inputHeight: 495,
      defaultModalWidth: this.modalWidth,
      magnifierVisible: false,
    }
  },
  watch: {},
  methods: {
    resetModalSize() {
      const self = this;
      setTimeout(() => {
        if (self.$refs.CmsModalRef) {
          const modalRef = self.$refs.CmsModalRef.$el.querySelector('.vxe-modal--box')
          if (modalRef.clientWidth < 1600) {
            self.defaultModalWidth = '60%'
          } else if (document.body.clientWidth < 1400) {
            self.defaultModalWidth = '70%'
          } else if (document.body.clientWidth < 1300) {
            self.defaultModalWidth = '80%'
          }
        }
      }, 300);
    },
    onCheckTable({ records }) {
      this.$emit("on-check", records);
    },
    searchClick() {
      this.$emit("searchMethod");
    },
    clearEvents() {
      const matchKey = this.matchKey;
      for (const key in matchKey) {
        if (Array.isArray(this.formModel[key])) {
          this.formModel[key] = [];
        } else if (typeof this.formModel[key] == "string") {
          this.formModel[key] = undefined;
        } else if (typeof this.formModel[key] == "boolean") {
          this.formModel[key] = false;
        } else if (typeof this.formModel[key] == "object") {
          this.formModel[key] = {};
        }
      }
      this.$emit("clear");
    },
    handleFocus() {
      this.magnifierVisible = true;
    },
    handleClose(tag) {
      this.inputValue.splice(this.inputValue.indexOf(tag), 1);
    },
    handleOk() {
      const table = this.$refs["magnifierTable"];
      const checkboxRecords = table.getTable().getCheckboxRecords();
      if (checkboxRecords.length > 0) {
        checkboxRecords.forEach((row) => {
          this.setValue(row)
        });
      }
      this.$emit('ok', checkboxRecords);
    },
    handleCancel() {
      this.magnifierVisible = false;
    },
    closeModal() {
      this.visible = false
      if (this.modalCallback) {
        this.modalCallback(false)
      }
      this.$emit('onCancel', false);
    },
    zoomModal({ $modal, $event, type }) {
      const modalRef = $modal.$el.querySelector('.vxe-modal--box')
      this.inputHeight = modalRef.clientHeight - 44;
      this.$emit('zoom', { $modal, $event, type })
    },
    showModal($modal) {
      const modalRef = $modal.$el.querySelector('.vxe-modal--content')
      console.log(modalRef, modalRef.clientHeight);
      this.inputHeight = modalRef.clientHeight;
      this.$emit('show', $modal);
    },
    reload() {
      this.$refs["magnifierTable"].reload();
    },
    focusTagInput() {
      if (this.readOnly || !this.$el.querySelector(".tag-input")) {
        return false;
      } else {
        this.$el.querySelector(".tag-input").focus();
      }
    },
    cellDbClick({ row }) {
      this.setValue(row)
      this.$emit("cell-dblclick", row);
    },
    setValue(row) {
      if (!this.closeBeforeConfirm) {
        return false;
      }
      if (typeof this.closeBeforeConfirm === 'function') {
        if (!this.closeBeforeConfirm(row)) {
          return false;
        }
      }
      if (this.matchKey) {
        const matchKey = this.matchKey;
        console.log('-----------matchKey: ', this.matchKey);
        for (const key in matchKey) {
          if (Array.isArray(this.formModel[key])) {
            if (this.formModel[key] && !this.formModel[key].includes(row[matchKey[key]])) {
              this.formModel[key].push(row[matchKey[key]]);
            }
          } else {
            this.formModel[key] = row[matchKey[key]];
          }
        }
      }
      this.magnifierVisible = false;
      if (this.callback) {
        this.callback(row);
      }
    }
  },
  computed: {
    inputValue: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    magnifierTitle() {
      return this.modalTitle;
    }
  },
  props: {
    value: {
      type: [ Array, String, Number, Boolean ],
      default: () => {
        return "";
      },
    },
    size: {
      type: String,
      default: () => {
        return "default";
      },
    },
    /** 查询参数 */
    queryParams: {
      type: Object,
      default: () => {
        return {};
      },
    },
    pagination: {
      type: [ Boolean ],
      default: () => {
        return true;
      },
    },
    height: {
      type: [ String, Number, Boolean ],
      default: () => {
        return 558;
      },
    },
    showSearchForm: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    multiple: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    closeBeforeConfirm: {
      type: [ Function, Boolean ],
      default: () => {
        return true
      }
    },
    formItems: {
      type: Array,
      default: () => {
        return [];
      },
    },
    callback: Function,
    /** 参数回调地址 */
    requestCall: {
      type: [ Function, Array, String, Object ],
      default: () => {
        return {
          data: [],
          total: 0,
        };
      },
    },
    /** 表格元素 */
    columns: {
      type: Array,
      default: () => {
        return [];
      },
    },
    width: {
      type: String,
      default: "60%",
    },
    /** 默认显示文本 */
    placeholder: {
      type: String,
      default: undefined,
    },
    matchKey: {
      type: [ Object ],
      default: () => {
        return undefined;
      },
    },
    formModel: {
      required: true,
      type: [ Object ],
      default: () => {
        return {};
      },
    },
    constantLoad: Function,
  },
};
</script>

<style lang="scss">
.cms-form-magnifier {
  .vxe-modal--content {
    padding: 0 !important;
  }


  .vxe-body--row .vxe-body--column {
    padding: 10px 0 !important;
  }

  .cms-tags {
    background-color: #FFF;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    box-sizing: border-box;
    color: #606266;
    font-size: inherit;
    height: 40px;
    line-height: 40px;
    outline: 0;
    padding: 0 0 0 2px;
    cursor: pointer;
    transition: border-color .2s cubic-bezier(.645, .045, .355, 1);
    width: 100%;
    display: flex;
    flex-direction: row;


    .el-tag {
      background-color: #ecf5ff;
      border-color: #d9ecff;
      height: 30px;
      padding: 0 10px;
      margin: 0 2px;
      line-height: 32px;
      font-size: 12px;
      border-width: 1px;
      border-style: solid;
      border-radius: 4px;
      box-sizing: border-box;
      white-space: nowrap;
    }

  }

  .cms-tags-show {

  }

  .cms-tags-input {
    flex: 1;

    .el-input__inner {
      border: none !important;
    }
  }

  .cms-tags:hover {

  }
}

.vxe-modal--wrapper .vxe-modal--footer {
  text-align: right;
  padding: 5px 1em !important;
}

</style>
