<template>
  <view class="status_bar"></view>
  <view  class="box" >
    <view class="navi">
      <view class="navi_but" @click.stop="showDrawer">
        <image src="../../static/moreThan.png" class="img"></image>
      </view>
      
      <view class="text">惊喜视界</view>
    </view>
    <view class="contentCell">
      <!-- <view class="content_cell_sys">
        <image src="../../static/noLogin.png" style="width: 60rpx;height: 60rpx;" />
        <view class="cell_text">嘿，好久不见，甚是想念。</view>
      </view>
      <view class="content_cell_user">
        <image src="../../static/noLogin.png" style="width: 60rpx;height: 60rpx;" />
        <view class="cell_text">白菜妖精</view>
      </view>
     </view> -->
     <scroll-view scroll-y style="height: calc(100vh - 400rpx);" :scroll-into-view="scrollToView"  scroll-with-animation>
        <view v-for="(item,index) in historyList" :key="index" class="cell" :id="'msg' + index"
      :class="{ 
          'cell_sys' : item.usertType === 'sys',
          'cell_user': item.usertType === 'user'
        }">
      <view>
        <view class="avatar" :style="{
          justifyContent:item.usertType === 'sys' ? 'flex-start' : 'flex-end'
        }">
          <view v-if="item.usertType === 'user'" class="nickname" >
            <text>{{ item.nickName }}</text>
          </view>
          <!-- 
          惊喜视界头像: https://image.jxc4.com/image/e1a731b7a1bff6e0afd0cd987f421daf.png
            -->
          <image :src="item.usertType === 'sys' ? 'https://image.jxc4.com/image/e1a731b7a1bff6e0afd0cd987f421daf.png' : '../../static/noLogin.png'" class="img" />
          <view v-if="item.usertType === 'sys'" class="nickname">
            <text >{{ item.nickName }}</text>
          </view>
        </view>
        <view class="content">
          <text>{{ item.usertType === 'sys' && index !== 0 ? `根据【${item.content}】生成的图片信息如下：`: item.content }}</text>
        </view>
        <!--  :style="{
          overflow:item.vendorDescription.length >1 ? 'hidden' : '',
          overflowX:item.vendorDescription.length >1 ? 'auto': '',
          width:item.vendorDescription.length >1  ? '600rpx': '400rpx'
        }" -->
        <view v-if=" item.usertType === 'sys' && index !==0 " class="backImg" 
        :class="{'moreImg':item.vendorDescription.length >1}"
       >
          <!-- <view > .split(',') -->
          <view v-for="(url,i) in item.vendorDescription">
            <!-- {{ url }}  -->
            <image  :src="url"  alt="图片加载中..." class="img"  @tap="previewImg(item.vendorDescription)" @error="handleImgError(index,i)" />
          </view>
          <!-- </view> -->
          
        </view>
      </view>

     </view>
     </scroll-view>
   
    </view>
    <view class="productImgTip" v-show="isLoadingImg">
      <text class="txt" style="--i: 1">拼</text>
      <text class="txt" style="--i: 2">命</text>
      <text class="txt" style="--i: 3">生</text>
      <text class="txt" style="--i: 4">图</text>
      <text class="txt" style="--i: 5">中</text>
      <text class="txt" style="--i: 6">,</text>
      <text class="txt" style="--i: 7">请</text>
      <text class="txt" style="--i: 8">稍</text>
      <text class="txt" style="--i: 9">后</text>
      <text class="txt" style="--i: 10">.</text>
      <text class="txt" style="--i: 11">.</text>
      <text class="txt" style="--i: 12">.</text>
    </view>
    <view class="foot_send" >
      <view style="width: 60rpx;height: 60rpx;border-radius:50%;margin-right: 20rpx;font-size: 72rpx;margin-left: 20rpx;border:1rpx solid #3c3c3c;text-align: center;line-height: 60rpx;" @click="selectImg">+</view>
      <input v-model="keyWord" placeholder="说点什么吧......" style="width: 100%;" >
      <view style="border-radius: 20rpx;margin-right: 20rpx;width: 160rpx;height: 60rpx;display: flex;background-color: #007aff;color:#fff;align-items: center;justify-content: center;" @click="sendText">发送</view>
    </view>
    <view class="AILogo">内容由AI生成，仅供参考</view>
  </view>
  <!-- {{ isShowDrawer }} -->
  <jx-drawer
    :isShowDrawer="isShowDrawer"
    @closeDrawer="closeDrawer">
    <view class="drawer">
      <view class="status_bar"></view>
      <view class="content" v-if="isShowDrawer">
        <view style="border: none;">
          <view  class="login" @click="jumpLogin">
            <view>
              <image :src="isLogin && userInfo.headUrl ? userInfo.headUrl : '../../static/noLogin.png'" class="avatar"></image>
            </view>
            <view class="login_but" v-if="!isLogin" style="font-weight: bold;">登录</view>
            <view class="login_but" v-else >
              <view style="width: 380rpx;white-space: nowrap;overflow:hidden;text-overflow: ellipsis;font-weight: bold;">{{ userInfo.nickName }}</view>
              <view style="font-size: 36rpx;margin-top: 20rpx;">账户余额:¥{{ accountBalance.toFixed(2) }}</view>
            </view>
          </view>
          <!-- 滑动内容 -->
          <scroll-view class="drawer_center" scroll-y="true">
            <jx-cell :text="'充值'" @jumpTo="jumpRefill"></jx-cell>
            <jx-cell :text="'充值记录'" @jumpTo="jumpMyOrder"></jx-cell>
            <jx-cell :text="'我的推广码'" @jumpTo="myPromte"></jx-cell>
            <jx-cell :text="'查看历史话题'" @jumpTo="queryHistoryChat"></jx-cell>
            <jx-cell :text="'密码管理'" @jumpTo="passwodMan"></jx-cell>
            <jx-cell :text="'联系客服'" @jumpTo="callPhone"></jx-cell>
          </scroll-view>
        </view>
        <view>
          <view @click="exitLogin" class="exitLogin" v-if="isLogin">退出登录</view>
          <view class="foot_ball">您好欢迎来到惊喜视界</view>
        </view>
      </view>
    </view>
  </jx-drawer>
