import { HttpClient } from "@angular/common/http";
import { Component, Inject, OnInit } from "@angular/core";
import {
  MatDialog,
  MatDialogRef,
  MAT_DIALOG_DATA,
} from "@angular/material/dialog";
import { MatSnackBar, MatSnackBarConfig } from "@angular/material/snack-bar";
import { ActivatedRoute } from "@angular/router";
import { EvaluateComponent } from "./evaluate/evaluate.component";

@Component({
  selector: "app-review-files",
  templateUrl: "./review-files.component.html",
  styleUrls: [
    "../../student/examination-details/examination-details.component.scss",
    "./review-files.component.scss",
  ],
})
export class ReviewFilesComponent implements OnInit {
  constructor(
    public http: HttpClient,
    public dialog: MatDialog,
    public snackBar: MatSnackBar,
    public route: ActivatedRoute
  ) {}

  async ngOnInit(): Promise<void> {
    this.paperType = this.route.snapshot.queryParams.paperType || 1;
    await this.getTest();
    this.getUnitPlans(); //将试卷的预案考题放进数据中

    //监听 此HTML标签焦点事件
    document.addEventListener("visibilitychange", () => {
      let isHidden = document.hidden;
      if (!isHidden) {
        this.getUnitPlans(false);
      }
    });
  }

  paperType: any = 1; //阅卷/查看
  examId: any = this.route.snapshot.queryParams.examId; //考卷id
  paperId: any; //试卷id
  paperData: any; //试卷信息
  examScore: number = 0; //整个试卷的总分
  paperCompanyData: any = []; //考生具体考卷
  selectPaper: any = { id: null }; //选择当前考卷
  selectPaperType: string = "1"; //选择当前考卷内容 基本信息/作战部署

  //获取考生试卷
  async getTest() {
    await new Promise((resolve, reject) => {
      this.http
        .get(`/api/Examinations/${this.examId}`)
        .subscribe((data: any) => {
          this.paperData = data;
          this.paperId = this.paperData.paperId;

          this.paperData.examinationDataInfo.forEach((element, index) => {
            element.adjoinData
              ? (element.adjoinData = JSON.parse(element.adjoinData))
              : null;
            element.basicInfoData
              ? (element.basicInfoData = JSON.parse(element.basicInfoData))
              : null;
            element.facilityData
              ? (element.facilityData = JSON.parse(element.facilityData))
              : null;
            element.functionalDivisionData
              ? (element.functionalDivisionData = JSON.parse(
                  element.functionalDivisionData
                ))
              : null;
            element.importLocationData
              ? (element.importLocationData = JSON.parse(
                  element.importLocationData
                ))
              : null;
            element.adjoinItemScore =
              data.paperInfo.paperDataInfo[index].adjoinItemScore; //四周毗邻单项分
            element.basicInfoItemScore =
              data.paperInfo.paperDataInfo[index].basicInfoItemScore; //基本信息单项分
            element.facilityItemScore =
              data.paperInfo.paperDataInfo[index].facilityItemScore; //消防设施单项分
            element.functionalDivisionItemSocre =
              data.paperInfo.paperDataInfo[index].functionalDivisionItemSocre; //功能分区单选分
            element.importLocationItemScore =
              data.paperInfo.paperDataInfo[index].importLocationItemScore; //重点部位单项分
            if (this.paperType == 1) {
              //阅卷
              element.adjoinScore =
                data.paperInfo.paperDataInfo[index].adjoinScore; //四周毗邻 总分
              element.basicInfoScore =
                data.paperInfo.paperDataInfo[index].basicInfoScore; //基本信息 总分
              element.facilityScore =
                data.paperInfo.paperDataInfo[index].facilityScore; //消防设施 总分
              element.functionalDivisionScore =
                data.paperInfo.paperDataInfo[index].functionalDivisionScore; //功能分区 总分
              element.importLocationScore =
                data.paperInfo.paperDataInfo[index].importLocationScore; //重点部位 总分
            }
            element.score =
              element.adjoinScore +
              element.basicInfoScore +
              element.facilityScore +
              element.functionalDivisionScore +
              element.importLocationScore;
          });
          this.paperCompanyData = JSON.parse(
            JSON.stringify(data.examinationDataInfo)
          ); //具体考卷
          this.selectPaper = this.paperCompanyData[0];
          resolve(1);
        });
    });
  }

