<template>
  <div>
    <div v-loading="loading" style="cursor: pointer;" @click.stop="markScoreDigBtn">
      <div class="scoreTit">
        <div>任务得分</div>
        <div>{{ totalScore ? totalScore : 0 }}分</div>
      </div>
      <div class="allD">
        <div class="scoreStarBack2">
          <div
            v-for="(e, index) in scoTitList"
            :key="index"
            style="height: 30px;"
          >
            <img
              class="rootImg"
              v-if="e.isai == 1 || !e.isai"
              src="../../../assets/icon/newIcons/blueRoot.png"
              alt=""
            />
          </div>
        </div>
        <div class="scoreStar">
          <div v-for="(e, index) in scoTitList" :key="index">
            <div class="scoreStarBack">
              <el-tooltip
                class="item"
                effect="dark"
                :content="e.detail"
                placement="top"
              >
                <div class="briefTit">
                  {{ e.detail }}
                </div>
              </el-tooltip>
              <el-rate
                disabled
                disabled-void-color="#ccc"
                v-model="e.cog"
              ></el-rate>
            </div>
          </div>
        </div>
      </div>
      <div class="AreaCss">
        {{ textarea }}
        <!-- <el-input
          type="textarea"
          disabled
          placeholder="您可在此输入评语"
          v-model="textarea"
          style="padding-bottom: 10px;"
        >
        </el-input> -->
      </div>
      <!-- <div style="width:100%;display:flex;justify-content: flex-end;">
        <el-button size="mini" @click="reset">重置</el-button>
        <el-button type="primary" size="mini" @click="submit">确认</el-button>
        <el-button type="primary" size="mini" @click="AIsubmit"
          >AI评分</el-button
        >
      </div> -->
    </div>
  </div>
</template>

<script>
import { v4 as uuidv4 } from "uuid";