</template>

<script setup lang="ts">
import jxDrawer from '@/components/jx-drawer/index.vue'
import jxCell from '@/components/jx-cell/index.vue'
import toast from '@/utils/toast'
import {  computed, ref } from 'vue'
import { store } from '@/store'
import order from '@/api/https/order'
import { onLoad, onShow } from '@dcloudio/uni-app'
import useGlobalFunc from '@/composables/useGlobalFunc'
import { qiniuyun } from '@/utils/qiniuUploader'
import { timeFormatD, timeFormatDateHMS } from '@/utils/tools'

const {
  previewImage, // 预览图片
} = useGlobalFunc()

let isLoadingImg = ref<boolean>(false)
const keyWord = ref<string>('') 
let isShowDrawer = ref(false)
const scrollToView = ref<string>('')

onLoad((query) => {
  console.log('初始化,query',query)
  // getAccountInvoice()
})


/**
 * 加载图片信息
 */
const defaultImg = 'https://image.jxc4.com/image/7f8c15f44bbcdbd9174df1797dfe74dd.jpg'
function handleImgError(index:number,i:number | string){
  // 防止无限循环：如果已经是默认图，不再替换
  // if (historyList.value[index].vendorDescription !== defaultImg) {
  //   historyList.value[index].vendorDescription = defaultImg
  // }
  if(historyList.value[index].vendorDescription[i] !== defaultImg ){
     historyList.value[index].vendorDescription[i] = defaultImg
  }
  // console.log('加载图片信息',e,'number',index)
}

/*************************************************
 * 预览图片
 */
 function previewImg(url:string[]) {
  // let arr = [skuName.img,skuName.img2,skuName.img3,skuName.img4,skuName.img5].filter(item => { return item && item.length > 0 })
  
  previewImage(url)
}