  //获得单位预案设定
  async getUnitPlans(type: boolean = true) {
    for (let index = 0; index < this.paperCompanyData.length; index++) {
      const item = this.paperCompanyData[index];
      item.planScore = 0; //预案总分
      item.planList = []; //预案data
      let params = {
        examinationId: this.route.snapshot.queryParams.examId,
        companyId: item.companyInfo.id,
      };
      await new Promise((resolve, reject) => {
        this.http
          .get(`/api/ExaminationPlans`, { params: params })
          .subscribe((data) => {
            item.planList = data;
            item.planList.forEach((element) => {
              item.planScore = item.planScore + element.paperPlanInfo.score;
            });
            if (type == false) {
              const config = new MatSnackBarConfig();
              config.verticalPosition = "top";
              config.duration = 5000;
              // this.snackBar.open('刷新成功','确定',config);
            }
            resolve(1);
          });
      });
    }
    type ? this.handleResults() : null; //计算答案正确错误
  }

  //处理数据 计算答案正确错误
  handleResults() {
    this.examScore = 0;
    this.paperCompanyData.forEach((element) => {
      this.examScore = this.examScore + element.score + element.planScore; //试卷总分
      //forEach
      element.adjoinData.forEach((item) => {
        //四周毗邻
        item.children.forEach((items) => {
          if (items.isRight === undefined) {
            items.result == items.userAnswer
              ? (items.isRight = true)
              : (items.isRight = false);
          }
        });
      });
      element.basicInfoData.forEach((item) => {
        //基本信息
        if (item.tabledata && item.tabledata.length) {
          //表格
          item.tabledata.forEach((itemss, index) => {
            if (index != 0) {
              itemss.data.forEach((items) => {
                if (items.isRight === undefined) {
                  items.result == items.userAnswer
                    ? (items.isRight = true)
                    : (items.isRight = false);
                }
              });
            }
          });
        } else {
          //input
          item.children.forEach((items) => {
            if (items.isRight === undefined) {
              items.result == items.userAnswer
                ? (items.isRight = true)
                : (items.isRight = false);
            }
          });
        }
      });
      element.facilityData.forEach((item) => {
        //消防设施
        item.children.forEach((items) => {
          if (items.isRight === undefined) {
            items.result == items.userAnswer
              ? (items.isRight = true)
              : (items.isRight = false);
          }
        });
      });
      element.functionalDivisionData.forEach((item) => {
        //功能分区
        item.tabledata.forEach((itemss, index) => {
          if (index != 0) {
            itemss.data.forEach((items) => {
              if (items.isRight === undefined) {
                items.result == items.userAnswer
                  ? (items.isRight = true)
                  : (items.isRight = false);
              }
            });
          }
        });
      });
      element.importLocationData.forEach((item) => {
        //重点部位
        item.tabledata.forEach((itemss, index) => {
          if (index != 0) {
            itemss.data.forEach((items) => {
              if (items.isRight === undefined) {
                items.result == items.userAnswer
                  ? (items.isRight = true)
                  : (items.isRight = false);
              }
            });
          }
        });
      });
      //forEach
    });
    this.getPaperGrade();
  }

