<template>
  <div class="tts-module flexBox">
    <el-icon v-if="isStop" @click="paly" size="16">
      <VideoPlay />
    </el-icon>
    <template v-else>
      <Corrugation />
      <svg-icon class="desktop-svg-icon" name="tingzhi-icon" width="16" height="16" fill="#4b72ef" @click="stop" />
    </template>
    <!-- <div class="line"></div> -->
    <!-- <svg-icon name="copy-cart" width="16" height="16" fill="#878787" @click="copyText(realText)"/> -->
    <el-icon @click="copyText(realText)">
      <DocumentCopy style="width: 14px; height: 14px" />
    </el-icon>
    <!-- <div class="line"></div>-->
    <svg-icon class="desktop-svg-icon" :name="zanOrCai === 1 ? 'zan-active-icon' : 'zan-icon'" width="18" height="18" fill="#878787" @click="zanOrCaiClick(zanOrCai === 1 ? 0 : 1)" />

    <!-- 点踩建议弹框 -->
    <el-popover :visible="dialogInfo.visible" placement="left" :width="400" trigger="click" popper-class="custom-zancai-popover">
      <template #reference>
        <svg-icon class="desktop-svg-icon" :name="zanOrCai === 2 ? 'cai-active-icon' : 'cai-icon'" width="18" height="18" fill="#878787" @click="zanOrCaiClick(2)" />
      </template>
      <div>
        <div class="top-content"> 
          <svg-icon class="active-card-bg" name="active-bg" :width="119" :height="145" />
          <div class="dialog-name"><span>你的反馈将帮助我们持续进步</span><span @click="dialogInfo.visible = false" style="cursor: pointer;"><el-icon><Close /></el-icon></span></div>
          <div class="dialog-content">
            <div v-for="item in opinionList" :key="item.id" class="item-desc"  :class="item.activeFlag ? 'item-active' :''">
              <div @click="selectOpinion(item)">{{ item.name }}</div>
            </div>
          </div>
        </div>
        <div class="dialog-form">
            <p>问题描述</p>
            <el-input class="text-input not-scrollbar" v-model="dialogInfo.problemDesc" type="textarea"  :autosize="{ minRows: 3, maxRows: 8 }"  placeholder="请输入"></el-input>
          </div>
        <div class="dialog-footer">
          <el-button size="small"  @click="dialogInfo.visible = false">取消</el-button>
          <el-button size="small" type="primary" @click="dialogInfoConfirm">确定</el-button >
        </div>

      </div>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import { VideoPlay, VideoPause, DocumentCopy, Close } from "@element-plus/icons-vue"
import { onBeforeUnmount, onMounted, ref, watch, reactive } from "vue"
import Corrugation from "@/components/Corrugation.vue"
import Experience from "./module/tts"
import { copyText, require } from "@/utils/common"
import { getGlobalConfig, changeChartStatus } from "@/api/common"
import useCtx from "@/hooks/useCtx"

const props = withDefaults(
  defineProps(),
  {
    machineText: "",
    isStop: true,
    zanOrCai: 0,
    traceId: "",
    feedback: ''
  }
)

const emit = defineEmits(["changePalyStatus", "changeDialogStatus", "changeZanOrCai"])

const { $app } = useCtx()
const realText = ref("")
const opinionList = ref([
  {name: '没能理解指令', id: 1, activeFlag: false},
  {name: '没有帮助', id: 2, activeFlag: false},
  {name: '逻辑问题', id: 3, activeFlag: false},
  {name: '存在偏见', id: 4, activeFlag: false},
  {name: '敏感/有害回答', id: 5, activeFlag: false},
])
const dialogInfo = ref({
  problemDesc: '',
  visible: false
})

const selectOpinion = (item) => {
  opinionList.value.forEach(obj => {
    if(obj.id === item.id){
      obj.activeFlag = !obj.activeFlag
    }
  })
}
const dialogInfoConfirm = () => {
  let str = ''
  opinionList.value.forEach(obj => {
    if(obj.activeFlag) {
      str +=obj.name + ';'
    }
  })
  const obj = {
    traceId: props.traceId,
    status: 2,
    feedback: str + dialogInfo.value.problemDesc,// 反馈
  }
  changeChartStatus(obj).then(res => {
      if(res.header.code === -1){
        $app.$message.warning(res.header.message)
      } else {
        emit("changeZanOrCai", 2)
        dialogInfo.value.visible = false
      }
    })
}
const replaceText = (text) => {
  let mdArray = text.replace(/<ret>/g, "").replace(/\\n/g, "").replace(/\\t/g, "").replace(/\\r/g, "").replace(/<end>/g, "").replace(/\$/g, "").replace(/imes/g, "×").replace(/\\div/g, "÷")
  return mdArray
}