let arr = ['两只老虎']

/**
 * 密码管理
 */
function passwodMan(){
  uni.navigateTo({url:'/subPages/login/passMan'})
}

/**
 * 联系客服
 */
function callPhone(){
  uni.makePhoneCall({
      phoneNumber: '18048531223',
      success() {
          console.log('拨号完成')
      },
      fail() {
          toast('取消拨号')
      }
  })

  uni.vibrateShort({})
}
// function onChange(){
//   console.log('聚焦11111111',isShowDrawer.value)
// }
/**
 * 登录状态
 */
const isLogin = computed(() => {
  return store.getters['serveInfo/isLogin']
})


/**
 * 用户信息
 */
const userInfo =computed(() => {
  return uni.getStorageSync('userInfo')
})

/**
 * 账户余额
 */
const accountBalance = computed(() => {
  return store.getters['serveInfo/accountBalance']
})


/**
 * 上传图片 图生图
 */
// const uploadImgUrl = ref<string>('')
const qiniuyunUploadImg = qiniuyun() // 七牛云sdk
async function uploadImg(img: string){
      let suffix = img.indexOf('.png') === -1 ? '.jpg' : '.png'
      let params = {
          suffix,
      }
      let res = await order.get_qiniu_upload_token(params)
      if (res.code == 0) {
          let filePath = img
          qiniuyunUploadImg.upload(
              filePath,
              (res: any) => {
                  // 得到图片网址
                  let url = 'https://image.jxc4.com/'
                  let imgUrl = url + res.key
                  let str = uni.getStorageSync(imgUrl)
                  str = str && str.length ? ',' + imgUrl : imgUrl
                  uni.setStorageSync('uploadImgUrl',str)
                  toast('图片上传成功，请告诉我怎么修改文字',)
                  // sendClick({ msg: imgUrl, type: 2 })
                  // sendText(imgUrl)
              },
              (err: AnyObject) => {
                  toast('上传失败，请重试', 2)
              },
              {
                  uploadURL: 'https://up-z2.qiniup.com/',
                  key: res.data.fileName,
                  uptoken: res.data.token,
              }
          )
      } else {
          toast('上传失败', 2)
      }
}

function selectImg(){
  if(!isLogin.value) return toast('请登录')
   uni.chooseImage({
      success: (res: any) => {
        // console.log('选择图片成功的路径',res)
          res.tempFiles.forEach(async(item: AnyObject) => {
            // console.log('选择多种图片时的数据',item)
              await uploadImg(item.path)
          })
      },
  })
}

/**
 * 打开
 */
function showDrawer(){

  isShowDrawer.value = true
}

/**
 * 关闭
 */
function closeDrawer(){
  isShowDrawer.value = false
}

/**
 * 退出登录
 */
function exitLogin(){
  uni.clearStorage()
  store.commit('serveInfo/changeLoginStatus',false)
}

/**
 * 跳转到登录
 */
async function jumpLogin(){
  // let userInfo = uni.getStorageSync('userInfo') || ""
  // if(!userInfo) await store.dispatch('serveInfo/wxLogin',{authType:'wx',isJudg:true}) // 查看当前用户是否为新用户
  uni.navigateTo({url:'/subPages/login/index'})
 
}

/**
 * 充值
 */
function jumpRefill() {
  uni.navigateTo({url:'/subPages/mine/refill'})
}


/**
 * 我的充值记录
 */
function jumpMyOrder(){
  console.log('我的订单')
  uni.navigateTo({url:'/subPages/mine/order'})
}

/**
 * 我的推广码
 */
function myPromte(){
  console.log('我的推广码------------')
  uni.navigateTo({url:'/subPages/mine/promote'})
}

/**
 * 查看历史话题
 */
function queryHistoryChat(){
  console.log('查看历史话题')
  uni.navigateTo({url:'/subPages/mine/historyTopic'})
}

onShow(() => {
  // 刷新物料袋
  getAccountInvoice()
})


