<template>
  <web-view src="https://eshangtech.com/deepseek/"></web-view>
  <!-- <web-view src="https://ahyd.eshangtech.com/robot/"></web-view> -->
  <!-- <web-view src="https://saas.eshangtech.com/robot/robot"></web-view> -->
  <!-- <view class="main" v-if="false">
    <view class="mainTop" :style="{
      height: menu.bottom + 6 + 'px',
      paddingTop: menu.top - 6 + 'px',
    }">
      <view class="mainTopContent" :style="{ height: menu.height + 12 + 'px' }">
        <image class="backIcon" src="https://eshangtech.com/ShopICO/ahyd-BID/commercial/navigation-left.svg" />
        <view class="robotBox">
          <image class="robotImg" src="https://eshangtech.com/ShopICO/ahyd-BID/robot/robotIcon.png" />
          <view class="robotDetail">
            <span class="name">小驿</span>
            <span class="desc">商业智能助理 </span>
          </view>
        </view>
      </view>
    </view>

    <view class="dialogContentBox">
      <view :class="item.type === 1 ? 'item itemLeft' : 'item rightItem'" v-for="(item, index) in dialogueList"
        :key="index" :style="{ marginTop: index !== 0 ? '8px' : '' }">
        <view :id="'printBox' + index" :class="item.type === 1 ? `dialogItem white` : `dialogItem green`">
          {{ item.text || "" }}
          <view class="line" v-if="item.searchType === 'default'"></view>

        </view>
      </view>

      <view class="loadingBox" v-if="isLoading"> 小驿分析中... </view>
    </view>

    <view class="inputBox">
      <div class="textBox">
        <textarea class="searchText" :value="searchText" @input="handleInput" auto-height :maxlength="500"
          placeholder="有问题尽管问我～" confirm-type="search" @confirm="handleSubmit" />
      </div>

      <view class="searchBtn" @click="handleSubmit"> 发送 </view>
    </view>
  </view> -->
