<template>
  <div class="batchCreationClassDialog">
    <el-dialog
      :visible.sync="show"
      width="100%"
      height="100%"
      fullscreen
      :modal="false"
      :close-on-click-modal="true"
      :show-close="false"
    >
      <div class="box">
        <div class="b_back">
          <div class="b_b_left" @click="close()">
            <img src="../../../../assets/icon/classroomObservation/right.svg" />
            <span>返回</span>
          </div>
          <div class="b_b_right">
            <el-button type="primary" size="small" @click="uploadFile"
              >上传文件</el-button
            >
          </div>
        </div>
        <div class="b_head">
          <span>已上传的课堂实录</span>
        </div>
        <div class="b_nav">
          <div class="b_n_left">
            <span
              :class="{ b_n_l_active: selectStatus == item.value }"
              v-for="item in statusList"
              :key="item.value"
              @click="changeStatus(item.value)"
              >{{ item.label }}</span
            >
          </div>
          <div class="b_n_right">
            <span @click="test">总计{{ dataList.length }}个</span>
          </div>
        </div>
        <div class="b_bottom">
          <div class="b_b_operation">
            <div class="b_b_o_left">
              <span
                >当前进度 {{ progress }}/{{
                  dataList.filter(
                    i =>
                      selectStatus == "99" ||
                      statusList
                        .find(i => i.value == selectStatus)
                        .allow.includes(i.status)
                  ).length
                }}</span
              >
            </div>
            <div class="b_b_o_right">
              <div>
                <el-checkbox v-model="selectAll" :indeterminate="indeterminate"
                  >全选</el-checkbox
                >
              </div>
              <span>
                <img
                  @click="delSelectBtn"
                  src="../../../../assets/icon/classroomObservation/del2.svg"
                />
              </span>
            </div>
          </div>
          <div class="b_b_list">
            <batchClassCard
              v-for="item in dataList"
              :data="item"
              :isSelect="selectList.includes(item.id)"
              :key="item.id"
              v-show="
                selectStatus === '99' ||
                  statusList
                    .find(i => i.value === selectStatus)
                    .allow.includes(item.status)
              "
              @changeChecked="changeCardChecked"
              @editBaseMessage="editBaseMessage"
              @changeData="changeData"
              @taskBtn="taskBtn"
              @goToEdit="goToEdit"
            />
          </div>
        </div>
      </div>
      <uploadFileToCreateClassDialog
        ref="uploadFileToCreateClassDialogRef"
        @success="uploadFileSuccess"
      />
      <editBaseMessageDialog
        ref="editBaseMessageDialogRef"
        @success="editBaseMessageSuccess"
      />
    </el-dialog>
    <!-- 录音转文字 -->
    <iframe
      allow="camera *; microphone *;display-capture;midi;encrypted-media;"
      src="https://beta.cloud.cocorobo.cn/browser/public/index.html"
      ref="iframeRef"
      v-show="false"
    ></iframe>
  </div>
</template>