const historyList = ref<AnyObject[]>([{
  // id:'-1',
  usertType:'sys',
  nickName:'惊喜视界',
  content:'嘿，好久不见，甚是想念。',
  // vendorDescription:'https://image.jxc4.com/image/22bf05e025b99aa79ca44f6ffca425e6.jpg' // 图片url
},
// {
//   // id:'-1',
//   usertType:'user',
//   nickName:'匿名11',
//   content:'白菜妖精'
// }
])
async function getAccountInvoice(){
  historyList.value = [{
    usertType:'sys',
    nickName:'惊喜视界',
    content:'嘿，好久不见，甚是想念。',
  }]
  try {
    // if(!isLogin.value) return
    let time = new Date()
    let obj = {
      rank:'desc', // desc/asc
      orderBy:'created_at',
      // keyword:keyword.value,
      beginTime:timeFormatDateHMS(+new Date(time.getTime() - 1000 * 60 * 60 * 24 * 1)),
      endTime:timeFormatDateHMS(time.getTime()), 
      // pageNum:page.value,
      // pageSize:pageSize.value
    }
    let res = await order.queryAccountInvoice(obj)
    if(res.code == 0 && res.data.total){

      let newArr = await combine(res.data.list.reverse() || [])
      historyList.value = historyList.value.concat(newArr || [])
      scrollToView.value = 'msg' + (historyList.value.length -1)
      console.log(historyList.value,'查询用户的使用记录',res)
      // totalCount.value = res.data.total || 0
      // [
      //   {
              // createdAt: "2026-04-29 17:27:06"
              // id: 10005
              // jxPrice: 66
              // orderId: "88515179626607"
              // payMoney: 55
              // status: "1"
              // tokens: 100000
              // updatedAt: "2026-04-29 17:27:06"
              // urls: ""
              // userDescription: "白菜妖精" // 土豆娃娃在云端游玩
              // userId: "FCB66AB342B011F1AB95001D4320A900"
              // vendorDescription: "https://ark-acg-cn-beijing.tos-cn-beijing.volces.com/doubao-seedream-5-0/0217774542470044acec6226078eafffb431763a23ccdf0fb00a2_0.png?X-Tos-Algorithm=TOS4-HMAC-SHA256&X-Tos-Credential=AKLTYWJkZTExNjA1ZDUyNDc3YzhjNTM5OGIyNjBhNDcyOTQ%2F20260429%2Fcn-beijing%2Ftos%2Frequest&X-Tos-Date=20260429T091755Z&X-Tos-Expires=86400&X-Tos-Signature=1cca8c0be33555d051b96aa8962e5437984b0d55360242b6fa16e0f9d0181b77&X-Tos-SignedHeaders=host"
              // vendorId: "doubao"
              // vendorPrice: 22
              // vendorStatus: "1"
      //   }
      // ]
      console.log('打印物料电',historyList.value)
    }
    // popup.value.close()
  } catch (error) {
    
  }

}

function combine(arr:AnyObject[]){
  let brr:AnyObject = []
  let userInfo = uni.getStorageSync('userInfo')
  arr.forEach(item => {
    brr.push({
      usertType:'user',
      nickName:userInfo.nickName,
      content:item.userDescription,
    })
    brr.push({
      ...item,
      usertType:'sys',
      nickName:'惊喜视界',
      content:item.userDescription,
      vendorDescription:item.vendorDescription.includes(',') ? item.vendorDescription.split(',') : [item.vendorDescription] 
    })
  })
  return brr
}

/**
 * 发送文本
 */
