<template>
  <rt-view>
    <rt-header>
      <rt-navbar :onBack="goBackClick" />
      <rt-search
        :placeholder="placeholder"
        :show-search-button="true"
        v-model="quickSearch"
        @on-search="search"
      ></rt-search>
    </rt-header>
    <rt-content>
      <rt-list ref="listWrapper" :fetch="fetchData">
        <rt-list-item class="list-item" @click.native="select(row)" slot-scope="{row}">
          <div class="list-item__content">
            <div
              class="list-item__row"
              :class="handleRowClass(row)"
              v-for="(col,index) in colList"
              :key="index"
            >{{col.label + (row[col.value] || "")}}</div>
          </div>

          <rt-icon
            :name="isSelected(row)? 'rt-base-checked': 'rt-base-unchecked'"
            :color="(selected.Id === row.id || ( selected.length > 0 && ~selected.findIndex( item => item.Id === row.id ))) ? '#53a4fc':'' "
            size="20"
          ></rt-icon>
        </rt-list-item>
      </rt-list>
      <div v-transfer-dom>
        <rt-popup v-if="messageDialog" :z-index="101" class="popup" v-model="messagePopup">
          <div class="popup-content">
            <div class="popup-item large-space">
              {{dialogContent.title}}
              <div style="margin-left: 8px;word-break: break-all;">
                <span
                  class="selectiveOptions"
                  v-for="(item,index) in selected"
                  :key="index"
                >{{item.Name}}</span>
              </div>
            </div>
            <div
              v-if="dialogContent.contentTitle!=''"
              class="popup-item large-space"
              style="display: flex;background-color: #FAFAFA;padding: 6px 8px;"
            >
              <span class="contentTitle">{{dialogContent.contentTitle}}</span>
            </div>
            <div class="popup-item large-space">
              <span class="messageLable">{{dialogContent.messageLable}}</span>
              <rt-textarea
                style="padding: 0px 15px;border-bottom: none;"
                v-model="messageContent"
                label
                placeholder="请输入..."
              ></rt-textarea>
            </div>
            <div class="popup-item button-group">
              <rt-button @click="messagePopup = false" text size="large" style="display: flex;">取消</rt-button>
              <rt-button
                @click="save();messagePopup = false"
                size="large"
                text
                style="color:#53A4FC;border-left: 1px solid #F0F0F0 !important;display: flex;"
              >确定</rt-button>
            </div>
          </div>
        </rt-popup>
      </div>
    </rt-content>
    <rt-footer v-if="multiple">
      <rt-button-large v-if="messageDialog" text="确认" :click="showmessageDialog">
        <rt-icon name="rt-cmm-submission" size="15" slot="icon"></rt-icon>
      </rt-button-large>
      <div v-if="!messageDialog" class="selectedData">
        <span @click="togglePopupDisplay" class="selectedData__text">已选内容</span>
        <rt-icon
          @click="togglePopupDisplay"
          class="selectedData__icon"
          name="rt-base-arrow"
          color="#ccc"
          size="20"
        ></rt-icon>
        <rt-button class="selectedData__button" @click="save();" type="sub">{{confirmText}}</rt-button>
      </div>
      <rt-popup
        v-if="!messageDialog"
        class="popup2"
        v-model="popupVisible"
        position="bottom"
        auto-scroll
      >
        <div class="popup2__header">
          <span class="popup2__header__text">已选内容</span>
          <div @click="clear" class="clear">清空</div>
        </div>

        <div class="popup2__item" v-for="(item,index) in selected" :key="index">
          <div class="popup2__item__content">
            <div
              class="popup2__item__content__text"
              v-for="(col,colIndex) in colList"
              :key="colIndex"
            >{{handleColDisplay(item,col)}}</div>
          </div>
          <rt-icon
            class="popup2__item__icon"
            name="rt-xrm-delete2"
            color="#B4BDCF"
            size="20"
            @click="removeSelect(item,index)"
          ></rt-icon>
        </div>
      </rt-popup>
    </rt-footer>
  </rt-view>
</template>