<script>
import batchClassCard from "../newComponents/batchClassCard.vue";
import uploadFileToCreateClassDialog from "./uploadFileToCreateClassDialog.vue";
import editBaseMessageDialog from "./editBaseMessageDialog.vue";
import { v4 as uuidv4 } from "uuid";
import { toolMixin } from "../tools/mixin";
export default {
  mixins: [toolMixin],
  components: {
    batchClassCard,
    uploadFileToCreateClassDialog,
    editBaseMessageDialog
  },
  data() {
    return {
      statusList: [
        { label: "全部", value: "99", allow: [] },
        { label: "已完成", value: "2", allow: ["2"] },
        { label: "处理中", value: "1", allow: ["1"] },
        { label: "等待处理", value: "0", allow: ["0"] },
        { label: "待开始", value: "3", allow: ["3"] }
      ],
      userId: this.$route.query["userid"],
      selectStatus: "99",
      show: false,
      selectList: [],
      dataList: [],
      nowDoTaskId: [],
      dialogTagDataList: []
    };
  },
  computed: {
    selectAll: {
      get() {
        let _result = false;

        let _data = this.dataList.filter(
          i =>
            this.selectStatus === "99" ||
            this.statusList
              .find(i2 => i2.value === this.selectStatus)
              .allow.includes(i.status)
        );

        if (_data.length > 0 && _data.length === this.selectList.length) {
          _result = true;
        }
        return _result;
      },
      set(value) {
        if (value) {
          this.selectList = this.dataList
            .filter(
              i =>
                this.selectStatus === "99" ||
                this.statusList
                  .find(i2 => i2.value === this.selectStatus)
                  .allow.includes(i.status)
            )
            .map(i => i.id);
          this.$forceUpdate();
        } else {
          this.selectList = [];
        }
      }
    },
    indeterminate() {
      let _result = false;

      let _data = this.dataList.filter(
        i =>
          this.selectStatus === "99" ||
          this.statusList
            .find(i2 => i2.value === this.selectStatus)
            .allow.includes(i.status)
      );

      if (_data.length > this.selectList.length && this.selectList.length > 0) {
        _result = true;
      }

      return _result;
    },
    progress() {
      return this.dataList.filter(
        i =>
          i.status == "2" &&
          (this.selectStatus == "99" ||
            this.statusList
              .find(i2 => i2.value == this.selectStatus)
              .allow.includes(i.status))
      ).length;
    }
  },
  methods: {
    open() {
      this.show = true;
    },
    close() {
      this.show = false;
    },
    init() {},
    changeStatus(newValue) {
      this.selectStatus = newValue;
      this.selectList = [];
    },
    uploadFile() {
      this.$refs.uploadFileToCreateClassDialogRef.open();
    },
    //批量上传文件成功
    async uploadFileSuccess(data) {
      this.$refs.uploadFileToCreateClassDialogRef.close();
      let { fileList, automaticCoding, analysisTemplate } = data;
      this.loading = true;

      let fileDataList = fileList.map(i => i.successData);

      let _tempData = await this.getTemplateData(analysisTemplate[1]);

      let _analysisList = JSON.parse(_tempData.tips);
      let tagList = _analysisList.find(i => i.isOtherData);

      if (!tagList) {
        tagList = [
          { value: 0, name: "通用课堂分析", loading: false },
          { value: 1, name: "学科课堂分析", loading: false },
          { value: 2, name: "扩展分析", loading: false }
        ];
      } else {
        tagList = tagList.dialogTagList;
      }

      let batch = uuidv4();

      _analysisList = _analysisList.filter(
        i => !i.isOtherData && i.jsonData.name != "词频词汇分析"
      );

      let promiseList = [];

      fileDataList.forEach(i => {
        let data = {
          id: uuidv4(),
          create_at: "2025-05-07 16.05.03",
          remarks: "备注",
          batch: batch,
          status: "3",
          createId: "",
          jsonData: {
            file_ids: "",
            baseMessage: {
              courseName: i.name,
              teacherName: "",
              time: "",
              grade: "",
              subject: "",
              textbook: "",
              studentNum: 0,
              imageList: {
                fileList: [],
                fileList1: [],
                fileList2: [],
                fileList3: [],
                name: "课堂记录",
                NephogramList: [],
                videoList: []
              }
            },
            tagList: tagList,
            steps: [],
            analysisList: _analysisList,
            fileData: i,
            automaticCoding: automaticCoding
          }
        };

        if (i.type == "text/plain") {
          data.jsonData.steps = [
            {
              type: "uploadFile",
              text: "上传文件",
              status: "1"
            },
            {
              type: "transcription",
              text: "文本转录",
              status: "0",
              progress: "0"
            },
            {
              type: "getFileIds",
              text: "获取文件fileid",
              status: "0"
            },
            {
              type: "generateReport",
              text: "生成报告",
              status: "0",
              progress: "0"
            },
            {
              type: "createClass",
              text: "创建课堂",
              status: "0",
              progress: "0"
            }
          ];
        } else if (["audio/wav",'audio/x-m4a','audio/mpeg'].includes(i.type) ) {
          data.jsonData.baseMessage.imageList.fileList = [
            {
              name: i.name,
              status: "success",
              url: i.url,
              uid: "1"
            }
          ];
          data.jsonData.steps = [
            {
              type: "uploadFile",
              text: "上传文件",
              status: "1"
            },
            {
              type: "transcription",
              text: "文本转录",
              status: "0",
              progress: "0"
            }
          ];

          if (data.jsonData.automaticCoding) {
            data.jsonData.steps.push({
              type: "automaticCoding",
              text: "自动编码",
              status: "0",
              progress: "0"
            });
          }

          data.jsonData.steps.push(
            ...[
              {
                type: "getFileIds",
                text: "获取文件fileid",
                status: "0"
              },
              {
                type: "generateReport",
                text: "生成报告",
                status: "0",
                progress: "0"
              },
              {
                type: "createClass",
                text: "创建课堂",
                status: "0",
                progress: "0"
              }
            ]
          );
        } else if (i.type == "video/mp4") {
          data.jsonData.baseMessage.imageList.videoList = [
            {
              name: i.name,
              status: "success",
              url: i.url,
              uid: "1"
            }
          ];
          data.jsonData.steps = [
            {
              type: "uploadFile",
              text: "上传文件",
              status: "1"
            },
            {
              type: "getVideoVoice",
              text: "视频提取音频",
              status: "0",
              progress: "0"
            },
            {
              type: "transcription",
              text: "文本转录",
              status: "0",
              progress: "0"
            }
          ];
          if (data.jsonData.automaticCoding) {
            data.jsonData.steps.push({
              type: "automaticCoding",
              text: "自动编码",
              status: "0",
              progress: "0"
            });
          }
          data.jsonData.steps.push(
            ...[
              {
                type: "getFileIds",
                text: "获取文件fileid",
                status: "0"
              },
              {
                type: "generateReport",
                text: "生成报告",
                status: "0",
                progress: "0"
              },
              {
                type: "createClass",
                text: "创建课堂",
                status: "0",
                progress: "0"
              }
            ]
          );
        }

        promiseList.push(
          new Promise((resolve, reject) => {
            // 本地保存fileObj
            const fileObj = data.jsonData.fileData.fileObj;
            delete data.jsonData.fileData.fileObj;
            const params = [
              {
                remarks: data.remarks,
                status: data.status,
                json: JSON.stringify(data.jsonData),
                batch: data.batch,
                createId: data.createId,
                userId: this.userId
              }
            ];
            console.log(params);
            this.ajax
              .post(this.$store.state.api + "insert_classroomTask", params)
              .then(res => {
                const _data = res.data[0][0];
                if (_data.id) {
                  data.jsonData.fileData.fileObj = fileObj;
                  data.id = _data.id;
                  this.dataList.push(data);
                }
                resolve();
              })
              .catch(err => {
                console.error(err);
                reject(err);
              });
          })
        );
      });
      console.log(promiseList);
      Promise.all(promiseList)
        .then(res => {
          this.$message.success("创建成功");
        })
        .catch(err => {
          console.log("创建出错", err);
        });
    },
    //获取模板的数据
    getTemplateData(tid) {
      return new Promise(resolve => {
        let params = {
          uid: this.userId,
          cid: tid,
          st: 0
        };
        this.ajax
          .get(this.$store.state.api + "selectClassroomTemplateDetail", params)
          .then(res => {
            let _data = res.data[0][0];
            resolve(_data);
          });
      });
    },
    changeCardChecked({ type = 0, id }) {
      if (type === 0 && !this.selectList.includes(id)) {
        this.selectList.push(id);
      } else if (type === 1 && this.selectList.push(id)) {
        this.selectList = this.selectList.filter(i => i != id);
      }
    },
    //修改课堂的baseMessage按钮
    editBaseMessage(id) {
      let _data = this.dataList.find(i => i.id === id);
      if (_data) {
        this.$refs.editBaseMessageDialogRef.open({
          editId: _data.id,
          message: _data.jsonData.baseMessage
        });
      } else {
        this.$message.error("未查询到该数据");
      }
    },
    //修改课堂的baseMessage
    editBaseMessageSuccess({ editId, message }) {
      if (editId) {
        let _editorBarData = null
        let _transcriptionData = null;
        if(this.dataList.find(i=>i.id===editId).jsonData.baseMessage.editorBarData){
          _editorBarData = this.dataList.find(i=>i.id===editId).jsonData.baseMessage.editorBarData;
        }

        if(this.dataList.find(i=>i.id===editId).jsonData.baseMessage.transcriptionData){
          _transcriptionData = this.dataList.find(i=>i.id===editId).jsonData.baseMessage.transcriptionData;
        }
        this.dataList.find(i => i.id === editId).jsonData.baseMessage = message;
        if(_editorBarData){
          this.dataList.find(i=>i.id===editId).jsonData.baseMessage.editorBarData = _editorBarData;
        }
        if(_transcriptionData){
          this.dataList.find(i=>i.id===editId).jsonData.baseMessage.transcriptionData = _transcriptionData;
        }
        this.$forceUpdate();
        this.$refs.editBaseMessageDialogRef.close();
        this.updateTask(editId);
      }
    },
    // 删除选择的数据
    delSelectBtn() {
      let _delList = this.dataList.filter(
        i =>
          this.selectList.includes(i.id) &&
          (this.selectStatus === "99" ||
            this.statusList
              .find(i2 => i2.value === this.selectStatus)
              .allow.includes(i.status))
      );

      if (_delList.length <= 0) return this.$message.info("请先选择列表");
      this.$confirm("您确定要删除选中的数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 确定删除
          let params = [
            {
              idList: _delList.map(i => i.id).join(","),
              userId: this.userId
            }
          ];

          this.ajax
            .post(this.$store.state.api + "delete_classroomTask", params)
            .then(res => {
              if (res.data > 0) {
                this.$message.success("删除成功");
                this.dataList = this.dataList.filter(
                  i => !_delList.find(del => del.id === i.id)
                );
                this.selectList = [];
              }
            })
            .catch(err => {
              console.log(err);
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          // 取消删除
        });
    },
    //获取任务列表
    getTaskList() {
      let params = {
        userId: this.userId
      };
      this.ajax
        .get(this.$store.state.api + "select_classroomTask", params)
        .then(res => {
          let _data = res.data[0];
          if (_data.length > 0) {
            _data.forEach(i => (i.jsonData = JSON.parse(i.jsonData)));
            this.dataList = _data;
          }
        });
    },
    //获取所有的模块分析
    getDialogTagDataList() {
      let params = {
        uid: this.userId
      };
      this.ajax
        .get(this.$store.state.api + "select_smodel", params)
        .then(res => {
          let _result = res.data[0];
          this.dialogTagDataList = _result;
        })
        .catch(e => {
          console.log(e);
          this.$message.error("获取模块分析列表失败");
        });
    },
    updateTask(id) {
      return new Promise((resolve, reject) => {
        let _data = this.dataList.find(i => i.id === id);
        if (_data) {
          const dataCopy = JSON.parse(JSON.stringify(_data));
          if (dataCopy.jsonData.fileData.fileObj) {
            delete dataCopy.jsonData.fileData.fileObj;
          }
          if (
            dataCopy.jsonData.baseMessage.editorBarData &&
            dataCopy.jsonData.baseMessage.editorBarData.content
          ) {
            delete dataCopy.jsonData.baseMessage.editorBarData.content;
          }
          if (
            dataCopy.jsonData.baseMessage.editorBarData &&
            dataCopy.jsonData.baseMessage.editorBarData.tableList
          ) {
            delete dataCopy.jsonData.baseMessage.editorBarData.tableList;
          }

          console.log("dataCopy", dataCopy);
          let params = [
            {
              id: dataCopy.id,
              userId: this.userId,
              remarks: dataCopy.remarks,
              status: ["0", "1"].includes(dataCopy.status)
                ? "3"
                : dataCopy.status,
              json: JSON.stringify(dataCopy.jsonData),
              createId: dataCopy.createId,
              batch: dataCopy.batch
            }
          ];

          this.ajax
            .post(this.$store.state.api + "update_classroomTask", params)
            .then(res => {
              if (res.data == 1) {
                console.log("修改任务成功");
                resolve();
              } else {
                reject();
                this.$message.error("修改任务失败");
              }
            })
            .catch(err => {
              console.log(err);
              this.$message.error("修改任务失败");
              reject();
            });
        }
      });
    },
    changeData({ field, data }) {
      let _index = this.dataList.findIndex(i => i.id === data.id);
      if (_index != -1) {
        if (this.dataList[_index][field] != data[field]) {
          this.dataList[_index][field] = data[field];
          this.updateTask(this.dataList[_index].id);
        }
      }
    },
    taskBtn(obj) {
      let { type, id } = obj;
      if (type === "startTask" && id) {
        // this.startTask(id);
        if (
          this.dataList.some(i => i.status === "1") &&
          this.dataList.find(i => i.id === id).status === "0"
        ) {
          this.$confirm(
            "您确定要开始该任务嘛？其他已开始的任务会暂停。",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
          )
            .then(() => {
              this.startTask(id);
            })
            .catch(() => {
              console.log("不暂停");
            });
        } else {
          this.startTask(id);
        }
      } else if (type === "stopTask" && id) {
        this.$confirm("您确定要停止该任务吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.stopTask(id);
          })
          .catch(() => {
            console.log("不暂停");
          });
      } else if (type === "pauseTask" && id) {
        this.$confirm("您确定要暂停该任务吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.pauseTask(id);
          })
          .catch(() => {
            console.log("不暂停");
          });
      }
    },
    async startTask(id) {
      let _isStartTaskIndex = this.dataList.findIndex(i => i.status === "1");
      let _needStartTaskIndex = this.dataList.findIndex(i => i.id === id);
      if (_isStartTaskIndex === -1) {
        //没有任务在进行，直接开始处理
        this.dataList[_needStartTaskIndex].status = "1"; //处理中
      } else if (
        this.dataList[_needStartTaskIndex].status === "3" &&
        _isStartTaskIndex !== -1
      ) {
        //有任务在进行，且这个任务是从待开始状态到开始状态，等待处理
        this.dataList[_needStartTaskIndex].status = "0";
      } else if (
        _isStartTaskIndex !== -1 &&
        this.dataList[_needStartTaskIndex].status === "0"
      ) {
        //有任务在进行，且这个任务是从等待状态到开始状态，停止现任务，开始新任务
        this.nowDoTaskId = this.nowDoTaskId.filter(
          i => i !== this.dataList[_isStartTaskIndex].id
        );
        this.dataList[_isStartTaskIndex].status = "0"; //
        this.dataList[_needStartTaskIndex].status = "1"; //处理中
      }

      if (
        !this.nowDoTaskId.includes(this.dataList.find(i => i.status === "1").id)
      ) {
        let _startData = JSON.parse(
          JSON.stringify(this.dataList.find(i => i.status === "1"))
        );

        if (
          this.dataList.find(i => i.id === _startData.id).jsonData.fileData
            .fileObj
        ) {
          _startData.jsonData.fileData.fileObj = this.dataList.find(
            i => i.id === _startData.id
          ).jsonData.fileData.fileObj;
        }
        this.nowDoTaskId.push(_startData.id);
        let _stepList = _startData.jsonData.steps;
        for (let i = 0; i < _stepList.length; i++) {
          //按顺序处理任务
          let _step = _stepList[i];
          console.log(_step);
          if(!this.nowDoTaskId.includes(_startData.id))break;
          if (_step.status === "1") continue;
          if (_step.type === "uploadFile") continue;
          if (_step.type === "getVideoVoice") {
            //视频提取音频
            _stepList[i].status = "2";
            this.dataList.find(
              i => i.id === _startData.id
            ).jsonData.steps = _stepList;
            let _fileData = _startData.jsonData.fileData;
            let audioFile = await this.getVideoToVoiceAndUploadMixin(_fileData);
            if(!this.nowDoTaskId.includes(_startData.id))break;
            _startData.jsonData.fileData.videoUrl = _fileData.url;
            _startData.jsonData.fileData.fileObj = audioFile.fileObj;
            _startData.jsonData.fileData.url = audioFile.audioUrl.Location;
            _startData.jsonData.baseMessage.imageList.fileList = [
              {
                name: _fileData.name,
                status: "success",
                url: audioFile.Location,
                uid: "1"
              }
            ];
            _stepList[i].status = "1";
            this.dataList.find(i => i.id === _startData.id).jsonData =
              _startData.jsonData;
            this.updateTask(_startData.id);
            _startData.jsonData = JSON.parse(
              JSON.stringify(
                this.dataList.find(i => i.id === _startData.id).jsonData
              )
            );
            _startData.jsonData.fileData.fileObj = audioFile.fileObj;//防止文件因为json失效
            console.log("data👉",JSON.parse(JSON.stringify(_startData)))
            console.log(`${_startData.id}:已完成视频转音频`);
          } else if (_step.type === "transcription") {
            //文本转录
            const fileData = _startData.jsonData.fileData;
            if (fileData.type === "text/plain") {
              //txt文件
              _stepList[i].status = "2";
              this.dataList.find(
                i => i.id === _startData.id
              ).jsonData.steps = _stepList;
              let { editorBarData } = await this.getTextContentMixin(fileData);
              if(!this.nowDoTaskId.includes(_startData.id))break;
              this.dataList.find(
                i => i.id === _startData.id
              ).jsonData.baseMessage.editorBarData = editorBarData;
              _stepList[i].status = "1";
              this.dataList.find(
                i => i.id === _startData.id
              ).jsonData.steps = _stepList;
              this.updateTask(_startData.id);
              _startData.jsonData = JSON.parse(
                JSON.stringify(
                  this.dataList.find(i => i.id === _startData.id).jsonData
                )
              );
              console.log(`${_startData.id}:已获取转录文稿(txt)`);
              console.log("data👉",JSON.parse(JSON.stringify(_startData)))
            } else if (
              ['video/mp4','audio/wav','audio/x-m4a','audio/mpeg'].includes(fileData.type)
            ) {
              //mp4与wav文件
              _stepList[i].status = "2";
              this.dataList.find(
                i => i.id === _startData.id
              ).jsonData.steps = _stepList;

              let _file = _startData.jsonData.fileData.fileObj;
              if(!_file && JSON.stringify(_file)!="{}"){
                let fileBody = await this.getFileBody(_startData.jsonData.fileData.url);
                let _type = _startData.jsonData.fileData.type.split('/')[1];
                if(_type=='x-m4a'){
                  _type="m4a"
                }else if(_type=="mpeg"){
                  _type = "mp3"
                }
                _file = new File([fileBody.data], `audio.${_type}`, { type: _startData.jsonData.fileData.type });
              }

              if (["audio/x-m4a","audio/mpeg"].includes(_file.type)) {
                let _data = await this.audioToWavMixin(_file);
                if(_data!==1){
                  _file = _data.data;
                }else{
                  console.log("报错👉",_data)
                }
              }
              console.log("转录文件",_file)

              let {
                transcriptionContent,
                editorBarData
              } = await this.wavAudioToTextAndObjMixin(_file);

              this.dataList.find(
                i => i.id === _startData.id
              ).jsonData.baseMessage.transcriptionData = transcriptionContent;
              this.dataList.find(
                i => i.id === _startData.id
              ).jsonData.baseMessage.editorBarData = editorBarData;

              _stepList[i].status = "1";
              this.dataList.find(
                i => i.id === _startData.id
              ).jsonData.steps = _stepList;
              this.updateTask(_startData.id);
              _startData.jsonData = JSON.parse(
                JSON.stringify(
                  this.dataList.find(i => i.id === _startData.id).jsonData
                )
              );
              console.log(`${_startData.id}:已获取转录文稿(mp4/wav)`);
            }
          } else if (_step.type === "automaticCoding") {
            if (_startData.jsonData.automaticCoding) {
              _stepList[i].status = "2";
              this.dataList.find(
                i => i.id === _startData.id
              ).jsonData.steps = _stepList;
              //选择了字段编码
              let _content =
                _startData.jsonData.baseMessage.editorBarData.content;
              let _tableList =
                _startData.jsonData.baseMessage.editorBarData.table;
              if (!_content) {
                _content = await this.getFile(
                  _startData.jsonData.baseMessage.editorBarData.url
                );
                _content = _content.data;
                this.dataList.find(
                  i => i.id === _startData.id
                ).jsonData.baseMessage.editorBarData.content = _content;
              }
              if(!_tableList){
                let _result = [];
                let _data = _content;
                let _div = document.createElement("div");
                _div.innerHTML = _data;
                let _tableRows = _div.querySelectorAll(`table tbody tr`);
                _tableRows.forEach((i, index) => {
                  if (index == 0) return;
                  let obj = {
                    index: i.cells[0].textContent,
                    startTime: i.cells[1].textContent,
                    endTime: i.cells[2].textContent,
                    value: i.cells[3].textContent,
                    time: i.cells[4].textContent,
                    role: i.cells[5] ? i.cells[5].textContent : "",
                    code: i.cells[6] ? i.cells[6].textContent : ""
                  };
                  _result.push(obj);
                });

                _tableList = _result;
              }

              let { editorBarData} = await this.automaticCodingMixin({ tableList: _tableList});
              if(!this.nowDoTaskId.includes(_startData.id))break;

              _stepList[i].status = "1";

              this.dataList.find(i => i.id === _startData.id).jsonData = _startData.jsonData;
              this.dataList.find(
                i => i.id === _startData.id
              ).jsonData.baseMessage.editorBarData = editorBarData;

              this.dataList.find(
                i => i.id === _startData.id
              ).jsonData.steps = _stepList;
              this.updateTask(_startData.id);
              _startData.jsonData = JSON.parse(
                JSON.stringify(
                  this.dataList.find(i => i.id === _startData.id).jsonData
                )
              );
              console.log("data👉",JSON.parse(JSON.stringify(_startData)))
              console.log(`${_startData.id}:已获完成自动编码`);
            } else {
              _stepList[i].status = "1";
              this.dataList.find(
                i => i.id === _startData.id
              ).jsonData.steps = _stepList;
              this.updateTask(_startData.id);
              _startData.jsonData = JSON.parse(
                JSON.stringify(
                  this.dataList.find(i => i.id === _startData.id).jsonData
                )
              );
            }
          } else if (_step.type === "getFileIds") {
            //文件获取fileId
            _stepList[i].status = "2";
            this.dataList.find(
              i => i.id === _startData.id
            ).jsonData.steps = _stepList;
            let _fileData = _startData.jsonData.baseMessage.editorBarData;
            let { fileId } = await this.getFileIdMixin(_fileData.url);
            if(!this.nowDoTaskId.includes(_startData.id))break;
            this.dataList.find(
              i => i.id === _startData.id
            ).jsonData.file_ids = fileId;
            _stepList[i].status = "1";
            this.dataList.find(
              i => i.id === _startData.id
            ).jsonData.steps = _stepList;
            this.updateTask(_startData.id);
            _startData.jsonData = JSON.parse(
              JSON.stringify(
                this.dataList.find(i => i.id === _startData.id).jsonData
              )
            );
            console.log("data👉",JSON.parse(JSON.stringify(_startData)))
            console.log(`${_startData.id}:已获取fileId`);

          } else if (_step.type === "generateReport") {
            //生成报告
            _stepList[i].status = "2";
            this.dataList.find(
              i => i.id === _startData.id
            ).jsonData.steps = _stepList;
            let _analysisList = _startData.jsonData.analysisList;

            let promises = [];
            let _content =
              _startData.jsonData.baseMessage.editorBarData.content;
            if (!_content) {
              _content = await this.getFile(
                _startData.jsonData.baseMessage.editorBarData.url
              );
              _content = _content.data;
              _startData.jsonData.baseMessage.editorBarData.content = _content;
            }
            promises = _analysisList.map((i, index) => {
              return new Promise(async resolve => {
                _startData.jsonData.analysisList[index].status = "default"; //默认状态
                let _num = 0;
                let _maxNum = 5;
                const getAnalysis = async () => {
                  if (
                    ["tryAgainMax", "noAgentData"].includes(
                      _startData.jsonData.analysisList[index].status
                    )
                  ) {
                    return resolve(_startData.jsonData.analysisList[index]);
                  }
                  if (_num >= _maxNum) {
                    _startData.jsonData.analysisList[index].status =
                      "tryAgainMax"; //超过尝试次数
                    return resolve();
                  }
                  _num += 1;
                  let _assistantData =
                    this.dialogTagDataList.find(
                      i2 => i2.id == i.jsonData.mId
                    ) ||
                    this.dialogTagDataList.find(
                      i2 => i2.name == i.jsonData.name
                    );

                  if (!_assistantData) {
                    _startData.jsonData.analysisList[index].status =
                      "noAgentData"; //无对应的智能体
                    return resolve();
                  }
                  let data = await this.getAnalysisMixin({
                    fileId: _startData.jsonData.file_ids,
                    content: _content,
                    analysisData: i.jsonData,
                    assistantData: _assistantData,
                    baseMessage: _startData.jsonData.baseMessage
                  });
                  if(!this.nowDoTaskId.includes(_startData.id))return resolve();
                  if (data.data == 1) {
                    if (_num < _maxNum) {
                      //重试
                      getAnalysis();
                    }
                  } else {
                    _startData.jsonData.analysisList[index].status = "success";
                    _startData.jsonData.analysisList[index].jsonData =
                      data.data;
                    resolve();
                  }
                };
                getAnalysis();
              });
            });

            await Promise.all(promises).then(() => {
              console.log(`${_startData.id}:已完成分析获取`);
              if(!this.nowDoTaskId.includes(_startData.id))return;
              console.log("data👉",JSON.parse(JSON.stringify(_startData)))
              console.log(_startData.jsonData.analysisList);
              _stepList[i].status = "1";
              this.dataList.find(
                i => i.id === _startData.id
              ).jsonData.steps = _stepList;
              this.dataList.find(
                i => i.id === _startData.id
              ).jsonData = _startData.jsonData

              this.updateTask(_startData.id);
              _startData.jsonData = JSON.parse(
                JSON.stringify(
                  this.dataList.find(i => i.id === _startData.id).jsonData
                )
              );
            });
            if(!this.nowDoTaskId.includes(_startData.id))break;
          } else if (_step.type === "createClass") {
            //创建课堂
            _stepList[i].status = "2";
            this.dataList.find(
              i => i.id === _startData.id
            ).jsonData.steps = _stepList;

            //创建课堂   赋值好fileid   替换创建后课堂的基础数据  继续下一个任务
            let newOption = await this.createClassMixin(_startData.jsonData);

            if(!this.nowDoTaskId.includes(_startData.id))break;

            this.$emit("addNewCourseOption", newOption.data);
            this.dataList.find(i => i.id === _startData.id).jsonData.createId =
              newOption.tid;
            _stepList[i].status = "1";
            this.dataList.find(
              i => i.id === _startData.id
            ).jsonData.steps = _stepList;
            this.dataList.find(i => i.id === _startData.id).status = "2";
            this.updateTask(_startData.id);
            _startData.jsonData = JSON.parse(
              JSON.stringify(
                this.dataList.find(i => i.id === _startData.id).jsonData
              )
            );
            console.log(`${_startData.id}:已创建课堂`);
            // 查看是否有需要开启的任务
            if (this.dataList.find(i => i.status == "0")) {
              let id = this.dataList.find(i => i.status == "0").id;
              this.startTask(id);
            }
          }
        }
      }
    },
    // 暂停任务
    pauseTask(id) {
      let _waitTask = this.dataList.find(i => i.status === "0");
      if (_waitTask) {
        //暂停这个任务，
        this.dataList.find(i => i.id === id).status = "0";
        this.nowDoTaskId = this.nowDoTaskId.filter(i=>i!==id);
        // 开始另一个任务
        this.startTask(_waitTask.id);
      } else {
        //没有任务了,所以改为待开始（停止）
        this.dataList.find(i => i.id === id).status = "3";
      }
    },
    //停止任务
    stopTask(id) {
      let stopTask = this.dataList.find(i=>i.id===id);
      if(stopTask.status==='0'){
        this.dataList.find(i => i.id === id).status = "3";
      }if(stopTask.status==='1'){
        this.dataList.find(i => i.id === id).status = "3";
        this.nowDoTaskId = this.nowDoTaskId.filter(i=>i!==id);
      }

      console.log(stopTask)

      let _waitTask = this.dataList.find(i => i.status === "0");
      console.log(_waitTask)
      if(_waitTask){
        // 开始另一个任务
        this.startTask(_waitTask.id);
      }
      // let _waitTask = this.dataList.find(i => i.status === "0" && i.id===id);
      // if (_waitTask) {
      //   //停止这个任务，
      //   this.dataList.find(i => i.id === id).status = "3";
      //   this.nowDoTaskId = this.nowDoTaskId.filter(i=>i!==id);
      //   // 开始另一个任务
      //   this.startTask(_waitTask.id);
      // } else {
      //   //只停止这个任务
      //   this.dataList.find(i => i.id === id).status = "3";
      // }
    },
    goToEdit(id){
      let _data = this.dataList.find(i=>i.id===id);
      if(_data){
        let createId = _data.jsonData.createId;
        this.$emit("changeClass",createId);
        this.close();
      }
    },
    test() {
      this.testMixin();
    }
  },
  mounted() {
    this.getTaskList();
    this.getDialogTagDataList();
  }
};
</script>