async function sendText(){
  try {
    // let url = uni.getStorageSync('uploadImgUrl')
    // if(!isLogin.value) return toast('请登录')
    if(keyWord.value.length === 0) return toast('请输入文字内容')
    isLoadingImg.value = true
    console.log('发送文本的内容111111111111111',keyWord.value)
    let userInfo = uni.getStorageSync('userInfo')
    console.log('userInfo',userInfo,'nickName',userInfo.nickName)
    historyList.value.push({
        usertType:'user',
        nickName:userInfo.nickName,
        content:keyWord.value,
    })
    scrollToView.value = 'msg' + (historyList.value.length -1)
    
    let obj:AnyObject = {
      vendorModel:'doubao',
      prompt:keyWord.value,
      isTools:false // 是否联网搜索
    }
    let url = uni.getStorageSync('uploadImgUrl')
    console.log('11111111',url)
    if(url) obj.image = url // 多张图，逗号隔开
    // console.log('中间的菜篮,,参数',obj)
    // return
    let res = await order.useText2Msg(obj)
    toast('发送成功，请等待......')
    if(res.code == 0){
      let arr = [{
         usertType:'sys',
          nickName:'惊喜视界',
          content:keyWord.value,
          vendorDescription:res.data.imgs
      }]
     
      // historyList.value.push({
      //     usertType:'sys',
      //     nickName:'惊喜视界',
      //     content:keyWord.value,
      //     vendorDescription:res.data.imgs[0]
      // })
      historyList.value = historyList.value.concat(arr)
      scrollToView.value = 'msg' + (historyList.value.length -1)
      console.log(historyList.value,'打印返回图片的信息',res)
      isLoadingImg.value = false
      keyWord.value = ''
      delImg(url)
      // getAccountInvoice
    }else{
      // setTimeout(()=>{
      //   console.log('2000之后再回来',res)
      //   toast(res.desc)
      //   isLoadingImg.value = false
      // },2000)
      toast(res.desc)
      isLoadingImg.value = false
    }
  } catch (error) {
    console.log('error',error)
    isLoadingImg.value = false
    toast('生成错误')
  }
}

/**
 * 删除图片
 */
async function delImg(urls:string){
  if(urls.length === 0) return
  let res = await order.del_qiniu_img(urls)
  uni.setStorageSync('uploadImgUrl','')
  console.log('删除图片的结果',res)
}
</script>

<style lang="scss" scoped>
  .status_bar {
    height: var(--status-bar-height);
    width: 100%;
  }

// --status-bar-height
  .box{
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border: none;
    height: calc(100vh - 100rpx);
    // border: 1rpx solid red;

    .navi{
      padding: 10rpx;
      height: 100rpx;
      width: 100%;
      display: flex;
      background-color: #efefef;
      align-items: center;
      justify-content: flex-start;

      .navi_but{
        width: 70rpx;
        height: 70rpx;
        border-radius: 50%;
        background-color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0rpx 0rpx 10rpx #888888;
        margin-top: 10rpx;

          .img{
            width: 40rpx;
            height: 40rpx;
        }
      }

      .text{
        margin-left: 20rpx;
        font-size: 50rpx;
        font-weight: bold;
        height: 60rpx;
        line-height: 60rpx;
        // margin-bottom: 10rpx;
      }
    }

    .contentCell{
      flex: 1;
      background-color: #efefef;
      padding: 20rpx 10rpx;
      overflow-x: auto;
      // width: 50%;
      // border: 1rpx solid rgb(81, 255, 0);

      .cell{
        margin-bottom: 30rpx;
        display: flex;
      }

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

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

      .avatar{
        // border:1rpx solid red;
        display: flex;
        margin-bottom: 20rpx;

        .img{
          width: 60rpx;
          height: 60rpx;
          border-radius: 50%;
        }
      }

      .nickname{
        // margin-top: -20rpx;
        //  border:1rpx solid rgb(30, 255, 0);
         height: 60rpx;
         line-height: 60rpx;
         padding: 0 20rpx;
      }

      .content,.backImg{
        margin-left: 10rpx;
        // border: 1rpx solid red;
        background-color: #fff;
        border-radius: 10rpx;
        padding: 10rpx;
      }

      .backImg{
        margin-top: 20rpx;
        width: 400rpx;
        display: flex;
        justify-content: flex-start;

        .img{
          // transform: scale(0.5);
          width: 400rpx;
          height: 400rpx;
        }
      }

      .moreImg{
        overflow: hidden;
        overflow-x: auto;
        width: 700rpx;
        box-sizing: border-box;
      }

      // .content_cell_sys,.content_cell_user{
      //   // display: flex;
        

      //   // .img{
      //   //   width: 60rpx;
      //   //   height: 60rpx;
      //   // }
        
      // }

      // .content_cell_sys{
      //   justify-content: flex-start;
      
      //   .cell_text{
      //     margin-left: 10rpx;
      //   }
      // }
      
      // .content_cell_user{
      //   // display: flex;
      //   justify-content: flex-end;

      //    .cell_text{
      //     margin-right: 10rpx;
      //    }
      // }

      // .cell_text{
      //   margin-left: 10rpx;
      //   // border: 1rpx solid red;
      //   background-color: #fff;
      //   border-radius: 10rpx;
      //   padding: 10rpx;
      // }
    }

  }