<script>
export default {
  name: 'rtLookupView',
  props: {
    // 获取数据名称
    getDataName: {
      type: String,
      required: true
    },
    // 事件名称
    name: {
      type: String,
      required: true
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 是否过滤权限
    filtered: {
      type: Boolean,
      default: true
    },
    // 排序
    orderby: {
      type: String,
      required: true
    },
    // 参数
    param: {
      type: Object,
      default: () => ({})
    },
    // 文本默认内容
    placeholder: {
      type: String,
      default: '输入名称'
    },
    colList: {
      type: [Array],
      default: () => {
        return [{ label: '', value: 'name' }];
      }
    },
    selectedData: {
      type: [Array, Object, String]
    },
    messageDialog: {
      type: Boolean,
      default: false
    },
    dialogContent: {
      type: Object,
      default: { title: '', contentTitle: '', messageLable: '' }
    }
  },
  data() {
    return {
      quickSearch: '',
      selected: this.selectedData || (this.multiple ? [] : {}),
      messagePopup: false,
      messageContent: '',
      popupVisible: false
    };
  },
  computed: {
    confirmText() {
      return this.multiple ? `确定(${(this.selected || []).length})` : '';
    }
  },
  methods: {
    async fetchData(page) {
      let paramsList = this.param;
      paramsList['@queryValue'] = this.quickSearch;
      const api = `api/DataService/${this.filtered ? 'Filtered' : ''}Query`;
      const dataString = await rt.post(api, {
        GetDataName: this.getDataName,
        Paramslist: paramsList,
        Orderby: this.orderby,
        PageSize: page.pageSize,
        PageIndex: page.pageIndex
      });
      // 如果是单选,默认选中第一条
      let data = JSON.parse(decodeURIComponent(dataString)).DataList;
      if (!this.multiple && rt.isNil(this.selected.Id) && data.length > 0) {
        this.selected = this.toEntityReference(data[0]);
      }
      return data;
    },
    search(queryValue) {
      this.$refs.listWrapper.loadData();
    },
    select(row) {
      // 多选
      if (this.multiple) {
        const index = this.selected.findIndex(item => item.Id == row.id);
        if (index != -1) {
          this.selected.splice(index, 1);
        } else {
          this.selected.push({ ...row, Id: row.id });
        }
      } // 单选
      else {
        this.selected = this.toEntityReference(row);
        this.save();
      }
    },
    toEntityReference(item) {
      return {
        Id: item.id,
        Name: item.name,
        LogicalName: ''
      };
    },
    save() {
      if (this.messageDialog && this.multiple) {
        let newSelected = this.selected.map(item => {
          this.$set(item, 'Content', this.messageContent);
          return item;
        });
        this.$bus.$emit(`choose-${this.name}`, newSelected);
      } else {
        this.$bus.$emit(`choose-${this.name}`, this.selected);
      }
      this.backView(-1);
    },
    showmessageDialog() {
      if (this.selected.length <= 0) {
        rt.showErrorToast('请选择至少一个选项');
        return;
      }
      this.messagePopup = true;
    },
    goBackClick() {
      this.$bus.$emit('go-back');
      this.backView(-1);
    },
    backView(num) {
      this.$router ? this.$router.history.go(num) : window.history.go(num);
    },
    handleRowClass(row) {
      return this.isSelected(row) ? 'is-selected' : '';
    },
    handleColDisplay(item, col) {
      let value = item[col.value];
      if (col.value === 'name') {
        value = value || item['Name'];
      }
      return col.label + (value || '');
    },
    removeSelect(item, index) {
      this.selected.splice(index, 1);
    },
    isSelected(row) {
      return this.multiple ? this.selected.some(item => item.Id === row.id) : this.selected.Id == row.id;
    },
    togglePopupDisplay() {
      this.popupVisible = !this.popupVisible;
    },
    clear() {
      this.$set(this, 'selected', []);
      this.popupVisible = false;
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .rt-popup .rt-popup-content {
  border-radius: 12px;
  overflow: scroll;
}

/deep/ .rt-popup .rt-popup-container {
  width: 70%;
}

/deep/ .rt-checker .rt-checker-item > a {
  min-width: unset;
  width: 100px;
  max-width: 100%;
}

/deep/ .rt-checkbox {
  .rt-checkbox-label {
    color: #555;
  }
}

/deep/ .rt-btn:before {
  content: none;
}
</style>

<style lang="less" scoped>
.list-item {
  margin: 10px;
  padding: 9px 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 5px;
  border-bottom: 1px solid #f0f0f0;
  background: #fff;
  .list-item__content {
    max-width: calc(~'100% - 35px');
    .list-item__row {
      line-height: 25px;
      font-size: 15px;
      color: #222;
      &:not(:first-child) {
        font-size: 13px;
        color: #888;
      }
      &.is-selected {
        color: #53a4fc !important;
      }
    }
  }
}
.popup {
  .popup-content {
    height: calc(~'100% - 60px');
    overflow: scroll;
  }
  .popup-item {
    margin: 10px 10px 6px 15px;
    font-size: 17px;
    font-weight: 500;
    color: #222;

    &.large-space {
      margin: 10px 16px 15px 15px;
    }

    &.button-group {
      display: flex;
      overflow: hidden;
      border-top: 1px solid #f0f0f0;
      margin: 0;
      bottom: 0;
      height: 50px;
      width: 100%;
    }
  }
  .contentTitle {
    font-size: 12px;
    color: #888888;
  }
  .messageLable {
    font-size: 14px;
    color: #222222;
  }
  .selectiveOptions {
    padding-right: 15px;
    font-size: 14px;
    color: #222222;
  }
}

.selectedData {
  position: absolute;
  z-index: 200;
  display: flex;
  align-items: center;
  bottom: 0;

  width: 100%;
  height: 50px;
  background: #fff;
  &__text {
    margin-left: 15px;
    font-size: 16px;
    color: #555;
    font-weight: 500;
  }
  &__icon {
    transform: rotate(-90deg);
  }
  &__button {
    margin-left: auto;
    margin-right: 9px;
    font-size: 14px;
  }
}

/deep/ .popup2 {
  .rt-popup-container {
    width: 100%;
    .rt-popup-content {
      margin-bottom: 50px;
      border-radius: 0;
    }
  }
  &__header {
    display: flex;
    align-items: center;
    &__text {
      padding: 15px 10px;
      line-height: 23px;
      color: #555;
    }
  }
  &__item {
    display: flex;
    margin: 10px;
    padding: 10px;
    background: #f7f8fa;
    &__content {
      &__text {
        &:first-child {
          font-size: 14px;
          font-weight: 500;
          color: #555;
        }
        &:nth-child(n + 2) {
          font-size: 12px;
          color: #888;
        }
      }
    }
    &__icon {
      margin-left: auto;
      align-items: center;
    }
  }
  .clear {
    margin-left: auto;
    margin-right: 10px;
    font-size: 14px;
    color: #888;
  }
}
</style>