const moduleInstance = ref(null)

watch(
  () => props.isStop,
  (flag) => {
    flag ? moduleInstance.value?.audioPause() : moduleInstance.value?.audioPlay("")
  }
)

const paly = () => {
  // 临时方案，调用config接口刷新token判断是否登录
  getGlobalConfig()
  emit("changePalyStatus", false)
}

const stop = () => {
  emit("changePalyStatus", true)
}

const zanOrCai1 = ref(0)
const zanOrCaiClick = (val: number) => {
  // zanOrCai1.value = val;
  //** 暂时隐藏 */
  // 点赞点踩：0未评价，1点赞，2点踩
  const obj: any = {
    traceId: props.traceId,
    status: val,
    feedback: "",// 反馈
  }
  // 点踩
  if (val === 2){
    // 已经点踩过的回显反馈
    if(props.zanOrCai === 2){
      let reson = JSON.parse(props.feedback)
      opinionList.value.forEach(item => {
        if(reson[0].includes(item.name)){
          item.activeFlag = true
        }
      })
      dialogInfo.value.problemDesc = reson.length >= 2 ? reson[1] : ''
    }
    dialogInfo.value.visible = true
  } else {
    changeChartStatus(obj).then(res => {
      if(res.header.code === -1){
        $app.$message.warning(res.header.message)
      } else {
        emit("changeZanOrCai", val)
      }
    })
  }
  
}
onMounted(() => {
  realText.value = replaceText(props.machineText)
  moduleInstance.value = new Experience({
    engineType: "intp65",
    tte: "UTF8",
    speed: 50,
    voice: 5,
    pitch: 50,
    text: realText.value,
    close: () => {
      emit("changePalyStatus", true)
    },
  })
})

onBeforeUnmount(() => {
  stop()
  moduleInstance.value?.audioPause()
})
</script>

<style lang="scss" scoped>
.tts-module {
  .el-icon {
    font-size: 22px;
    cursor: pointer;
    color: #878787;
    margin-left: 16px;

    &:hover {
      color: var(--el-color-primary);
    }
  }

  .line {
    width: 2px;
    height: 16px;
    background-color: #e2e2e2;
    margin-left: 16px;
    margin-right: 4px;
  }

  .desktop-svg-icon {
    cursor: pointer;
    margin-left: 16px;
  }
  
}
.top-content{
  position: relative;
  background: linear-gradient(180deg,rgba(56,112,255,0.09), rgba(255,255,255,0.00) 100%);
}
.active-card-bg{
  position: absolute;
  top: 0;
  right: 2px;
  z-index: -1;
  opacity: 0.49;
}
.dialog-name{
    padding: 20px;
    font-size: 18px;
    font-family: PingFang SC;
    font-weight: 500;
    color: #000000;
    line-height: 26px;
    display: flex;
    justify-content: space-between;
    background: linear-gradient(180deg,rgba(56,112,255,0.09), rgba(255,255,255,0.00) 100%);
  }
  .dialog-content{
    padding: 16px 20px 0 20px;
    display: flex;
    flex-wrap: wrap;
    .item-desc{
      margin-bottom: 16px;
      margin-right: 16px;
      padding: 7px 16px;
      height: 32px;
      background: rgba(217,217,217,0.20);
      border-radius: 33px;
      font-size: 14px;
      color: #30405d;
      cursor: pointer;
    }
    .item-active{
      color: #4B72EF;
      background: rgba(75,114,239,0.10);
    }
    
    
  }
  .dialog-form{
    padding: 20px;
    padding-top: 8px;
      width: 100%;
      p{
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 400;
        text-align: LEFT;
        color: #30405d;
        line-height: 22px
      }
    }
  .dialog-footer{
    height: 64px;
    padding: 16px 24px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    border-top: 1px solid #e2e7ee;
  }
</style>
<style lang="scss">
.el-popover.custom-zancai-popover {
  padding: 2px !important;
}
</style>