.foot_send{
  width: 90%;
  height: 80rpx;
  display: flex;
  align-items: center;
  margin: 0 auto;
  border: 1rpx solid #5d5d5d;
  border-radius: 50rpx;
  margin-bottom: 20rpx;
}

.AILogo{
  // border:1rpx solid red;
  text-align: center;
  color: #808080;
}

.drawer{
  border: none;

  .content{
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    height: 100vh;
  }


  .login{
    width: 100%;
    height: 140rpx;
    // line-height: 100rpx;
    // font-weight: bold;
    font-size: 40rpx;
    // text-align: center;
    border-bottom: 5rpx solid #7c7c7c;
    display: flex;
    justify-content:flex-start;
    align-items: center;
    padding: 10rpx 20rpx;
    box-sizing: border-box;
    margin-top: 20rpx;

    .avatar{
      width: 70rpx;
      height: 70rpx;
      border-radius: 50%;
    }

    .login_but{
      margin-left: 50rpx;
    }

    .drawer_center{
      height: calc(100% - 292rpx);
    }
  }


  .exitLogin{
    width: 80%;
    text-align: center;
    background-color: #ff4646;
    color: #fff;
    padding: 20rpx ;
    border-radius: 20rpx;
    margin:0 auto;
    margin-bottom: 20rpx;
  }

  .foot_ball{
    height: 140rpx;
    width: 100%;
    text-align: center;
    font-weight: bold;
    font-size: 36rpx;
  }
}



.productImgTip{
      // font-size: 48px;
      font-weight: bold;
      color: #4c4c4c;
      text-align: center;
      // margin-top: 100px;
      margin-bottom: 20rpx;
      // border: 1rpx solid red;
      padding: 20rpx;
    background-color: rgb(37 37 37 / 13%);

   .txt {
      display: inline-block;
      font-size: 40rpx;
      animation: animate 2s ease-in-out infinite;
      animation-delay: calc(0.1s * var(--i));
    }

}


@keyframes animate {
  0% {
    transform: translateY(0rpx);
  }

  20% {
    transform: translateY(-15rpx);
  }

  40%,
  100% {
    transform: translateY(0rpx);
  }
}


    // .productImgTip span {
    //     display: inline-block;
    //     animation: wordJump 1s ease-in-out infinite alternate;
    //   }
  // border: 1rpx solid red;
  // margin-bottom: 20rpx;
  // display: inline-block;
  // animation: wordJump 1s ease-in-out infinite alternate;

  //  /* 给每个字错开延迟，形成波浪效果 */
  //   .productImgTip span:nth-child(1) { animation-delay: 0s; }
  //   .productImgTip span:nth-child(2) { animation-delay: 0.1s; }
  //   .productImgTip span:nth-child(3) { animation-delay: 0.2s; }
  //   .productImgTip span:nth-child(4) { animation-delay: 0.3s; }
  //   .productImgTip span:nth-child(5) { animation-delay: 0.4s; }
  //   .productImgTip span:nth-child(6) { animation-delay: 0.5s; }
@keyframes wordJump {
      0% { transform: translateY(0); }
      100% { transform: translateY(-25px); }
    }
</style>