</template>
<script>
import request from "@/util/index.js";
export default {
  data() {
    return {
      searchText: "",
      dialogueList: [], // 对话list  type 1 是居左 2 是居右 searchType default
      printText: "",
      isLoading: false, // 是否加载中
      useInfo: {},
      menu: {},
      nowTime: new Date().getTime()
    };
  },
  onLoad() {
    this.menu = uni.getMenuButtonBoundingClientRect();
    console.log("menu", this.menu);
    this.dialogueList.push({
      text: `您好！我是服务区商业智能助理小驿。\n您想了解服务区哪些方面的信息？`,
      type: 1,
      searchType: "default",
    });
    this.handlePrintText();
    let userInfo = uni.getStorageSync("vuex");
    userInfo = JSON.parse(userInfo);
    this.useInfo = JSON.parse(JSON.stringify(userInfo));
    // this.printText = `您好！我是服务区商业智能助理小驿。<br>您想了解服务区哪些方面的信息？`
  },
  methods: {
    handleSubmit() {
      console.log('111');

      let list = this.dialogueList;
      console.log("this.searchText", this.searchText);
      if (this.searchText) {
        list.push({ text: this.searchText, type: 2 });
        this.dialogueList = list;
        this.$forceUpdate();
        this.handleGetData();
        this.searchText = "";
      }
    },
    // 输入框中的值
    handleInput(e) {
      console.log("e", e);
      this.searchText = e.detail.value;
    },
    // 查询的方法
    async handleGetData() {
      this.isLoading = true;
      const req = {
        Sentence: this.searchText,
        ProvinceCode: "340000",
        DialogCode: this.nowTime,
      };
      const data = await request.$webGet(
        "CommercialApi/Analysis/TranslateSentence",
        req
      );

      console.log('datadatadatadata', data);
      if (data.Result_Data.AnalysisRuleId) {
        let configReq = {
          searchParameter: {
            ANALYSISRULE_IDS: data.Result_Data.AnalysisRuleId,
            current: 1,
            pageSize: 10,
          },
          sortstr: "RULE_PRIORITY asc",
          PageIndex: 1,
          pagesize: 999999,
        }


        const configData = await request.$webPost(
          "EShangApiMain/Analysis/GetANALYSISRULEList",
          configReq
        )
        console.log('configDataconfigDataconfigDataconfigData', configData);
        if (configData.Result_Data.List && configData.Result_Data.List.length > 0) {
          let configDetail = configData.Result_Data.List[0];

          if (configDetail) {


          }

        }
      }
      // return
      // this.isLoading = true;
      // const data = await request.$webGet(
      //   "CommercialApi/Analysis/TranslateSentence",
      //   { Sentence: this.searchText }
      // );
      // console.log("data", data);

      // await this.handleGetRequestAnwers(data.Result_Data.AnalysisRuleId, data.Result_Data)


      // if (data.Result_Code === 999) {
      //   this.dialogueList.push({
      //     text: `'小驿还无法理解，请换个说法我会不停努力学习的！'`,
      //     type: 1,
      //   });
      // } else {
      //   let str = data.Result_Data.RevenueAnalysis + "\n";
      //   let list = data.Result_Data.ServerpartList;
      //   if (list && list.length > 0) {
      //     list.forEach((item) => {
      //       let obj = item["RevenueINC"];
      //       if (str) {
      //         str += `${item.ServerpartName}：${this.formatNumber(
      //           obj.curYearData / 10000
      //         )}万元${obj.increaseRate > 0
      //           ? "，同比增幅"
      //           : obj.increaseRate < 0
      //             ? "，同比降幅"
      //             : ""
      //           }${obj.increaseRate || ""}\n`;
      //       } else {
      //         str = `${item.ServerpartName}：${this.formatNumber(
      //           obj.curYearData / 10000
      //         )}万元${obj.increaseRate > 0
      //           ? "，同比同比增幅"
      //           : obj.increaseRate < 0
      //             ? "，同比降幅"
      //             : ""
      //           }${obj.increaseRate || ""}\n`;
      //       }
      //     });
      //   }

      //   this.dialogueList.push({ text: str, type: 1 });
      // }
      this.isLoading = false;
    },
    // 打印机效果
    handlePrintText() {
      const query = wx.createSelectorQuery();
      const contentBox = query.select(
        `#printBox${this.dialogueList && this.dialogueList.length > 0
          ? this.dialogueList.length - 1
          : 0
        }`
      );
      console.log("contentBox", contentBox);
    },
    formatNumber(num) {
      // 确保输入为数字类型
      num = Number(num);
      if (isNaN(num)) return "0.00"; // 处理无效数字
      // 将数字转换为字符串，并分离整数部分和小数部分
      let parts = num.toString().split(".");
      // 处理小数部分，不进行四舍五入，直接截取小数点后两位
      let decimalPart = parts[1] ? parts[1].substring(0, 2) : "00";
      if (decimalPart.length < 2) {
        decimalPart = decimalPart.padEnd(2, "0"); // 不足两位补零
      }
      // 格式化整数部分，添加千分号
      let integerPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      // 返回带千分号的整数部分和保留两位小数的数字
      return `${integerPart}.${decimalPart}`;
    },

    // 拿到问题的答案方法
    async handleGetRequestAnwers(id, resData) {
      const data = await request.$webGet(
        "EShangApiMain/Analysis/GetANALYSISRULEDetail",
        { ANALYSISRULEId: id }
      );

      console.log('datadatadatadata', data);

      let newData = data.Result_Data

      if (newData) {
        let newReq = JSON.parse(`${newData?.PARAM_TEMPLATE}`)
        let newRESPONSE_CONFIG = JSON.parse(`${newData?.RESPONSE_CONFIG}`)
        let newPARSING_RULES = JSON.parse(`${newData?.PARSING_RULES}`)

        let lastReq = {}
        if (newReq) {
          for (let key in newReq) {
            let realKey = newPARSING_RULES[key]
            console.log('realKey', realKey);
            // formatType   0：数值  1：字段  2：取缓存  3：取年份    name 就是去resData里面去字段    value  非1 的时候会有值
            if (realKey) {
              if (realKey.formatType === 1) {
                lastReq[key] = resData[realKey.fieldName]
              } else if (realKey.formatType === 0) {
                lastReq[key] = realKey.value
              } else if (realKey.formatType === 2) {
                if (key === 'pushProvinceCode') {
                  lastReq[key] === '340000'
                } else {
                  lastReq[key] = this.useInfo[realKey.fieldName]
                }
              } else if (realKey.formatType === 3) {
                lastReq[key] = resData[realKey.fieldName] ? moment(resData[realKey.fieldName]).format('YYYY') : ''
              }
            }

          }
        }

        let [requestMethod, resultType, type] = []
        if (newData.OUTPUT_FORMAT) {
          // requestMethod 请求方法  resultType 结果类型   type 要不要wrapTreeNode 对结果
          [requestMethod, resultType, type] = newData.OUTPUT_FORMAT.split('|')
        }

        const lastData = await this.handleRequest(newData.API_ENDPOINT, requestMethod === 'post' ? {
          method: 'POST',
          data: lastReq
        } : {
          method: 'GET',
          params: lastReq
        }
        )
        console.log('lastData', lastData);
      }


    },
    // 公共调用方法
    async handleRequest(url, params) {
      console.log('url', url);
      console.log('params', params);

      const data = params.method === 'GET' ?
        request.$webGet(
          url,
          params.params
        ) :
        request.$webPost(
          url,
          params.params
        )


      // const data = await request(url, params)

      if (data.Result_Code !== 100) {
        return []
      }

      return data.Result_Data
    }
  },
};
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  height: 100vh;
  // background: #f0f0f0;
  background-image: url("https://eshangtech.com/ShopICO/ahyd-BID/robot/robotBackground.png");
  background-repeat: no-repeat;

  .mainTop {
    width: 100%;
    box-sizing: border-box;

    .mainTopContent {
      width: 100%;
      box-sizing: border-box;
      padding-left: 32rpx;
      display: flex;
      align-items: center;

      .backIcon {
        width: 52rpx;
        height: 52rpx;
        margin-right: 16rpx;
      }

      .robotBox {
        display: flex;
        align-items: center;

        .robotImg {
          width: 68rpx;
          height: 68rpx;
          margin-right: 16rpx;
        }

        .robotDetail {
          display: flex;
          flex-direction: column;

          .name {
            font-family: PingFangSC, PingFang SC;
            font-weight: 600;
            font-size: 28rpx;
            color: #090c1a;
            line-height: 40rpx;
            text-align: left;
            font-style: normal;
          }

          .desc {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 24rpx;
            color: #787879;
            line-height: 36rpx;
            text-align: justify;
            font-style: normal;
          }
        }
      }
    }
  }

  .dialogContentBox {
    width: 100%;
    height: calc(100vh - 100px);
    overflow-y: scroll;
    box-sizing: border-box;
    padding: 32rpx;

    .item {
      display: flex;
      align-items: center;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 30rpx;
      color: #090c1a;
      line-height: 44rpx;
      text-align: left;
      font-style: normal;

      .dialogItem {
        max-width: calc(100vw - 64rpx);
        display: block;
        box-sizing: border-box;
        padding: 24rpx 32rpx;
        border-radius: 4px;
        background: #ffffff;
        border-radius: 0rpx 24rpx 24rpx 24rpx;

        .line {
          width: 100%;
          height: 2rpx;
          background: #f2f2f2;
          border-radius: 16rpx;
          margin: 24rpx 0;
        }

        .defaultBox {
          .clickItem {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 30rpx;
            color: #2363ff;
            line-height: 44rpx;
            text-align: left;
            font-style: normal;
          }
        }
      }

      .white {
        background: #fff;
        color: #000;
      }

      .green {
        background: #12a153ff;
        color: #fff;
      }
    }

    .itemLeft {
      justify-content: flex-start;
    }

    .rightItem {
      justify-content: flex-end;
    }

    .loadingBox {
      font-size: 12px;
      color: #ccc;
      width: 100%;
      display: flex;
      justify-content: center;
    }
  }

  .inputBox {
    width: 100%;
    min-height: 180rpx;
    background: #fff;
    position: fixed;
    left: 0;
    bottom: 0;
    box-sizing: border-box;
    padding: 16rpx 32rpx;
    padding-bottom: env(safe-area-inset-bottom);
    display: flex;
    align-items: center;

    .microphone {
      width: 48rpx;
      height: 48rpx;
      margin-right: 16rpx;
    }

    .textBox {
      width: calc(100% - 90px);
      min-height: 88rpx;
      background: #f2f3f7;
      border-radius: 44rpx;
      box-sizing: border-box;
      padding: 26rpx 16rpx 0;
    }

    .searchText {
      width: 100%;
    }

    .searchBtn {
      width: 80px;
      height: 40px;
      box-sizing: border-box;
      color: #fff;
      background: #07c160;
      border-radius: 4px;
      margin-left: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
    }
  }
}
</style>