<style scoped>
.batchCreationClassDialog {
  width: 100vw;
  height: 100vh;
}

.batchCreationClassDialog >>> .el-dialog__header,
.batchCreationClassDialog >>> .el-dialog__footer {
  display: none; /* 隐藏头部和底部 */
}

.batchCreationClassDialog >>> .el-dialog__body {
  padding: 0;
  margin: 0;
  height: 100vh;
  width: 100vw;
  overflow: auto;
  display: flex;
  justify-content: center;
}

.box {
  width: 70%;
  min-width: 500px;
  height: 100%;
  box-sizing: border-box;
  border-left: solid 1px #e1e1e1;
  border-right: solid 1px #e1e1e1;
  padding: 0 40px;
}

.b_back {
  height: 50px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;
}

.b_b_left {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.b_b_left > img {
  width: 25px;
  height: 25px;
  transform: rotate(180deg);
}

.b_b_left > span {
  font-size: 16px;
  font-weight: bold;
  margin-left: 5px;
}

.b_head {
  width: 100%;
  height: 50px;
  margin: 20px 0 0px 0;
  box-sizing: border-box;
}

.b_head > span {
  font-size: 18px;
  font-weight: bold;
  color: #000;
}

.b_nav {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  border-bottom: solid 1px rgba(150, 155, 163, 1);
}

.b_n_left {
  width: calc(100% - 60px);
  height: 100%;
  display: flex;
  align-items: center;
}

.b_n_left > span {
  height: 100%;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  cursor: pointer;
  transition: 0.3s;
  font-size: 16px;
}

.b_n_left > span:hover {
  color: rgba(5, 96, 253, 1);
}

.b_n_left > .b_n_l_active {
  color: rgba(5, 96, 253, 1);
}

.b_n_left > .b_n_l_active::after {
  content: "";
  position: absolute;
  width: 70%;
  height: 4px;
  border-radius: 4px;
  bottom: -1px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(5, 96, 253, 1);
}

.b_n_right {
  width: 60px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  color: rgba(150, 155, 163, 1);
  font-size: 16px;
}

.b_bottom {
  width: 100%;
  height: auto;
  min-height: calc(100% - 210px);
  /* height: calc(100% - 200px); */
}

.b_b_operation {
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
}
.b_b_o_left {
  width: calc(100% - 100px);
  height: 100%;
  display: flex;
  align-items: center;
  font-size: 16px;
}

.b_b_o_right {
  width: 100px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.b_b_o_right > div {
  margin-right: 10px;
  font-size: 16px;
}

.b_b_o_right > div >>> .el-checkbox {
  display: flex;
  align-items: center;
}

.b_b_o_right > span {
  width: 20px;
  height: 20px;
  cursor: pointer;
}

.b_b_o_right > span > img {
  width: 100%;
  height: 100%;
}

.b_b_list {
  width: 100%;
  height: auto;
  padding-bottom: 40px;
}
</style>