  //循环 获取最新得分
  getPaperGrade() {
    this.paperCompanyData.forEach((element) => {
      //forEach
      element.adjoinTotalPoints = 0; //四周毗邻 分数
      element.adjoinData.forEach((item) => {
        //四周毗邻
        item.children.forEach((items) => {
          items.isRight
            ? (element.adjoinTotalPoints =
                element.adjoinTotalPoints + element.adjoinItemScore)
            : null;
        });
      });
      element.basicInfoTotalPoints = 0; //基本信息总分
      element.basicInfoData.forEach((item) => {
        //基本信息
        if (item.tabledata && item.tabledata.length) {
          //表格
          let indexList = [];
          item.tabledata[0].data.forEach((e, index) => {
            let everyRow = { isRight: true, index: index };
            indexList.push(everyRow);
          }); //表格 行数
          item.tabledata.forEach((itemss, index) => {
            indexList.forEach((ele) => {
              if (
                itemss.data[ele.index].isRight != undefined &&
                itemss.data[ele.index].isRight === false
              ) {
                ele.isRight = false;
              }
            });
          });
          indexList.forEach((item) => {
            item.isRight
              ? (element.basicInfoTotalPoints =
                  element.basicInfoTotalPoints + element.basicInfoItemScore)
              : null;
          });
        } else {
          //input
          item.children.forEach((items) => {
            items.isRight
              ? (element.basicInfoTotalPoints =
                  element.basicInfoTotalPoints + element.basicInfoItemScore)
              : null;
          });
        }
      });
      element.facilityTotalPoints = 0; //消防设施总分
      element.facilityData.forEach((item) => {
        //消防设施
        item.children.forEach((items) => {
          items.isRight
            ? (element.facilityTotalPoints =
                element.facilityTotalPoints + element.facilityItemScore)
            : null;
        });
      });
      element.functionalDivisionTotalPoints = 0; //功能分区总分
      element.functionalDivisionData.forEach((item) => {
        //功能分区
        if (item.tabledata && item.tabledata.length) {
          let indexList = [];
          item.tabledata[0].data.forEach((e, index) => {
            let everyRow = { isRight: true, index: index };
            indexList.push(everyRow);
          }); //表格 行数
          item.tabledata.forEach((itemss, index) => {
            indexList.forEach((ele) => {
              if (
                itemss.data[ele.index].isRight != undefined &&
                itemss.data[ele.index].isRight === false
              ) {
                ele.isRight = false;
              }
            });
          });
          indexList.forEach((item) => {
            item.isRight
              ? (element.functionalDivisionTotalPoints =
                  element.functionalDivisionTotalPoints +
                  element.functionalDivisionItemSocre)
              : null;
          });
        }
      });
      element.importLocationTotalPoints = 0; //重点部位总分
      element.importLocationData.forEach((item) => {
        //重点部位
        if (item.tabledata && item.tabledata.length) {
          let indexList = [];
          item.tabledata[0].data.forEach((e, index) => {
            let everyRow = { isRight: true, index: index };
            indexList.push(everyRow);
          }); //表格 行数
          item.tabledata.forEach((itemss, index) => {
            indexList.forEach((ele) => {
              if (
                itemss.data[ele.index].isRight != undefined &&
                itemss.data[ele.index].isRight === false
              ) {
                ele.isRight = false;
              }
            });
          });
          indexList.forEach((item) => {
            item.isRight
              ? (element.importLocationTotalPoints =
                  element.importLocationTotalPoints +
                  element.importLocationItemScore)
              : null;
          });
        }
      });
      //forEach
    });
  }

  //修改结果
  editResults(e) {
    let data = e;
    const dialogRef = this.dialog.open(editRightWrongComponent, { data });
    dialogRef.afterClosed().subscribe((data) => {
      if (data) {
        if (e.isRight != data.isChecked) {
          e.isRight = data.isChecked;
          this.getPaperGrade();
        }
      }
    });
  }

  //刷新预案设定表格
  refreshTable() {
    this.getUnitPlans(false);
  }

  //基本信息表格 是否展示当前行
  rowIsShow(children, tag) {
    let isShow: boolean = false;
    children.forEach((element) => {
      element.result == tag ? (isShow = true) : null;
    });
    return isShow;
  }

  //切换 选择考卷
  togglePaper(e) {
    if (this.selectPaper.id != e.id) {
      this.selectPaper = e;
    }
  }

  //切换 选择考卷内容
  togglePaperType(e) {
    if (this.selectPaperType != e) {
      this.selectPaperType = e;
    }
  }

