<template>
  <view>
    <!-- see https://uniapp.dcloud.net.cn/component/uniui/uni-popup.html#type-options   -->
    <uniPopup ref="popup" type="bottom" :safeArea="false" :isMaskClick="true" @maskClick="hide" background-color="#fff" borderRadius="20px 20px 20px 20px">
      <div class='popup-content'>
        <div class="dialog-head">
          <div class="dialog-title">
            {{ TUITranslateService.t("AIDesk.感谢您的反馈，我们会持续优化改进") }}
          </div>
          <div class="icon-container" @click="hide">
            <image v-if="isTikTok" :src="iconClose" :style="{width: '16px', height: '16px'}"></image>
            <Icon v-else :src="iconClose" width="16px" height="16px"/>
          </div>
        </div>
        <div class="dialog-select">
            <span class="dialog-session-title">
              {{ TUITranslateService.t("AIDesk.您遇到了哪方面的问题") }}
            </span>
          <div class="dialog-button-list">
            <div class="dialog-button-row" v-for="(item) in feedbackButtonList">
              <div :class="['dialog-button',item.isSelected ? 'dialog-button-selected': '']" @click="dialogButtonClick(item)">
                {{ feedbackButtonListFromStore ? item.content : TUITranslateService.t(`AIDesk.${item.content}`) }}
              </div>
            </div>
          </div>
        </div>
        <div class="dialog-other">
          <span class="dialog-session-title">
            {{ TUITranslateService.t("AIDesk.其他反馈内容") }}
          </span>
          <textarea type="text" v-model="feedbackText" class="dialog-other-input" maxlength="200"/>
        </div>
        <div class="dialog-foot">
          <div :class="isSubmitEnabled ? 'dialog-submit' : 'dialog-submit disabled'" @click="submit">
            {{ TUITranslateService.t("AIDesk.提交") }}
          </div>
        </div>
      </div>
    </uniPopup>
  </view>
</template>
<script lang="ts">
import uniPopup from "../../common/uni-ui/uni-popup/components/uni-popup/uni-popup.vue";
import Icon from "../message-list/message-elements/message-desk/message-desk-elements/customer-icon.vue";
import TUIChatEngine, {
  TUITranslateService,
  TUIStore,
  StoreName, TUIChatService,
} from '../../../@aidesk/uikit-engine';
import iconClose from '../../../assets/dialog-close.png';
import { Toast, TOAST_TYPE } from "../../../components/common/Toast/index-uniapp";
import Log from "../../../utils/logger";
import { isTikTok } from "../../../utils/env";
import { CUSTOM_MESSAGE_SRC } from "../../../constant";
import { closeBottomPopup, showBottomPopup } from "../../../utils/utils";