export default {
  name: "PblStudentTableMarkScore",
  props: [
    "scoTit",
    "scoCon",
    "task",
    "stage",
    "loading",
    "wIndex",
    "toolIndex",
    "tool",
    "markScoreVisible"
  ],

  data() {
    return {
      homeworkVal: [],
      scoTitList: [],
      markScoPopover: false,
      id: this.$route.query.courseId,
      stUid: this.scoCon.userid,
      userid: this.$route.query.userid,
      total: 0,
      textarea:''
    };
  },

  computed: {
    totalScore() {
      let a = 0;
      let isPing = 0;
      
      this.scoTitList.forEach(e => {
        if (e.cog || e.cog == "0") {
          a += e.cog * 1;
        } else {
          isPing += 1;
        }
      });
      

      let data = 0;
      if (isPing == this.scoTitList.length) {
        this.$emit("updateDocSco", {
          val: this.toolIndex,
          val2: this.wIndex,
          val3: null
        });
      } else {
        data = (a / this.scoTitList.length).toFixed(1);
        this.$emit("updateDocSco", {
          val: this.toolIndex,
          val2: this.wIndex,
          val3: data
        });
      }

      return data;
    }
  },

  mounted() {
    
    if (this.tool.eList && this.tool.eList.length) {
      this.scoTitList = JSON.parse(JSON.stringify(this.tool.eList));
    }else{
      this.scoTitList = JSON.parse(JSON.stringify(this.scoTit));
    }
    this.getData();
  },

  methods: {
   
    // // 获取文档id
    createFileid(url) {
      let _this = this;
      return new Promise((resolve, reject) => {
        try {
          _this.ajax
            .put("https://gpt4.cocorobo.cn/upload_file_knowledge", {
              url: url
            })
            .then(res => {
              let _data = res.data.FunctionResponse;
              if (_data.result && _data.result.id) {
                resolve(_data.result.id);
              } else {
                resolve(1);
              }
            })
            .catch(function(error) {
              resolve(1);
            });
        } catch (e) {
          resolve(1);
        }
      });
    },

    // 获取单个数据
    getData() {

      let params = {
        uid: this.scoCon.userid,
        cid: this.id,
        s:this.stage,
        t:this.task,
        tool:this.toolIndex ? this.toolIndex :''
      };
      this.ajax
        .get(this.$store.state.api + "selectWorksEvaScoreTwo", params)
        .then(res => {
          // console.log("res", res.data);

          if (res.data[0].length > 0) {
            
            var data2 = [];
            res.data[0].forEach((val, index) => {
              if (val.task == this.task) {
                data2 = res.data[0][index];
                this.homeworkVal = res.data[0][index];
              }
            });
            
            if (data2.length == 0) {
              if (this.tool.eList && this.tool.eList.length) {
                this.scoTitList = JSON.parse(JSON.stringify(this.tool.eList));
              }else{
                this.scoTitList = JSON.parse(JSON.stringify(this.scoTit));
              }
            } else {
              let data = JSON.parse(data2.rate);
              this.scoTitList.forEach((e, index) => {
                e.cog = null;
                for (const key in data) {

                  if (isNaN(parseFloat(e.detail)) && e.detail) {
                    var result = e.detail.match(/[\u4e00-\u9fa5a-zA-Z]+/g).join("");
                  }else{
                    var result = e.detail
                  }

                  if (isNaN(parseFloat(key)) && key) {
                    var key2 = key.match(/[\u4e00-\u9fa5a-zA-Z]+/g).join("");
                  }else{
                    var key2 = key
                  }

                  // let result = e.detail.match(/[\u4e00-\u9fa5a-zA-Z]+/g).join("");
                  // let key2 = key.match(/[\u4e00-\u9fa5a-zA-Z]+/g).join("");

                  if (result.indexOf(key2) != -1) {
                    e.cog = data[key];
                  }
                  if ("content" == key) {
                    this.textarea = data[key];
                  }
                }
              });
              this.scoTitList = JSON.parse(JSON.stringify(this.scoTitList));

              // console.log(this.scoTitList);
            }
          } else {
            this.scoTitList.forEach((e, index) => {
              e.cog = null;
            }) 
            this.scoTitList = JSON.parse(JSON.stringify(this.scoTitList));

          }
        })
        .catch(err => {
          console.error(err);
        });
    },
    markScoreDigBtn() {
      if (this.tool.eList && this.tool.eList.length) {
        this.$emit("markScoreDig", {
          val: this.stUid,
          val2: this.toolIndex,
          tit: this.tool.eList,
          uname:this.scoCon.sName
        });
      }else{
        this.$emit("markScoreDig", {
          val: this.stUid,
          val2: this.toolIndex,
          tit: this.scoTit,
          uname:this.scoCon.sName
        });
      }
    },
    // 重置
    reset() {
      this.scoTitList.forEach(e => {
        e.cog = 0;
        // console.log(e.cog);
      });
    },



    // ai循环评分
    async aiupdetaSco(messages, uid, stage, task,_fileid,work) {
      
      let _this = this;
      let params = {
        assistant_id: "6063369f-289a-11ef-8bf4-12e77c4cb76b",
        message: [
          {
            type: "text",
            text: messages.replaceAll("\n", " ").replaceAll("*", "")
          }
        ],
        session_name: uuidv4(),
        userId: this.userid,
        file_ids: _fileid ? [_fileid] : [],
        isImage: work == 0 ? true : '',
        model:  _fileid ? "gpt-4o-2024-11-20"  : "gpt-4o-2024-11-20"
      };
      return new Promise((resolve,reject) => {
        this.ajax
          .post("https://gpt4.cocorobo.cn/ai_agent_park_chat", params)
          .then( response => {
            let data = response.data.FunctionResponse;
            console.log(data);

            if (data.message) {
              let dArray = {};
              try {
                dArray = JSON.parse(
                  data.message.replaceAll("```json", "").replaceAll("```", "")
                );
              } catch (error) {
                console.log("error_________________" + error);
                try {
                  let regex = new RegExp("(?<=```json)([\\s\\S]*?)(?=```)");

                  let match = data.message.match(regex);
                  // console.log("dArray2", match);
                  dArray = JSON.parse(
                    match[0]
                      .replace(/\n/g, "")
                      .replace(/\s{2,}/g, "")
                      .replace(/\'/g, '"')
                  );
                  // dArray = data.choices[0].message.content
                } catch (error) {
                  try {
                    dArray = JSON.parse(
                      data.message
                        .replaceAll("```json", "")
                        .replaceAll("```javascript", "")
                        .replaceAll("# Solution", "")
                        .replaceAll("```", "")
                        .replace(/\n/g, "")
                        .replace(/\s{2,}/g, "")
                        .replace(/\'/g, '"')
                    );
                  } catch (error) {
                    console.log("error_________________" + error);
                  }
                  console.log("error_________________" + error);
                }
              }
              let processedData = {};

              dArray.forEach(function(item) {
                let key = Object.keys(item)[0];
                let value = item[key];
                processedData[key] = value;
              });

              let IsAIsuccess = 0

              for (let tKey in this.scoTitList) {
                for (let key in processedData) {


                  if (isNaN(parseFloat(this.scoTitList[tKey].detail)) && this.scoTitList[tKey].detail) {
                    var result = this.scoTitList[tKey].detail.match(/[\u4e00-\u9fa5a-zA-Z]+/g).join("");
                  }else{
                    var result = this.scoTitList[tKey].detail
                  }

                  if (isNaN(parseFloat(key)) && key) {
                    var key2 = key.match(/[\u4e00-\u9fa5a-zA-Z]+/g).join("");
                  }else{
                    var key2 = key
                  }

                  // let result = this.scoTitList[tKey].detail.match(/[\u4e00-\u9fa5a-zA-Z]+/g).join("");
                  // let key2 = key.match(/[\u4e00-\u9fa5a-zA-Z]+/g).join("");


                  if (key != "comment") {
                  let isNumK = /^\d+(\.\d+)?$/.test(processedData[key]);

                    if (result.indexOf(key2) != -1 && isNumK) {
                      key = this.scoTitList[tKey].detail
                      IsAIsuccess++
                    }
                    continue;
                  }
                }
                continue;
              }
              let scotNum = 0
              this.scoTitList.forEach(e=>{
                if (e.isai == 1 || !e.isai) {
                  scotNum++
                }
              })
              if (IsAIsuccess != scotNum) {
                console.log("评价失败");
                _this.ScLoading = false;
               return  _this.aiupdetaSco(messages, uid, stage, task,_fileid).then(_=>{
                  resolve();
                })
              }
              let processedDataCopy = {}
              for (const tKey in _this.scoTitList) {
                for (const key in processedData) {

                  if (isNaN(parseFloat(_this.scoTitList[tKey].detail)) && _this.scoTitList[tKey].detail) {
                    var result = _this.scoTitList[tKey].detail.match(/[\u4e00-\u9fa5a-zA-Z]+/g).join("");
                  }else{
                    var result = _this.scoTitList[tKey].detail
                  }

                  if (isNaN(parseFloat(key)) && key) {
                    var key2 = key.match(/[\u4e00-\u9fa5a-zA-Z]+/g).join("");
                  }else{
                    var key2 = key
                  }


                  // let result = _this.scoTitList[tKey].detail.match(/[\u4e00-\u9fa5a-zA-Z]+/g).join("");
                  // let key2 = key.match(/[\u4e00-\u9fa5a-zA-Z]+/g).join("");
                  if (result.indexOf(key2) != -1) {
                    let aaa = _this.scoTitList[tKey].detail
                    processedDataCopy[aaa] = processedData[key]
                  }
                }
              }
              for (const key in processedData) {
                if (key == "comment") {
                  processedDataCopy.content = processedData[key];
                }
              }
              let params = {
                cid: _this.id,
                s: stage,
                t: task,
                tool: this.toolIndex ? this.toolIndex : '',
                rate: JSON.stringify(processedDataCopy),
                uid: uid
              };
              // console.log("params", params);
              _this.ajax
                .get(_this.$store.state.api + "updateWorksEvaTwo", params)
                .then(res => {
                  console.log('999999999999999999999999999999999999999999999999999');
                  this.getData()
                  this.$emit('refreshOther',{tid:this.toolIndex,wid:this.wIndex})
                  
                  return resolve(1);
                  
                })
                .catch(err => {
                  console.error(err);
                  return _this.aiupdetaSco(messages, uid, stage, task,_fileid).then(_=>{
                  resolve();
                })

                });
                
            }
          })
          .catch(error => {
            console.log(error);
            
            return _this.aiupdetaSco(messages, uid, stage, task,_fileid).then(_=>{
                  resolve();
                })
          });
      });
    },
    
  }
};
</script>
<style scoped>
.scoreTit {
  font-size: 16px;
  font-weight: 600;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
}
.allD {
  margin: 5px 0;
  display: flex;
  width: 100%;
  overflow: auto;
  max-height: 100px;
  min-height: 60px;
}
.scoreStar {
  background-color: #f3f7fd;
  padding: 10px;
  height: 100%;
  flex: 1;
}
.scoreStar > div:last-child > .scoreStarBack {
  margin-bottom: 0;
}
.scoreStarBack {
  flex: 1;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.rootImg {
  padding-top: 1px;
  box-sizing: border-box;
  display: block;
}

.scoreStarBack2 {
  padding: 10px 0;
  margin-right: 2px;
}

.AreaCss {
  margin-bottom: 5px;
  -webkit-line-clamp: 2;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  /* margin-left: 20px; */
}
.AreaCss >>> .el-textarea__inner {
  min-height: 60px;
  max-height: 150px;
  padding-bottom: 20px;
}

.briefTit {
  width: 150px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
</style>