  //提交阅卷结果
  submitResult() {
    const dialogRef = this.dialog.open(EvaluateComponent, {
      data: { Evaluate: "" },
    });

    dialogRef.afterClosed().subscribe((result) => {
      // console.log("The dialog was closed", result);
      if (result.type) {
        let bodyData = {
          id: this.paperData.id,
          isMarked: true,
          totalScore: 0,
          examinationDataInfo: [],
          comment: result.value,
        };
        let paramsData = JSON.parse(JSON.stringify(this.paperCompanyData)); //考卷
        paramsData.forEach((element) => {
          //计算总分
          bodyData.totalScore =
            bodyData.totalScore +
            element.adjoinTotalPoints +
            element.basicInfoTotalPoints +
            element.facilityTotalPoints +
            element.functionalDivisionTotalPoints +
            element.importLocationTotalPoints;
          element.planList.forEach((item) => {
            bodyData.totalScore = bodyData.totalScore + item.score || 0;
          });
          //计算总分
          element.adjoinScore = element.adjoinTotalPoints; //四周毗邻
          delete element.adjoinTotalPoints;
          delete element.adjoinItemScore;
          element.basicInfoScore = element.basicInfoTotalPoints; //基本信息
          delete element.basicInfoTotalPoints;
          delete element.basicInfoItemScore;
          element.facilityScore = element.facilityTotalPoints; //消防设施
          delete element.facilityTotalPoints;
          delete element.facilityItemScore;
          element.functionalDivisionScore =
            element.functionalDivisionTotalPoints; //功能分区
          delete element.functionalDivisionTotalPoints;
          delete element.functionalDivisionItemSocre;
          element.importLocationScore = element.importLocationTotalPoints; //重点部位
          delete element.importLocationTotalPoints;
          delete element.importLocationItemScore;
          delete element.planList;
          delete element.planScore;
          delete element.score;
          element.adjoinData = JSON.stringify(element.adjoinData);
          element.basicInfoData = JSON.stringify(element.basicInfoData);
          element.facilityData = JSON.stringify(element.facilityData);
          element.functionalDivisionData = JSON.stringify(
            element.functionalDivisionData
          );
          element.importLocationData = JSON.stringify(
            element.importLocationData
          );
        });
        bodyData.examinationDataInfo = paramsData;
        this.http
          .put(`/api/Examinations/${this.paperData.id}`, bodyData)
          .subscribe((data) => {
            const config = new MatSnackBarConfig();
            config.verticalPosition = "top";
            config.duration = 5000;
            this.snackBar.open(
              "阅卷结果提交成功,页面将于一秒后关闭!",
              "确定",
              config
            );
            setTimeout(() => {
              window.close();
            }, 1000);
          });
      }
    });
  }

  //作战部署 阅卷
  readExam(item, e) {
    sessionStorage.setItem("companyName", this.selectPaper.companyInfo.name);
    sessionStorage.setItem("planId", item.paperPlanInfo.planComponentId);
    sessionStorage.setItem(
      "buildingTypeId",
      this.selectPaper.companyInfo.buildingTypes[0].id
    );
    sessionStorage.setItem("companyId", this.selectPaper.companyInfo.id);
    sessionStorage.setItem("remark", item.remark);
    let openType;
    item.paperPlanInfo.examPlanType == 0 ? (openType = 1) : (openType = 2);
    window.open(
      `/canvasToolRead?planName=${item.paperPlanInfo.title}&paperplanId=${item.paperPlanId}&openType=${openType}&paperId=${this.paperId}&examId=${this.route.snapshot.queryParams.examId}&planComponentId=${item.paperPlanInfo.planComponentId}&paperType=${e}`
    );
  }
}

export interface radioType {
  isRight: boolean;
  name: string;
}
@Component({
  selector: "app-edit-rightWrong",
  templateUrl: "./editRightWrong.html",
  styleUrls: ["./review-files.component.scss"],
})
export class editRightWrongComponent implements OnInit {
  constructor(
    public http: HttpClient,
    public dialog: MatDialog,
    public snackBar: MatSnackBar,
    public route: ActivatedRoute,
    @Inject(MAT_DIALOG_DATA) public data: any,
    public dialogRef: MatDialogRef<any>
  ) {}

  ngOnInit(): void {
    this.isChecked = JSON.parse(JSON.stringify(this.data.isRight));
  }

  isChecked: boolean; //是否正确
  radioList: radioType[] = [
    { isRight: true, name: "正确" },
    { isRight: false, name: "错误" },
  ];

  submit() {
    let data = { isChecked: this.isChecked };
    this.dialogRef.close(data);
  }
}