export default {
  components: {
    uniPopup,
    Icon,
  },
  data() {
    const feedbackButtonList = [
      { id:'101', content: '答非所问', isSelected: false },
      { id:'102', content: '信息错误', isSelected: false },
      { id:'103', content: '格式不规范', isSelected: false },
      { id:'104', content: '内容不完整', isSelected: false },
      { id:'105', content: '未匹配相关内容', isSelected: false },
      { id:'106', content: '上下文理解错误', isSelected: false },
    ];
    let feedbackButtonListFromStore = false;
    let feedbackText = '';
    return {
      TUITranslateService,
      iconClose,
      feedbackButtonList,
      feedbackButtonListFromStore,
      feedbackText,
      isTikTok,
      _messageInfo: {},
    }
  },
  mounted() {
    TUIStore.watch(StoreName.CUSTOM, {
      feedbackTags: this.onFeedbackTags
    });
  },
  unmounted() {
    TUIStore.unwatch(StoreName.CUSTOM, {
      feedbackTags: this.onFeedbackTags
    });
  },
  computed: {
    isSubmitEnabled() {
      const selectedList = this.feedbackButtonList.filter((item) => item.isSelected);
      if (selectedList.length === 0 && this.feedbackText.trim() === '') {
        return false;
      }
      return true;
    }
  },
  methods: {
    // 点击关闭 button，默认发送 dislike，然后关闭 popup
    hide() {
      this.postFeedback(2, this._messageInfo, false);
      this.reset();
    },
    dialogButtonClick(item) {
      item.isSelected = !item.isSelected;
    },
    onFeedbackTags(data) {
      if (!data) {
        return;
      }
      this.feedbackButtonListFromStore = true;
      this.feedbackButtonList = data;
    },
    reset() {
      this.feedbackButtonList.forEach(item => {
        item.isSelected = false;
      });
      this.feedbackText = "";
      closeBottomPopup(this.$refs.popup);
    },
    async postFeedback(type: number, messageInfo: Object, withReasons = false) {
      Log.i(`postFeedback type:${type} messageInfo:`, messageInfo);
      let feedbackDetail = {
        type,
        menuSelected: [],
        otherContent: '',
      };
      // 是否需要带上反馈原因（不带上就是默认点赞或者默认点踩）
      if (withReasons) {
        if (this.feedbackText) {
          feedbackDetail.otherContent = this.feedbackText;
        }
        feedbackDetail.menuSelected = this.feedbackButtonList.filter((item) => item.isSelected).map(item => ({ id: item.id, content: item.content }));
      }
      TUIChatService.sendCustomMessage({
        to: messageInfo.toAccount,
        conversationType: TUIChatEngine.TYPES.CONV_C2C,
        payload: {
          data: JSON.stringify({
            src: CUSTOM_MESSAGE_SRC.SEND_FEEDBACK,
            customerServicePlugin: 0,
            feedbackDetail,
            messageInfo,
          }),
        },
      }, { onlineUserOnly: true });
    },
    async submit() {
      await this.postFeedback(2, this._messageInfo, true);
      this.showToast();
      this.reset();
    },
    showToast() {
      Toast({
        message: TUITranslateService.t('AIDesk.提交成功'),
        type: TOAST_TYPE.SUCCESS,
        duration: 1000,
      });
    },
    onLike(messageInfo: Object) {
      this.postFeedback(1, messageInfo, false);
    },
    onDislike(messageInfo: Object) {
      this._messageInfo = messageInfo;
      showBottomPopup(this.$refs.popup);
    }
  }
}
</script>
<style scoped lang="scss">
.popup-content {
  background-color: #fff;
  background-image: url("https://web.sdk.qcloud.com/im/desk/assets/background_mobile_1.png");
  border-radius: 20px 20px 0px 0px;
  width: 100vw;
  max-height: 80vh;
  overflow-y: auto;
  z-index: 100000;

  .dialog-head {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 5px;

    .dialog-title {
      font-weight: 500;
      font-size: 16px;
      padding: 20px;
    }

    .icon-container {
      margin: 3px 20px 0 0;
    }
  }

  .dialog-select {
    padding: 0 20px;
    margin-top: 0;

    .dialog-button-list {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      justify-content: center;
      align-items: center;
      gap: 12px;
      margin-top: 10px;

      .dialog-button-row {
        flex: 0 0 48%;
        min-width: 0;

        .dialog-button {
          border-radius: 8px;
          border: 1px solid #E4E8EF;
          background: #F9FAFC;
          padding: 4px 16px;
          display: flex;
          justify-content: center;
          font-size: 12px;
          color: #0f1014;
          cursor: pointer;
          text-align: center;
          align-items: center;
          min-height: 30px;
          height: 100%;

          &-selected {
            border-radius: 8px;
            border: 1px solid #1C66E5;
            background: rgba(28, 102, 229, 0.10);
            color: #0052d9;
          }
        }
      }
    }
  }

  .dialog-other {
    margin: 20px 0 10px 0;
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 0 20px;
    .dialog-other-input {
      border-radius: 12px;
      border: 1px solid #E4E8EE;
      background: #F9FAFC;
      height: 75px;
      width: 96%;
      padding: 5px;
      font-size: 12px;
      display: flex;
      align-items: flex-start;
      align-self: stretch;
      resize: none;
      &::placeholder {
        color: var(---Black-6, rgba(0, 0, 0, 0.25));
        font-size: 12px;
      }
    }
  }

  .dialog-foot {
    padding: 20px;
    .dialog-submit {
      padding: 9px 33px;
      border-radius: 20px;
      background: #1C66E5;
      font-weight: 500;
      font-size: 16px;
      color: #fff;
      cursor: pointer;
      text-align: center;
    }
    .disabled {
      background: #C0E4FF;
      color: #fff;
      cursor: not-allowed;
    }
  }
}

.dialog-session-title {
  color: #4D586D;
  font-size: 12px;
}
</style>
