import { Component, OnInit, ViewChild, Inject } from "@angular/core";
import {
  HttpClient,
  HttpHeaders,
  HttpErrorResponse,
} from "@angular/common/http";
import {
  MatTreeFlatDataSource,
  MatTreeFlattener,
} from "@angular/material/tree";
import { MatPaginator } from "@angular/material/paginator";
import { FlatTreeControl } from "@angular/cdk/tree";
import { FormControl } from "@angular/forms";
import { Router, ActivatedRoute } from "@angular/router";
import { PageEvent } from "@angular/material/paginator";
import {
  MatDialogRef,
  MatDialog,
  MAT_DIALOG_DATA,
} from "@angular/material/dialog";
import { MatSnackBar, MatSnackBarConfig } from "@angular/material/snack-bar";
import { TreeService } from "../../http-interceptors/tree.service";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { async } from "@angular/core/testing";
import { Viewer } from "photo-sphere-viewer";
import { STEPPER_GLOBAL_OPTIONS } from "@angular/cdk/stepper";
import Swiper from "swiper";
import { resolve } from "dns";
import { DomSanitizer } from "@angular/platform-browser";
import { EditPlanCategoryComponent } from "./edit-plan-category/edit-plan-category.component";
declare var CryptoJS;
@Component({
  selector: "app-entry-plan-look",
  templateUrl: "./entry-plan-look.component.html",
  styleUrls: ["./entry-plan-look.component.scss"],
})
export class EntryPlanLookComponent implements OnInit {
  constructor(
    private http: HttpClient,
    private router: Router,
    private route: ActivatedRoute,
    private tree: TreeService,
    public dialog: MatDialog,
    public snackBar: MatSnackBar,
    private sanitizer: DomSanitizer
  ) {}
  pageEvent: PageEvent;
  private _transformer = (node, level: number) => {
    //初始化tree
    return {
      expandable: !!node.children && node.children.length > 0,
      name: node.name,
      level: level,
      id: node.id,
      parentId: node.parentId,
      children: node.children,
    };
  };
  treeControl = new FlatTreeControl<any>(
    (node) => node.level,
    (node) => node.expandable
  );
  treeFlattener = new MatTreeFlattener(
    this._transformer,
    (node) => node.level,
    (node) => node.expandable,
    (node) => node.children
  );
  dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
  myControl = new FormControl();
  hasChild = (_: number, node: any) => node.expandable;
  IsNewData = true; //维护更新活新增
  displayedColumns: string[] = [
    "state",
    "planname",
    "addpeople",
    "addtime",
    "planCategory",
    "plantype",
    "auditstate",
    "weihustate",
    "isopen",
    "preparethelevel",
    "operation",
  ];
  tabledataSource: any;
  //分页
  @ViewChild(MatPaginator, { static: true })
  paginator: MatPaginator;
  length: any; //共多少条数据
  pageSize: any; //每页条数
  pageSizeOptions: number[] = [10]; //设置每页条数
  PageNumber: any = 1; //第几页

  unitdata: any = {};

  unittypeId: any; //单位类型id

  //获取当前单位信息
  compantData: any;
  getCompanyData() {
    let CompanyName = sessionStorage.getItem("companyName");
    let header = {
      CompanyName: CompanyName || "",
    };
    this.http.get("/api/Plans", { params: header }).subscribe((data: any) => {
      data.items.forEach((element) => {
        if (element.companyId === this.route.snapshot.queryParams.unitId) {
          this.compantData = element.company;
          return;
        }
      });
      // console.log(123,this.compantData)
      this.unitdata.unitname = this.compantData.name;
      this.unitdata.organizationName = this.compantData.organizationName;
      this.unitdata.unittype = this.compantData.buildingTypes[0].name;
      this.unitdata.unitaddress = this.compantData.address;
      this.unittypeId = this.compantData.buildingTypes[0].id;
    });
  }
  //跳转单位信息
  lookUnitData() {
    sessionStorage.setItem("editable", "0");
    sessionStorage.setItem(
      "companyName",
      this.route.snapshot.queryParams.unitName
    );
    sessionStorage.setItem("companyId", this.route.snapshot.queryParams.unitId);
    // sessionStorage.setItem(element.id,JSON.stringify(element.companyIntegrityScore))
    window.open(
      `/keyUnit/viewunitinfo?id=${this.route.snapshot.queryParams.unitId}&usci=${this.route.snapshot.queryParams.usci}`
    );
  }
  //分页事件
  changePage(e) {
    this.PageNumber = e.pageIndex + 1;
    this.getAllPlanComponents();
  }
  isoperation: any; //判断预案录入  和  审核公开预案  区别变量
  ngOnInit(): void {
    this.tabledataSource = [];
    this.getCompanyData();
    this.isoperation = this.route.snapshot.queryParams.operation;
    this.unitdata.unitname = this.route.snapshot.queryParams.unitName;
    this.unitdata.organizationName = this.route.snapshot.queryParams.orName;
    this.unitdata.unittype = this.route.snapshot.queryParams.unitType;
    this.unitdata.unitaddress = this.route.snapshot.queryParams.unitAdd;
    this.companyId = this.route.snapshot.queryParams.unitId;
    this.unittypeId = this.route.snapshot.queryParams.unitTypeId;
    this.getAllPlanComponents();
  }
  //查看预案
  lookPlan(e) {
    if (e.planType == 16 || e.planType == 4 || e.planType == 8) {
      if (e.planType == 16 && e.attachmentUrls == null) {
        window.open(
          `/planManagement/createplanonlinefive?navIsOpen=false&companyId=${this.companyId}&planName=${e.name}&unitName=${this.unitdata.unitname}&planCategory=${e.planCategory}&planId=${e.id}&unitTypeId=${this.compantData.buildingTypes[0].id}&orName=${this.compantData.organizationName}&orId=${this.compantData.organizationId}&pattern=false`
        );
      } else {
        var index = e.attachmentUrls[0].indexOf("/");
        if (e.attachmentUrls[0].substr(0, index) == "psw") {
          const dialogRef = this.dialog.open(PsViewer, {
            width: "1500px",
            height: "800px",
            data: e.attachmentUrls[0],
          });
        } else if (
          e.attachmentUrls[0].substr(
            e.attachmentUrls[0].length - 3,
            e.attachmentUrls[0].length
          ) == "JPG" ||
          e.attachmentUrls[0].substr(
            e.attachmentUrls[0].length - 3,
            e.attachmentUrls[0].length
          ) == "png" ||
          e.attachmentUrls[0].substr(
            e.attachmentUrls[0].length - 3,
            e.attachmentUrls[0].length
          ) == "jpeg" ||
          e.attachmentUrls[0].substr(
            e.attachmentUrls[0].length - 3,
            e.attachmentUrls[0].length
          ) == "jpg"
        ) {
          let data = e;
          const dialogRef = this.dialog.open(ImgDetails, {
            //调用open方法打开对话框并且携带参数过去
            data: data.attachmentUrls,
          });
          dialogRef.afterClosed().subscribe();
        } else {
          let fetchUrl = e.attachmentUrls[0];
          if (fetchUrl) {
            let suffix = fetchUrl
              .split(".")
              [fetchUrl.split(".").length - 1].toLowerCase();
            if (suffix == "docx" || suffix == "doc") {
              let arr = fetchUrl.split(".");
              arr[arr.length - 1] = "pdf";
              window.open(`/api/Objects/PlanPlatform/` + arr.join("."));
            } else if (suffix == "pdf") {
              window.open(`/api/Objects/PlanPlatform/` + fetchUrl);
            } else {
              let config = new MatSnackBarConfig();
              config.verticalPosition = "top";
              config.duration = 3000;
              this.snackBar.open("该文件类型暂不支持在线查看", "确定", config);
            }
          }
        }
      }
    }
    if (e.planType == 1 && e.planMode == 2) {
      //如果是在线编辑
      let id = e.id;
      sessionStorage.setItem("planId", id);
      sessionStorage.setItem("companyId", this.companyId);
      sessionStorage.setItem("buildingTypeId", this.unittypeId);
      sessionStorage.setItem("editable", "0");
      sessionStorage.setItem("planName", e.name);
      let companyId = sessionStorage.getItem("companyId");
      window.open(
        `/keyUnit/viewunitinfoplan?id=${companyId}&orName=${this.route.snapshot.queryParams.orName}&orId=${this.route.snapshot.queryParams.orId}`
      );
    }
    if (e.planType == 2 && e.planMode == 3) {
      //如果是跳转网页
      if (e.url.indexOf("app") == 0) {
        window.location.href = e.url;
      } else {
        sessionStorage.setItem("url", e.url);
        if ((e.url as string).includes("gis/threeDimensionalHome")) {
          //三维预案
          window.open(
            `${e.url}?unitId=${this.companyId}&unitName=${this.unitdata.unitname}&editMode=false`
          );
        } else {
          window.open(`/planManagement/webLook`);
        }
      }
    }
  }
  //编辑预案
  editPlan(e) {
    console.log(e);
    const config = new MatSnackBarConfig();
    config.verticalPosition = "top";
    config.duration = 3000;
    if (e.openRange != "未公开" || e.auditStatus != 8) {
      let isTrue = confirm(
        "您确定编辑吗,若是公开预案会变成未公开状态,审核状态也会改变"
      );
      if (isTrue) {
        if (e.auditStatus == 8) {
          if (e.planType == 1) {
            //如果是在线编辑
            let id = e.id;
            let body = {};
            let resetAudit = true;
            let headers = new HttpHeaders({
              "Content-Type": "text/json",
            });
            let options = {
              headers,
            };
            this.http
              .put(
                `/api/PlanComponents/${e.id}?resetAudit=${resetAudit}`,
                body,
                options
              )
              .subscribe((data) => {
                this.getAllPlanComponents();
                // this.lookPlan(e)
              });
            sessionStorage.setItem("planId", id);
            sessionStorage.setItem("companyId", this.companyId);
            sessionStorage.setItem("buildingTypeId", this.unittypeId);
            sessionStorage.setItem("editable", "1");
            sessionStorage.setItem("planName", e.name);
            let companyId = sessionStorage.getItem("companyId");
            window.open(
              `/keyUnit/editunitinfo?id=${companyId}&orName=${this.route.snapshot.queryParams.orName}&orId=${this.route.snapshot.queryParams.orId}`
            );
          } else if (e.planType == 16) {
            if (e.attachmentUrls == null) {
              if (e.planMode == 4) {
                window.open(
                  `/planManagement/createplanonlinefive?navIsOpen=false&companyId=${this.companyId}&planName=${e.name}&unitName=${this.unitdata.unitname}&planCategory=${e.planCategory}&planId=${e.id}&unitTypeId=${this.compantData.buildingTypes[0].id}&orName=${this.compantData.organizationName}&orId=${this.compantData.organizationId}&pattern=true&planMode=${e.planMode}`
                );
              } else {
                window.open(
                  `/planManagement/createplanonlinefive?navIsOpen=false&companyId=${this.companyId}&planName=${e.name}&unitName=${this.unitdata.unitname}&planCategory=${e.planCategory}&planId=${e.id}&unitTypeId=${this.compantData.buildingTypes[0].id}&orName=${this.compantData.organizationName}&orId=${this.compantData.organizationId}&pattern=true&planMode=${e.planMode}`
                );
              }
            } else {
              let body = {};
              let resetAudit = true;
              let headers = new HttpHeaders({
                "Content-Type": "text/json",
              });
              let options = {
                headers,
              };
              this.http
                .put(
                  `/api/PlanComponents/${e.id}?resetAudit=${resetAudit}`,
                  body,
                  options
                )
                .subscribe(
                  (data) => {
                    /* this.getAllPlanComponents()
                this.lookPlan(e) */
                    const dialogRef = this.dialog.open(editUpload, {
                      width: "300px",
                      height: "150px",
                      data: {
                        id: e.id,
                        companyId: this.companyId,
                        unitType: this.unitdata.unittype,
                        unitName: this.unitdata.unitname,
                      },
                      disableClose: true,
                    });
                    dialogRef.afterClosed().subscribe((data) => {
                      this.getAllPlanComponents();
                    });
                  } /* ,err => {
            this.snackBar.open(err,'确定',config);
          } */
                );
            }
          } else if (e.planType == 2) {
            //三维预案
            const dialogRef = this.dialog.open(ChangeUrl, {
              //改网址
              data: { element: e },
            });
            dialogRef.afterClosed().subscribe((data) => {
              if (data) {
                const config = new MatSnackBarConfig();
                config.verticalPosition = "top";
                config.duration = 3000;
                this.snackBar.open("修改成功!", "确定", config);
                this.getAllPlanComponents();
              }
            });
          } else {
            this.snackBar.open(
              "只有二维预案和文本预案可以编辑!",
              "确定",
              config
            );
          }
        } else {
          //let isTrue = confirm('编辑后审核状态会成为未审核状态,您确定要编辑吗')
          if (e.planType == 1) {
            //如果是在线编辑
            let id = e.id;
            let body = {};
            let resetAudit = true;
            let headers = new HttpHeaders({
              "Content-Type": "text/json",
            });
            let options = {
              headers,
            };
            this.http
              .put(
                `/api/PlanComponents/${e.id}?resetAudit=${resetAudit}`,
                body,
                options
              )
              .subscribe(
                (data) => {
                  this.getAllPlanComponents();
                  // this.lookPlan(e)
                } /* ,err => {
            this.snackBar.open(err,'确定',config);
          } */
              );
            sessionStorage.setItem("planId", id);
            sessionStorage.setItem("companyId", this.companyId);
            sessionStorage.setItem("buildingTypeId", this.unittypeId);
            sessionStorage.setItem("editable", "1");
            sessionStorage.setItem("planName", e.name);
            let companyId = sessionStorage.getItem("companyId");
            window.open(
              `/keyUnit/editunitinfo?id=${companyId}&orName=${this.route.snapshot.queryParams.orName}&orId=${this.route.snapshot.queryParams.orId}`
            );
          } else if (e.planType == 16) {
            if (e.attachmentUrls == null) {
              console.log(this.compantData);
              window.open(
                `/planManagement/createplanonlinefive?navIsOpen=false&companyId=${this.companyId}&planName=${e.name}&unitName=${this.unitdata.unitname}&planCategory=${e.planCategory}&planId=${e.id}&unitTypeId=${this.compantData.buildingTypes[0].id}&orName=${this.compantData.organizationName}&orId=${this.compantData.organizationId}&planMode=${e.planMode}`
              );
            } else {
              let body = {};
              let resetAudit = true;
              let headers = new HttpHeaders({
                "Content-Type": "text/json",
              });
              let options = {
                headers,
              };
              this.http
                .put(
                  `/api/PlanComponents/${e.id}?resetAudit=${resetAudit}`,
                  body,
                  options
                )
                .subscribe(
                  (data) => {
                    const dialogRef = this.dialog.open(editUpload, {
                      width: "300px",
                      height: "150px",
                      data: {
                        id: e.id,
                        companyId: this.companyId,
                        unitType: this.unitdata.unittype,
                        unitName: this.unitdata.unitname,
                      },
                      disableClose: true,
                    });
                    dialogRef.afterClosed().subscribe((data) => {
                      this.getAllPlanComponents();
                    });
                  } /* ,err => {
            this.snackBar.open(err,'确定',config);
          } */
                );
            }
          } else if (e.planType == 2) {
            //三维预案

            const dialogRef = this.dialog.open(ChangeUrl, {
              data: { element: e },
            });
            dialogRef.afterClosed().subscribe((data) => {
              if (data) {
                const config = new MatSnackBarConfig();
                config.verticalPosition = "top";
                config.duration = 3000;
                this.snackBar.open("修改成功!", "确定", config);
                this.getAllPlanComponents();
              }
            });
          } else {
            this.snackBar.open(
              "只有二维预案和文本预案可以编辑!",
              "确定",
              config
            );
          }
        }
      }
    } else {
      if (e.planType == 1) {
        //如果是在线编辑
        let id = e.id;
        sessionStorage.setItem("planId", id);
        sessionStorage.setItem("companyId", this.companyId);
        sessionStorage.setItem("buildingTypeId", this.unittypeId);
        sessionStorage.setItem("editable", "1");
        sessionStorage.setItem("planName", e.name);
        let companyId = sessionStorage.getItem("companyId");
        window.open(
          `/keyUnit/editunitinfo?id=${companyId}&orName=${this.route.snapshot.queryParams.orName}&orId=${this.route.snapshot.queryParams.orId}`
        );
      } else if (e.planType == 16) {
        if (e.attachmentUrls == null) {
          if (e.planMode == 4) {
            window.open(
              `/planManagement/createplanonlinefive?navIsOpen=false&companyId=${this.companyId}&planName=${e.name}&unitName=${this.unitdata.unitname}&planCategory=${e.planCategory}&planId=${e.id}&unitTypeId=${this.compantData.buildingTypes[0].id}&orName=${this.compantData.organizationName}&orId=${this.compantData.organizationId}&pattern=true&planMode=${e.planMode}`
            );
          } else {
            window.open(
              `/planManagement/createplanonlinefive?navIsOpen=false&companyId=${this.companyId}&planName=${e.name}&unitName=${this.unitdata.unitname}&planCategory=${e.planCategory}&planId=${e.id}&unitTypeId=${this.compantData.buildingTypes[0].id}&orName=${this.compantData.organizationName}&orId=${this.compantData.organizationId}&pattern=true&planMode=${e.planMode}`
            );
          }
        } else {
          let body = {};
          let resetAudit = true;
          let headers = new HttpHeaders({
            "Content-Type": "text/json",
          });
          let options = {
            headers,
          };
          this.http
            .put(
              `/api/PlanComponents/${e.id}?resetAudit=${resetAudit}`,
              body,
              options
            )
            .subscribe((data) => {
              const dialogRef = this.dialog.open(editUpload, {
                width: "300px",
                height: "200px",
                data: {
                  id: e.id,
                  companyId: this.companyId,
                  unitType: this.unitdata.unittype,
                  unitName: this.unitdata.unitname,
                },
                disableClose: true,
              });
              dialogRef.afterClosed().subscribe((data) => {
                this.getAllPlanComponents();
              });
            });
        }
      } else if (e.planType == 2) {
        //三维预案
        const dialogRef = this.dialog.open(ChangeUrl, {
          //改网址
          data: { element: e },
        });
        dialogRef.afterClosed().subscribe((data) => {
          if (data) {
            const config = new MatSnackBarConfig();
            config.verticalPosition = "top";
            config.duration = 3000;
            this.snackBar.open("修改成功!", "确定", config);
            this.getAllPlanComponents();
          }
        });
        /* if (e.url.indexOf('app') == 0) {
          window.location.href = e.url
        } else {
          sessionStorage.setItem("url", e.url)
          if ((e.url as string).includes('gis/threeDimensionalHome')) { //三维预案
            window.open(`${e.url}?unitId=${this.companyId}&unitName=${this.unitdata.unitname}&editMode=true`)
          } else {
            window.open(`/planManagement/webLook`)
          }
        } */
      } else {
        this.snackBar.open("只有二维预案和文本预案可以编辑!", "确定", config);
      }
      /* else {
         if (e.planType == 1) {  //如果是在线编辑
           let id = e.id
           sessionStorage.setItem("planId", id)
           sessionStorage.setItem("companyId", this.companyId)
           sessionStorage.setItem("buildingTypeId", this.unittypeId)
           sessionStorage.setItem("editable", "1")
           sessionStorage.setItem("planName", e.name)
           let companyId = sessionStorage.getItem("companyId")
           window.open(`/keyUnit/editunitinfo?id=${companyId}&orName=${this.route.snapshot.queryParams.orName}&orId=${this.route.snapshot.queryParams.orId}`);
         }
         else if (e.planType == 16) {
           if (e.attachmentUrls == null) {
             console.log(this.compantData)
             window.open(`/planManagement/createplanonlinefive?navIsOpen=false&companyId=${this.companyId}&planName=${e.name}&unitName=${this.unitdata.unitname}&planCategory=${e.planCategory}&planId=${e.id}&unitTypeId=${this.compantData.buildingTypes[0].id}&orName=${this.compantData.organizationName}&orId=${this.compantData.organizationId}`)
           }
           else {
             let body = {};
             let resetAudit = true
             let headers = new HttpHeaders({
               'Content-Type': 'text/json'
             });
             let options = {
               headers
             };
             this.http.put(`/api/PlanComponents/${e.id}?resetAudit=${resetAudit}`, body, options).subscribe(data => {
               this.getAllPlanComponents()
               this.lookPlan(e)
             })
           }
 
         }
         else if (e.planType == 2) { //三维预案
           const dialogRef = this.dialog.open(ChangeUrl, {
             data: { element: e }
           });
           dialogRef.afterClosed().subscribe(
             data => {
               if (data) {
                 const config = new MatSnackBarConfig();
                 config.verticalPosition = 'top';
                 config.duration = 3000
                 this.snackBar.open('修改成功!', '确定', config);
                 this.getAllPlanComponents()
                 
               }
             }
           );
         } else {
 
           this.snackBar.open('只有二维预案和文本预案可以编辑!', '确定', config);
         }
       
     } */
    }
  }
  allPlanComponents: any; //所有预案组件
  companyId: any; //新建预案需要使用的id
  planId: any; //统一预案id
  lookUrl; //查看文件路径
  //改名
  changeName(element) {
    // console.log(element)
    const dialogRef = this.dialog.open(ChangeName, {
      data: { element: element },
    });
    dialogRef.afterClosed().subscribe((data) => {
      if (data) {
        const config = new MatSnackBarConfig();
        config.verticalPosition = "top";
        config.duration = 3000;
        this.snackBar.open("修改成功!", "确定", config);
        this.getAllPlanComponents();
      }
    });
  }

  //修改预案级别
  editPlanCategory(data) {
    console.log(data);
    const dialogRef = this.dialog.open(EditPlanCategoryComponent, {
      data: data,
    });
    dialogRef.afterClosed().subscribe((data) => {
      if (data) {
        const config = new MatSnackBarConfig();
        config.verticalPosition = "top";
        config.duration = 3000;
        this.snackBar.open("修改成功!", "确定", config);
        this.getAllPlanComponents();
      }
    });
  }
  //获得所有预案组件
  audit: boolean;
  getAllPlanComponents() {
    let pagetype = this.route.snapshot.queryParams.pagetype;
    let unitId = this.route.snapshot.queryParams.unitId;
    let paramsData: any;
    if (pagetype == "entryplan") {
      paramsData = {
        companyId: unitId,
        pageNumber: this.PageNumber,
        pageSize: "",
        sort: "",
      };
    }
    if (pagetype == "passplan") {
      paramsData = {
        companyId: unitId,
        pageNumber: this.PageNumber,
        pageSize: "",
        AuditStatus: 2,
        sort: "",
      };
    }
    if (pagetype == "openplan") {
      paramsData = {
        companyId: unitId,
        pageNumber: this.PageNumber,
        pageSize: "",
        IsPublic: true,
        sort: "",
      };
    }

    this.http
      .get("/api/PlanComponents", { params: paramsData })
      .subscribe((data: any) => {
        this.length = data.totalCount;
        this.allPlanComponents = data;
        this.tabledataSource = data.items;
        console.log("预案列表", data.items);
        /* if(this.tabledataSource.isNewData){
        this.tabledataSource.auditStatus==8?this.audit=true:false
      }else{
        (this.tabledataSource.newVerifyState=='待终审'&&this.tabledataSource.newVerifyState=='审核中'&&this.tabledataSource.maintenanceVerifyState!='未提交审核')?this.audit=false:true
      } */
      });
  }
  //删除预案
  deletePlan(plandata) {
    const config = new MatSnackBarConfig();
    config.verticalPosition = "top";
    config.duration = 3000;
    let isTrue = confirm("您确定要删除吗");
    if (isTrue) {
      if (plandata.planType == 1) {
        //如果删除的是二维预案
        this.http.delete(`/api/PlanComponents2D/${plandata.id}`).subscribe(
          (data) => {
            this.snackBar.open("删除成功!", "确定", config);
            this.getAllPlanComponents();
          },
          (err) => {
            this.snackBar.open(err, "确定", config);
          }
        );
      } else {
        this.http.delete(`/api/PlanComponents/${plandata.id}`).subscribe(
          (data) => {
            const config = new MatSnackBarConfig();
            config.verticalPosition = "top";
            config.duration = 3000;
            this.snackBar.open("删除成功!", "确定", config);
            this.getAllPlanComponents();
          },
          (err) => {
            this.snackBar.open(err, "确定", config);
          }
        );
      }
    }
  }
  //提交审核
  submitAudit(element) {
    const config = new MatSnackBarConfig();
    config.verticalPosition = "top";
    config.duration = 3000;
    if (element.auditStatus == 4 || element.auditStatus == 32) {
      this.snackBar.open(
        "审核退回的预案需要修改后方可再次提交审核!",
        "确定",
        config
      );
    }
    if (element.planType == 1) {
      //如果提交审核的是二维预案
      if (
        element.auditStatus == 8 ||
        (element.auditStatus == 2 && !element.isNewData)
      ) {
        this.http
          .put(`/api/PlanComponents2D/${element.id}/Commit`, "")
          .subscribe((data) => {
            this.getAllPlanComponents();
          });
      }
    } else {
      this.http
        .put(`/api/PlanComponents/${element.id}/Commit`, "")
        .subscribe((data) => {
          this.getAllPlanComponents();
        });
    }
  }

  //撤销审核
  cancelAudit(element) {
    if (element.planType == 1) {
      //如果撤销审核的是二维预案
      this.http
        .put(`/api/PlanComponents2D/${element.id}/Cancel`, "")
        .subscribe((data) => {
          this.getAllPlanComponents();
        });
    } else {
      this.http
        .put(`/api/PlanComponents/${element.id}/Cancel`, "")
        .subscribe((data) => {
          this.getAllPlanComponents();
        });
    }
  }
  //审核结果
  auditResult(element) {
    const dialogRef = this.dialog.open(AuditResult, {
      width: "395px",
      data: { element: element },
    });
  }

  //下载↓
  selectDownloadFile: any; //选择下载的文件
  download: any; //下载文件元数据
  downloadisLoading: boolean = false; //进度条loading加载
  downloadProgress: number = 0; //进度条进度
  downloadFileName: any;

  uploadFileLonging: any;
  //读取下载文件信息
  readFile(element) {
    this.uploadFileLonging = element;
    console.log(element);
    if (
      element.planType == 16 &&
      (element.planMode == 4 || element.planMode == 2)
    ) {
      const dialogRef = this.dialog.open(wenbenUpload, {
        width: "180px",
        height: "200px",
        disableClose: true,
        data: {
          src: `/planManagement/createplanonlinefive?navIsOpen=false&companyId=${this.companyId}&planName=${element.name}&unitName=${this.unitdata.unitname}&planCategory=${element.planCategory}&planId=${element.id}&unitTypeId=${this.compantData.buildingTypes[0].id}&orName=${this.compantData.organizationName}&orId=${this.compantData.organizationId}&pattern=false&xiazai=true`,
        },
      });
      //window.open(`/planManagement/createplanonlinefive?navIsOpen=false&companyId=${this.companyId}&planName=${element.name}&unitName=${this.unitdata.unitname}&planCategory=${element.planCategory}&planId=${element.id}&unitTypeId=${this.compantData.buildingTypes[0].id}&orName=${this.compantData.organizationName}&orId=${this.compantData.organizationId}&pattern=false&xiazai=true`)
    } else {
      const dialogRef = this.dialog.open(DownloadFile, {
        width: "435px",
        // height:"410px",
        data: {
          fileUrls: element.attachmentUrls,
          compantData: this.unitdata.unitname,
          element: element,
        },
      });
      dialogRef.afterClosed().subscribe((data) => {
        if (data) {
          this.downloadFileName = data.fileName;
          this.download = data;
          this.downloadFile();
        }
      });
    }
  }

  //初始化下载
  downloadFile() {
    this.downloadProgress = 0;
    let file = this.download;
    let fileSize = file.fileLength; //下载文件的总大小
    let shardSize = 10 * 1024 * 1024; //文件大小是否大于10MB
    console.log(file);
    if (file && fileSize <= shardSize) {
      //<=10MB时直接下载
      this.downloadisLoading = true;
      // this.setFileLoading()
      this.http
        .get(`/api/Objects/PlanPlatform/${file.objectName}`, {
          responseType: "blob",
        })
        .subscribe((data) => {
          console.log(data);
          let url = window.URL.createObjectURL(new Blob([data])); //createObjectURL创建一个下载Blob的url地址
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;

          let suffix = file.objectName.substring(
            file.objectName.lastIndexOf(".") + 1,
            file.objectName.length
          );
          link.setAttribute(
            "download",
            file.fileName
              ? file.fileName
              : this.unitdata.unitname +
                  "-" +
                  this.uploadFileLonging.name +
                  "." +
                  suffix
          );
          document.body.appendChild(link);
          link.click();
          this.downloadisLoading = false;
          // this.setFileLoading()
        });
    } else if (file && fileSize > shardSize) {
      //>10MB时分块下载
      this.blockingDownload(); //分段下载
      this.downloadisLoading = true;
      // this.setFileLoading()
    }
  }

  //分段下载并合并
  async blockingDownload() {
    let file = this.download;
    let fileSize = file.fileLength; //下载文件的总大小
    let shardSize = 3 * 1024 * 1024; //3MB一个分片
    let allSlice = Math.ceil(fileSize / shardSize); //总文件/3MB===共分多少段
    let allFile: any = []; //所有的file分段

    for (let i = 0; i < allSlice; i++) {
      let start = i * shardSize; //每次下载文件开始位置
      let end = Math.min(fileSize, start + shardSize - 1); //每次下载文件结束为止

      let result = await new Promise((result, reject) => {
        this.http
          .get(`/api/Objects/PlanPlatform/${file.objectName}`, {
            headers: { range: `bytes= ${start}-${end}` },
            responseType: "blob",
          })
          .subscribe((data) => {
            result(data);
          });
      });
      allFile.push(result);
      this.downloadProgress = Number((i / allSlice).toFixed(2)) * 100;

      if (allFile.length === allSlice) {
        //合并文件输出给浏览器
        let url = window.URL.createObjectURL(new Blob(allFile)); //createObjectURL创建一个下载Blob的url地址
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        let suffix = file.objectName.substring(
          file.objectName.lastIndexOf(".") + 1,
          file.objectName.length
        );
        link.setAttribute(
          "download",
          file.fileName
            ? file.fileName
            : this.unitdata.unitname +
                "-" +
                this.uploadFileLonging.name +
                "." +
                suffix
        );
        document.body.appendChild(link);
        link.click();
        // this.downloadProgress = 0
        this.downloadisLoading = false;
        // this.setFileLoading()
      }
    } //for循环
  }

  //取消分块下载
  cancelDowload() {}

  //封装函数设置当前文件loading状态
  setFileLoading() {
    // let id = this.selectDownloadFile.id
    // this.CADList.forEach(element => {
    //   if (element.id === id) { element.loading = !element.loading }
    // });
  }

  //新建预案弹出框
  addplan() {
    const dialogRef = this.dialog.open(AddPlanone, {
      width: "585px",
      height: "430px",
      data: {
        companyId: this.companyId,
        unitType: this.unitdata.unittype,
        unitName: this.unitdata.unitname,
      },
      disableClose: true,
    });
    dialogRef.afterClosed().subscribe((data) => {
      if (data) {
        // this.route.snapshot.queryParams.id = data.planId
        this.planId = data.planId;
        this.getAllPlanComponents();
        if (data.planMode == 2) {
          //如果添加方式为在线编辑
          sessionStorage.setItem("planId", data.id);
          sessionStorage.setItem("companyId", this.companyId);
          sessionStorage.setItem("buildingTypeId", this.unittypeId);
          sessionStorage.setItem("editable", "1");
          let companyId = sessionStorage.getItem("companyId");
          window.open(
            `/keyUnit/editunitinfo?id=${companyId}&orName=${this.route.snapshot.queryParams.orName}&orId=${this.route.snapshot.queryParams.orId}`
          );
        }
      }
    });
  }
  //上传word转在线编制
  spinner = false; //圈圈是否存在
  async upzhuanMb(element) {
    this.spinner = true;
    const config = new MatSnackBarConfig();
    config.verticalPosition = "top";
    config.duration = 3000;
    let objectName; //预案文件名称
    let formData = new FormData();
    //模板导入接口传参
    let type =
      this.unitdata.unittype == "高层建筑"
        ? 1
        : this.unitdata.unittype == "居民小区"
        ? 2
        : this.unitdata.unittype == "厂房"
        ? 3
        : this.unitdata.unittype == "商市场" ||
          this.unitdata.unittype == "医院" ||
          this.unitdata.unittype == "学校" ||
          this.unitdata.unittype == "宾馆" ||
          this.unitdata.unittype == "娱乐场所" ||
          this.unitdata.unittype == "餐饮业" ||
          this.unitdata.unittype == "影剧院" ||
          this.unitdata.unittype == "展览建筑" ||
          this.unitdata.unittype == "养老院" ||
          this.unitdata.unittype == "会议中心" ||
          this.unitdata.unittype == "古建筑" ||
          this.unitdata.unittype == "多层"
        ? 4
        : this.unitdata.unittype == "储罐类"
        ? "StorageTankFivePlan"
        : this.unitdata.unittype == "化工生产"
        ? "ChemicalProductionFivePlan"
        : this.unitdata.unittype == "轨道交通"
        ? "MetroFivePlan"
        : this.unitdata.unittype == "地下建筑"
        ? "UndergroundBuildingFivePlan"
        : this.unitdata.unittype == "农村"
        ? "CountrysideFivePlan"
        : "";

    let blob = [];
    /* 
    调用下载接口获取文件流,并赋值给blob
     */
    let fileRuquest = await new Promise((resolve, reject) => {
      this.http
        .get(`/api/ObjectMetadata/PlanPlatform/` + element.attachmentUrls[0])
        .subscribe((obdata: any) => {
          objectName = obdata.objectName;
          this.http
            .get(`/api/Objects/PlanPlatform/${objectName}`, {
              responseType: "blob",
            })
            .subscribe((blobdata) => {
              resolve(blobdata);
            });
        });
    });
    blob.push(fileRuquest); //接收返回的blob类型数据
    let file = new File(blob, objectName); //转化为file类型
    formData.append("file", file);
    let pData; //接受返回的模板信息数据
    /* 
    调用模板导入接口,获取在线编制的json,并赋值给pData
     */
    let pRequest = await new Promise((resolve, rejest) => {
      this.http
        .post(`/api/OfficeExtract/ExtractWordPlan?type=${type}`, formData)
        .subscribe(
          (data: any) => {
            resolve(data);
          },
          (err) => {
            this.spinner = false;
            this.snackBar.open(
              "解析失败,请确定好格式再重新上传!",
              "确定",
              config
            );
          }
        );
    });
    pData = pRequest;
    /* 调用新建预案接口,新建一条新的预案,并跳转新建在线编制页面 */
    let body = {
      name: element.name,
      planType: element.planType,
      planMode: 2,
      planLevel: element.planLevel,
      planCategory: element.planCategory,
      webTextData: JSON.stringify(pData),
    };
    let planData;
    let newyuan = await new Promise((resolve, reject) => {
      this.http
        .post("/api/PlanComponents", body, {
          params: {
            companyId: this.route.snapshot.queryParams.unitId,
          },
        })
        .subscribe((plandata) => {
          resolve(plandata);
        });
    });
    planData = newyuan;
    window.open(
      `/planManagement/createplanonlinefive?navIsOpen=false&companyId=${this.route.snapshot.queryParams.unitId}&planName=${planData.name}&unitName=${this.unitdata.unitname}&planCategory=${planData.planCategory}&planId=${planData.id}&&wordChange=true`
    );
    this.getAllPlanComponents();
    this.spinner = false;
  }
}

//新建预案弹出框
@Component({
  selector: "AddPlanone",
  templateUrl: "./AddPlanone.html",
  styleUrls: ["./entry-plan-look.component.scss"],
})
export class AddPlanone {
  isLinear = true; //是否为线性步进器
  firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;
  constructor(
    private _formBuilder: FormBuilder,
    private http: HttpClient,
    public dialogRef: MatDialogRef<AddPlanone>,
    @Inject(MAT_DIALOG_DATA) public data,
    public snackBar: MatSnackBar,
    private tree: TreeService
  ) {}

  ngOnInit(): void {
    this.levels = sessionStorage.getItem("level");
    this.firstFormGroup = this._formBuilder.group({
      firstCtrlone: ["", Validators.required],
      firstCtrltwo: ["", Validators.required],
      firstCtrlthree: ["", Validators.required],
    });
    this.secondFormGroup = this._formBuilder.group({
      secondCtrl: ["", Validators.required],
    });
  }
  onNoClick(): void {
    this.dialogRef.close();
  }
  levels; //
  isup: boolean = false; //上传input框是否显示
  isweb: boolean = false; //web输入框是否显示
  isinput: boolean = false; //编制按钮是否显示
  defaultisshow = "0"; //默认显示上传input框
  pswShow = false; //是否为全景图选项默认不显示
  psw; //是否为全景图
  cadPlan; //是否为卡片预案
  //选择radio
  selectradio(e) {
    if (e.value == "1") {
      //如果点击本地上传
      this.isup = true;
      this.isinput = false;
      this.isweb = false;
      this.webaddress = "";
    }
    if (e.value == "4") {
      //如果点击导入word文档
      this.isinput = true;
      this.isup = false;
      this.isweb = false;
      this.webaddress = "";
    }
    if (e.value == "2") {
      //如果点击在线编辑
      this.isinput = false;
      this.isup = false;
      this.isweb = false;
      this.webaddress = "";
    }
    if (e.value == "3") {
      //如果点击输入网址
      this.isweb = true;
      this.isup = false;
      this.isinput = false;
      this.webaddress = "";
    }
  }
  file2: any = null; //导入的文件
  webaddress: any = ""; //输入的网页地址

  //上传文件↓
  file: any; //上传的文件
  fileName: any; //上传文件name
  uploadisLoading: boolean = false; //进度条loading加载
  uploadProgress: number = 0; //进度条进度
  objectName: any; //上传对象名
  uploadId: any; //上传分块上传事件编号
  //上传文件input
  filechange(e) {
    this.psw = false;
    this.file = e.target.files[0] || null; //上传的文件
    if (
      this.selectedPLanType == "4" &&
      this.file.type != null &&
      this.file.type != undefined
    ) {
      if (this.file.type == "image/png" || this.file.type == "image/jpeg") {
        this.pswShow = true;
      } else {
        this.pswShow = false;
      }
    } else {
      this.pswShow = false;
    }
  }

  //上传文件
  startUploading(planType) {
    let file = this.file || null; //获取上传的文件
    let fileSize = file.size || null; //上传文件的总大小
    let shardSize = 5 * 1024 * 1024; //5MB一个分片

    if (file && fileSize <= shardSize) {
      //上传文件<=5MB时
      let formData = new FormData();
      formData.append("file", file);
      this.http
        .post(
          this.psw
            ? "/api/Objects/PlanPlatform/psw"
            : `/api/Objects/PlanPlatform/${this.data.companyId}/2D`,
          formData
        )
        .subscribe((data: any) => {
          this.objectName = data.objectName;
          const config = new MatSnackBarConfig();
          config.verticalPosition = "top";
          config.duration = 3000;
          this.snackBar.open("上传成功!", "确定", config);
          this.uploadover = true;

          let level = sessionStorage.getItem("level");
          // console.log(level)
          let PlanLevel;
          if (level == "0") {
            PlanLevel = 1;
          }
          if (level == "1") {
            PlanLevel = 2;
          }
          if (level == "2") {
            PlanLevel = 4;
          }
          if (level == "3") {
            PlanLevel = 8;
          }
          let uploadUrl;
          if (planType == "非二维") {
            uploadUrl = "/api/PlanComponents";
          } else {
            uploadUrl = "/api/PlanComponents2D";
          }
          if (this.uploadover) {
            this.http
              .post(
                uploadUrl,
                {
                  id: "",
                  name: this.selectedPLanName,
                  planType: Number(this.selectedPLanType),
                  planMode: Number(this.defaultisshow),
                  planLevel: PlanLevel,
                  planCategory: Number(this.selectedPLanLevel),
                  url: "",
                  attachmentUrls: [`${this.objectName}`],
                },
                {
                  params: {
                    companyId: this.data.companyId,
                  },
                }
              )
              .subscribe((data) => {
                this.dialogRef.close(data);
              });
          } else {
            console.log("上传出错");
          }
        });
    } else if (file && fileSize > shardSize) {
      //上传文件>5MB时,分块上传
      let data = { filename: file.name };
      this.uploadisLoading = true;
      this.http
        .post(
          this.psw
            ? "/api/NewMultipartUpload/PlanPlatform/psw"
            : `/api/NewMultipartUpload/PlanPlatform/${this.data.companyId}/2D`,
          {},
          { params: data }
        )
        .subscribe((data: any) => {
          //初始化分段上传
          this.objectName = data.objectName;
          this.uploadId = data.uploadId;
          this.subsectionUploading(planType);
        });
    }
  }

  PartNumberETag: any = []; //每次返回需要保存的信息
  //开始分段上传
  async subsectionUploading(planType) {
    let file = this.file || null; //获取上传的文件
    let fileSize = file.size || null; //上传文件的总大小
    let shardSize = 5 * 1024 * 1024; //5MB一个分片
    let allSlice = Math.ceil(fileSize / shardSize); //总文件/5MB===共分多少段 向上取整

    for (let i = 0; i < allSlice; i++) {
      //循环分段上传
      let start = i * shardSize; //切割文件开始位置
      let end = Math.min(fileSize, start + shardSize); //切割文件结束位置 (对比取小数)
      let formData = new FormData();
      formData.append("file", file.slice(start, end));

      //同步写法实现异步调用
      let result = await new Promise((resolve, reject) => {
        // await 需要后面返回一个 promise 对象
        this.http
          .post(
            `/api/MultipartUpload/PlanPlatform/${this.objectName}?uploadId=${
              this.uploadId
            }&partNumber=${i + 1}`,
            formData
          )
          .subscribe((data: any) => {
            let msg = {
              partNumber: data.partNumber || null,
              eTag: data.eTag || null,
            };
            resolve(msg); // 调用 promise 内置方法处理成功
          });
      });
      this.PartNumberETag.push(result);
      this.uploadProgress = Number((i / allSlice).toFixed(2)) * 100;

      if (this.PartNumberETag.length === allSlice) {
        this.uploadProgress = 100;
        this.endUploading(planType);
      }
    } //for循环
  }
  uploadover: any = false; //上传完成之后提示
  //完成分块上传
  endUploading(planType) {
    let data = this.PartNumberETag;
    let paramsData = { uploadId: this.uploadId };
    this.http
      .post(
        `/api/CompleteMultipartUpload/PlanPlatform/${this.objectName}`,
        data,
        { params: paramsData }
      )
      .subscribe((data) => {
        const config = new MatSnackBarConfig();
        config.verticalPosition = "top";
        config.duration = 3000;
        this.snackBar.open("上传成功!", "确定", config);
        this.uploadProgress = 0;
        this.uploadisLoading = false;
        this.PartNumberETag = []; //清空保存返回的信息
        this.uploadover = true;
        let level = sessionStorage.getItem("level");
        // console.log(level)
        let PlanLevel;
        if (level == "0") {
          PlanLevel = 1;
        }
        if (level == "1") {
          PlanLevel = 2;
        }
        if (level == "2") {
          PlanLevel = 4;
        }
        if (level == "3") {
          PlanLevel = 8;
        }
        let uploadUrl;
        if (planType == "非二维") {
          uploadUrl = "/api/PlanComponents";
        } else {
          uploadUrl = "/api/PlanComponents2D";
        }
        if (this.uploadover) {
          //如果上次成功了才创建
          this.http
            .post(
              uploadUrl,
              {
                id: "",
                name: this.selectedPLanName,
                planType: Number(this.selectedPLanType),
                planMode: Number(this.defaultisshow),
                planLevel: PlanLevel,
                planCategory: Number(this.selectedPLanLevel),
                url: "",
                attachmentUrls: [`${this.objectName}`],
              },
              {
                params: {
                  companyId: this.data.companyId,
                },
              }
            )
            .subscribe((data) => {
              this.dialogRef.close(data);
            });
        } else {
          console.log("上传出错!");
        }
      });
  }

  //取消分块上传
  cancel() {
    this.http
      .delete(
        `/api/MultipartUpload/PlanPlatform/${this.objectName}?uploadId=${this.uploadId}`
      )
      .subscribe((data) => {
        this.uploadProgress = 0;
        this.uploadisLoading = false;
        (<HTMLInputElement>document.getElementById("uploadFile")).value = null;
        this.PartNumberETag = []; //清空保存返回的信息
        const config = new MatSnackBarConfig();
        config.verticalPosition = "top";
        config.duration = 3000;
        this.snackBar.open("取消上传成功!", "确定", config);
        this.uploadover = false;
        this.file = null;
      });
  }

  //导入word文件
  fileInput(e) {
    this.file2 = e.target.files[0];
  }
  //点击下一步
  selectedPLanType: any; //所选预案类型
  selectedPLanName: any; //所选预案名称
  selectedPLanLevel: any; //所选预案级别
  localup: boolean = false; //本地上传
  inputword: boolean = false; //导入文档
  onlineedit: boolean = false; //在线编辑
  website: boolean = false; //网页地址
  inputNew: boolean = false; //自定义编辑
  next(formdata) {
    this.psw = false;
    this.selectedPLanName = formdata.value.firstCtrlone;
    this.selectedPLanType = formdata.value.firstCtrltwo;
    this.selectedPLanLevel = formdata.value.firstCtrlthree;
    if (
      formdata.value.firstCtrltwo == "16" &&
      formdata.value.firstCtrlthree == "4"
    ) {
      //如果是文本预案
      this.localup = true;
      this.inputword = false;
      this.onlineedit = false;
      this.website = false;
    }
    if (formdata.value.firstCtrltwo == "16") {
      //&& formdata.value.firstCtrlthree != '4'
      this.localup = true;
      this.inputword = true;
      this.onlineedit = false;
      this.website = false;
      this.inputNew = true;
    }
    if (
      formdata.value.firstCtrltwo == "16" &&
      formdata.value.firstCtrlthree != "4"
    ) {
      //&& formdata.value.firstCtrlthree != '4'
      this.localup = true;
      this.inputword = true;
      this.inputNew = true;
      this.onlineedit = false;
      this.website = false;
    }
    if (formdata.value.firstCtrltwo == "1") {
      //如果是2D预案
      this.localup = false;
      this.inputword = false;
      this.onlineedit = true;
      this.website = true;
      this.inputNew = false;
    }
    if (
      formdata.value.firstCtrltwo == "2" ||
      formdata.value.firstCtrltwo == "4"
    ) {
      this.localup = true;
      this.inputword = false;
      this.inputNew = false;
      this.onlineedit = false;
      this.website = true;
      this.pswShow = true;
    }
    if (
      this.selectedPLanType == "4" &&
      this.file != undefined &&
      this.file.type != null
    ) {
      if (this.file.type == "image/png" || this.file.type == "image/jpeg") {
        this.pswShow = true;
        this.website = false;
      } else {
        this.pswShow = false;
      }
    } else {
      this.pswShow = false;
    }
  }
  setttt() {
    this.pswShow = false;
    this.psw = false;
  }
  closediv() {
    //console.log(this.file)
    if (this.file != undefined) {
      this.cancel();
    }

    this.dialogRef.close();
  }
  //文本预案在线编制跳转
  newleftTabledata;
  planData;
  createWord(haveNew) {
    const config = new MatSnackBarConfig();
    config.verticalPosition = "top";
    config.duration = 3000;
    let level = sessionStorage.getItem("level");
    // console.log(level)
    let PlanLevel;
    if (level == "0") {
      PlanLevel = 1;
    }
    if (level == "1") {
      PlanLevel = 2;
    }
    if (level == "2") {
      PlanLevel = 4;
    }
    if (level == "3") {
      PlanLevel = 8;
    }
    this.http.get("/api/PlanTemplate").subscribe((data: any) => {
      this.newleftTabledata = data;
      this.newleftTabledata.forEach((value, index, array) => {
        value.data = JSON.parse(value.data);
      });
      this.http.get("/api/BuildingTypes").subscribe((buildData: any) => {
        this.newleftTabledata.forEach((value, index, array) => {
          buildData.forEach((element, i, buildArray) => {
            if (value.buildingTypeId == element.id) {
              array[index].unitname = buildArray[i].name;
              array[index].facilityCategoryId =
                buildArray[i].facilityCategoryId;
            }
          });
        });
        let open = this.newleftTabledata.filter((value, index, array) => {
          return (
            value.unitname == this.data.unitType &&
            value.planCategory == this.selectedPLanLevel
          );
        });
        if (haveNew == true) {
          this.http
            .post(
              "/api/PlanComponents",
              {
                id: "",
                name: this.selectedPLanName,
                planType: Number(this.selectedPLanType),
                planMode: Number(this.defaultisshow),
                planLevel: PlanLevel,
                planCategory: Number(this.selectedPLanLevel),
                url: "",
                //attachmentUrls: [`${this.objectName}`]
              },
              {
                params: {
                  companyId: this.data.companyId,
                },
              }
            )
            .subscribe((plandata) => {
              this.planData = plandata;
              this.dialogRef.close(plandata);
              //console.log(plandata)
              window.open(
                `/planManagement/createplanonlinefive?navIsOpen=false&companyId=${this.data.companyId}&planName=${this.planData.name}&unitName=${this.data.unitName}&planCategory=${this.selectedPLanLevel}&planId=${this.planData.id}&haveNew=${haveNew}&planMode=${this.defaultisshow}`
              );
            });
        } else {
          if (open.length > 0) {
            this.http
              .post(
                "/api/PlanComponents",
                {
                  id: "",
                  name: this.selectedPLanName,
                  planType: Number(this.selectedPLanType),
                  planMode: Number(this.defaultisshow),
                  planLevel: PlanLevel,
                  planCategory: Number(this.selectedPLanLevel),
                  url: "",
                  //attachmentUrls: [`${this.objectName}`]
                },
                {
                  params: {
                    companyId: this.data.companyId,
                  },
                }
              )
              .subscribe((plandata) => {
                this.planData = plandata;
                this.dialogRef.close(plandata);
                //console.log(plandata)
                window.open(
                  `/planManagement/createplanonlinefive?navIsOpen=false&companyId=${this.data.companyId}&planName=${this.planData.name}&unitName=${this.data.unitName}&planCategory=${this.selectedPLanLevel}&planId=${this.planData.id}&haveNew=${haveNew}`
                );
              });
          } else {
            this.snackBar.open("请先创建模板!", "确定", config);
          }
        }
      });
    });
    //window.open('')
  }

  // 提交创建
  onSubmit(value) {
    let level = sessionStorage.getItem("level");
    // console.log(level)
    let PlanLevel;
    if (level == "0") {
      PlanLevel = 1;
    }
    if (level == "1") {
      PlanLevel = 2;
    }
    if (level == "2") {
      PlanLevel = 4;
    }
    if (level == "3") {
      PlanLevel = 8;
    }
    if (this.selectedPLanType != "1") {
      //如果创建的不是二维预案
      if (this.defaultisshow == "1" && this.file == null) {
        //如果是本地上传
        const config = new MatSnackBarConfig();
        config.verticalPosition = "top";
        config.duration = 3000;
        this.snackBar.open("请先上传文件", "确定", config);
      }
      if (this.defaultisshow == "1" && this.file) {
        //如果是本地上传并且有文件
        //先上传成功
        this.startUploading("非二维");

        //再创建预案
        // this.http.post("/api/PlanComponents",{
        //   id: "",
        //   name: this.selectedPLanName,
        //   planType:Number(this.selectedPLanType),
        //   planMode: Number(this.defaultisshow),
        //   planLevel: PlanLevel,
        //   url: "",
        //   attachmentUrls: [`${this.objectName}`]
        // },{params:{
        //   companyId : this.data.companyId
        // }}).subscribe(data=>{
        //   this.dialogRef.close(data);
        // })
      }

      if (this.defaultisshow == "2") {
        //如果是导入则很复杂
        const config = new MatSnackBarConfig();
        config.verticalPosition = "top";
        config.duration = 3000;
        //this.snackBar.open('暂不支持导入','确定',config);
        this.createWord(false);
      }
      if (this.defaultisshow == "4") {
        this.createWord(true);
      }
      if (
        this.defaultisshow == "3" &&
        (this.webaddress == "" || this.webaddress == null)
      ) {
        //如果是填写网址
        const config = new MatSnackBarConfig();
        config.verticalPosition = "top";
        config.duration = 3000;
        this.snackBar.open("请先输入网址", "确定", config);
      }
      if (this.defaultisshow == "3" && this.webaddress) {
        //如果是填写网址
        var reg = new RegExp(
          "(http|https|app1|app2)://([w.!@#$%^&*()_+-=])*s*"
        );
        if (reg.test(this.webaddress)) {
          let body = {
            id: "",
            name: this.selectedPLanName,
            planType: Number(this.selectedPLanType),
            planMode: Number(this.defaultisshow),
            planCategory: Number(this.selectedPLanLevel),
            planLevel: PlanLevel,
            url: this.webaddress,
            attachmentUrls: null,
          };
          //console.log(body)
          this.http
            .post("/api/PlanComponents", body, {
              params: {
                companyId: this.data.companyId,
              },
            })
            .subscribe((data) => {
              this.dialogRef.close(data);
            });
        } else {
          const config = new MatSnackBarConfig();
          config.verticalPosition = "top";
          config.duration = 3000;
          this.snackBar.open(
            "请填写正确网址格式,需以http://或者https://开头的正确网址",
            "确定",
            config
          );
        }
      }
    } else {
      //如果创建的是二维预案
      if (this.defaultisshow == "1" && this.file == null) {
        //如果是本地上传
        const config = new MatSnackBarConfig();
        config.verticalPosition = "top";
        config.duration = 3000;
        this.snackBar.open("请先上传文件", "确定", config);
      }
      if (this.defaultisshow == "1" && this.file) {
        this.startUploading("二维");
        // let body  = {
        //   id: "",
        //   name: this.selectedPLanName,
        //   planType:Number(this.selectedPLanType),
        //   planMode: Number(this.defaultisshow),
        //   planLevel: PlanLevel,
        //   url: "",
        //   attachmentUrls: [`${this.objectName}`]
        // }
        // this.http.post("/api/PlanComponents2D",body,{params:{
        //   companyId : this.data.companyId
        // }}).subscribe(data=>{
        //   // console.log("创建成功")
        //   this.dialogRef.close(data);
        // })
      }
      if (this.defaultisshow == "2") {
        //如果是在线编辑------>跳转编制工具
        let body = {
          id: "",
          name: this.selectedPLanName,
          planType: Number(this.selectedPLanType),
          planMode: Number(this.defaultisshow),
          planLevel: PlanLevel,
          planCategory: Number(this.selectedPLanLevel),
          url: "",
          attachmentUrls: null,
        };
        this.http
          .post("/api/PlanComponents2D", body, {
            params: {
              companyId: this.data.companyId,
            },
          })
          .subscribe((data) => {
            // console.log("创建成功")
            this.dialogRef.close(data);
          });
      }
      if (
        this.defaultisshow == "3" &&
        (this.webaddress == "" || this.webaddress == null)
      ) {
        //如果是填写网址
        const config = new MatSnackBarConfig();
        config.verticalPosition = "top";
        config.duration = 3000;
        this.snackBar.open("请先输入网址", "确定", config);
      }
      if (this.defaultisshow == "3" && this.webaddress) {
        //如果是填写网址

        var reg = new RegExp("(http|https)://([w.!@#$%^&*()_+-=])*s*");
        if (reg.test(this.webaddress)) {
          let body = {
            id: "",
            name: this.selectedPLanName,
            planType: Number(this.selectedPLanType),
            planMode: Number(this.defaultisshow),
            planCategory: Number(this.selectedPLanLevel),
            planLevel: PlanLevel,
            url: this.webaddress,
            attachmentUrls: null,
          };
          //console.log(body)
          this.http
            .post("/api/PlanComponents2D", body, {
              params: {
                companyId: this.data.companyId,
              },
            })
            .subscribe((data) => {
              // console.log("创建成功")
              this.dialogRef.close(data);
            });
        } else {
          const config = new MatSnackBarConfig();
          config.verticalPosition = "top";
          config.duration = 3000;
          this.snackBar.open(
            "请填写正确网址格式,需以http://或者https://开头的正确网址",
            "确定",
            config
          );
        }
      }
    }
  }
  onSubmit2(value) {
    // console.log(this.webaddress)
    var reg = new RegExp("(http|https)://([w.!@#$%^&*()_+-=])*s*");
    //console.log(reg.test(this.webaddress))
  }
}

//下载文件弹出框
@Component({
  selector: "downloadfile",
  templateUrl: "./downloadFile.html",
  styleUrls: ["./entry-plan-look.component.scss"],
})
export class DownloadFile {
  constructor(
    private http: HttpClient,
    public dialogRef: MatDialogRef<DownloadFile>,
    @Inject(MAT_DIALOG_DATA) public data,
    public snackBar: MatSnackBar
  ) {}
  fileUrls: any; //当前预案附件地址
  fileDatas: any = [];
  selectedFileIndex: any = 0;
  selectedFileData: any;

  name2: any; //如果真实姓名为空时
  ngOnInit(): void {
    this.name2 = this.data.element.name;
    this.fileUrls = this.data.fileUrls;
    this.fileUrls.forEach((item) => {
      this.http
        .get("/api/ObjectMetadata/PlanPlatform/" + item)
        .subscribe((data: any) => {
          data.filePige = (data.fileLength / (1024 * 1024)).toFixed(2);
          this.fileDatas.push(data);
          this.selectedFileData = data;
        });
    });
  }
  onNoClick(): void {
    this.dialogRef.close();
  }

  confirm() {
    this.dialogRef.close(this.selectedFileData);
  }

  //点击想要下载的文件
  addurl(item, key) {
    // console.log(item,key)
    this.selectedFileIndex = key;
    this.selectedFileData = item;
  }
}

//审批结果弹出框
@Component({
  selector: "auditresult",
  templateUrl: "./auditresult.html",
  styleUrls: ["./entry-plan-look.component.scss"],
})
export class AuditResult {
  constructor(
    private http: HttpClient,
    public dialogRef: MatDialogRef<AuditResult>,
    @Inject(MAT_DIALOG_DATA) public data,
    public snackBar: MatSnackBar
  ) {}

  planName: any = this.data.element.name;
  commitTime: any = this.data.element.committedTime;
  commitOrganizationName: any = this.data.element.committerOrganizationName;

  auditOrganizationName: any = this.data.element.auditorOrganizationName;
  auditResult: any = this.data.element.auditStatus;
  auditOpinion: any = this.data.element.auditOpinion;
  ngOnInit(): void {}
  onNoClick(): void {
    this.dialogRef.close();
  }
}

//改名弹出框
@Component({
  selector: "changename",
  templateUrl: "./changename.html",
  styleUrls: ["./entry-plan-look.component.scss"],
})
export class ChangeName {
  constructor(
    private http: HttpClient,
    public dialogRef: MatDialogRef<ChangeName>,
    @Inject(MAT_DIALOG_DATA) public data,
    public snackBar: MatSnackBar
  ) {}
  planName: any; //预案名称
  ngOnInit(): void {
    this.planName = this.data.element.name;
  }
  onNoClick(): void {
    this.dialogRef.close();
  }
  onSubmit(value) {
    let headers = new HttpHeaders({
      "Content-Type": "text/json",
    });
    let options = {
      headers,
    };
    let body = {
      name: value.name,
    };
    let body2d = JSON.stringify(value.name);
    if (this.data.element.planType == 1) {
      //如果是二维预案
      this.http
        .put(`/api/PlanComponents2D/${this.data.element.id}`, body2d, options)
        .subscribe((data) => {
          this.dialogRef.close("success");
        });
    } else {
      this.http
        .put(`/api/PlanComponents/${this.data.element.id}`, body, options)
        .subscribe((data) => {
          this.dialogRef.close("success");
        });
    }
  }
}

//全景图弹出框
@Component({
  selector: "PsViewer",
  templateUrl: "./Photo-Sphere-Viewer.html",
  styleUrls: ["./entry-plan-look.component.scss"],
})
export class PsViewer {
  constructor(
    private router: Router,
    private http: HttpClient,
    public dialog: MatDialog,
    public snackBar: MatSnackBar,
    public dialogRef: MatDialogRef<PsViewer>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {}
  ngOnInit(): void {
    // console.log(this.data)
    const viewer = new Viewer({
      container: document.querySelector("#viewer"),
      panorama: "/api/Objects/PlanPlatform/" + this.data,
    });
  }
}

//普通图片弹窗
@Component({
  selector: "imgdetails",
  templateUrl: "./previewImg.html",
  styleUrls: ["./entry-plan-look.component.scss"],
})
export class ImgDetails {
  constructor(
    private http: HttpClient,
    public dialog: MatDialog,
    public dialogRef: MatDialogRef<ImgDetails>,
    @Inject(MAT_DIALOG_DATA) public data
  ) {}
  testSwiper: Swiper;

  ngOnInit(): void {
    //console.log(this.data)
    this.allImages = [];
    this.data.forEach((element) => {
      element = `/api/Objects/PlanPlatform/${element}?x-oss-process=image/auto-orient,1`;
      this.allImages.push(element);
    });
    //this.allImages.push(`${this.data.attachmentUrls[0]}?x-oss-process=image/auto-orient,1`)
  }

  ngAfterViewInit() {
    this.testSwiper = new Swiper(".swiper-container", {
      lazy: true,
      direction: "horizontal",
      loop: false,

      // 如果需要前进后退按钮
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
    });
  }

  allImages: any; //展示所有的图片
  rotationAngle: number = 0; //旋转角度

  //旋转图片
  rotate() {
    this.rotationAngle = this.rotationAngle + 90;
    if (this.rotationAngle === 360) {
      this.rotationAngle = 0;
    }
  }
}

//修改三维预案地址
@Component({
  selector: "changename",
  templateUrl: "./changeurl.html",
  styleUrls: ["./entry-plan-look.component.scss"],
})
export class ChangeUrl {
  constructor(
    private http: HttpClient,
    public dialogRef: MatDialogRef<ChangeUrl>,
    @Inject(MAT_DIALOG_DATA) public data,
    public snackBar: MatSnackBar
  ) {}
  planUrl: any; //预案路径
  updata; //修改后的data
  ngOnInit(): void {
    this.planUrl = this.data.element.url;
  }
  onNoClick(): void {
    this.dialogRef.close();
  }
  onSubmit(value) {
    console.log(value);
    let headers = new HttpHeaders({
      "Content-Type": "text/json",
    });
    let options = {
      headers,
    };
    let body = {
      url: value.name,
      auditStatus: 8,
    };
    this.http
      .put(`/api/PlanComponents/${this.data.element.id}`, body, options)
      .subscribe((data) => {
        console.log(data);
        this.updata = data;
        this.dialogRef.close("success");
        sessionStorage.setItem("url", this.updata.url);
        if ((this.updata.url as string).includes("gis/threeDimensionalHome")) {
          //三维预案
          window.open(
            `${this.updata.url}?unitId=${this.updata.companyId}&unitName=${this.updata.name}&editMode=true`
          );
        } else {
          window.open(`/planManagement/webLook`);
        }
      });
  }
}

//编辑上传文件
@Component({
  selector: "editUpload",
  templateUrl: "./upLoad.html",
  styleUrls: ["./entry-plan-look.component.scss"],
})
export class editUpload {
  constructor(
    private http: HttpClient,
    public dialogRef: MatDialogRef<editUpload>,
    @Inject(MAT_DIALOG_DATA) public data,
    public snackBar: MatSnackBar
  ) {}
  planName: any; //预案名称
  ngOnInit(): void {
    //console.log(this.data)
  }
  onNoClick(): void {
    this.dialogRef.close();
  }
  //上传文件↓
  file: any; //上传的文件
  fileName: any; //上传文件name
  uploadisLoading: boolean = false; //进度条loading加载
  uploadProgress: number = 0; //进度条进度
  objectName: any; //上传对象名
  uploadId: any; //上传分块上传事件编号
  lastyuanData; //之前的预案数据
  //上传
  upload() {
    document.getElementById("up").click();
  }
  //上传文件input
  filechange(e) {
    this.file = e.target.files[0] || null; //上传的文件
  }
  //上传文件
  startUploading() {
    console.log(this.file);
    let file = this.file || null; //获取上传的文件
    let fileSize = file.size || null; //上传文件的总大小
    let shardSize = 5 * 1024 * 1024; //5MB一个分片
    if (this.file != undefined) {
      if (file && fileSize <= shardSize) {
        //上传文件<=5MB时
        let formData = new FormData();
        formData.append("file", file);
        this.http
          .post(`/api/Objects/PlanPlatform/${this.data.companyId}/2D`, formData)
          .subscribe((data: any) => {
            this.objectName = data.objectName;
            let headers = new HttpHeaders({
              "Content-Type": "text/json",
            });
            let options = {
              headers,
            };
            this.uploadover = true;
            let level = sessionStorage.getItem("level");
            let PlanLevel;
            if (level == "0") {
              PlanLevel = 1;
            }
            if (level == "1") {
              PlanLevel = 2;
            }
            if (level == "2") {
              PlanLevel = 4;
            }
            if (level == "3") {
              PlanLevel = 8;
            }
            let uploadUrl = "/api/PlanComponents";
            this.http
              .get(`/api/PlanComponents/${this.data.id}`)
              .subscribe((yuandata) => {
                console.log(yuandata);
                this.lastyuanData = yuandata;
                this.lastyuanData.attachmentUrls[0] = this.objectName;
                this.http
                  .put(
                    `/api/PlanComponents/${this.data.id}`,
                    this.lastyuanData,
                    options
                  )
                  .subscribe((data) => {
                    this.dialogRef.close(data);
                  });
              });
          });
      } else if (file && fileSize > shardSize) {
        //上传文件>5MB时,分块上传
        let data = { filename: file.name };
        this.http
          .post(
            `/api/NewMultipartUpload/PlanPlatform/${this.data.companyId}/2D`,
            {},
            { params: data }
          )
          .subscribe((data: any) => {
            //初始化分段上传
            this.objectName = data.objectName;
            this.uploadId = data.uploadId;
            this.uploadisLoading = true;
            this.subsectionUploading();
          });
      }
    } else {
      const config = new MatSnackBarConfig();
      config.verticalPosition = "top";
      config.duration = 3000;
      this.snackBar.open("请选择文件!", "确定", config);
    }
  }

  PartNumberETag: any = []; //每次返回需要保存的信息
  //开始分段上传
  async subsectionUploading() {
    let file = this.file || null; //获取上传的文件
    let fileSize = file.size || null; //上传文件的总大小
    let shardSize = 5 * 1024 * 1024; //5MB一个分片
    let allSlice = Math.ceil(fileSize / shardSize); //总文件/5MB===共分多少段 向上取整

    for (let i = 0; i < allSlice; i++) {
      //循环分段上传
      let start = i * shardSize; //切割文件开始位置
      let end = Math.min(fileSize, start + shardSize); //切割文件结束位置 (对比取小数)
      let formData = new FormData();
      formData.append("file", file.slice(start, end));

      //同步写法实现异步调用
      let result = await new Promise((resolve, reject) => {
        // await 需要后面返回一个 promise 对象
        this.http
          .post(
            `/api/MultipartUpload/PlanPlatform/${this.objectName}?uploadId=${
              this.uploadId
            }&partNumber=${i + 1}`,
            formData
          )
          .subscribe((data: any) => {
            let msg = {
              partNumber: data.partNumber || null,
              eTag: data.eTag || null,
            };
            resolve(msg); // 调用 promise 内置方法处理成功
          });
      });
      this.PartNumberETag.push(result);
      this.uploadProgress = Number((i / allSlice).toFixed(2)) * 100;

      if (this.PartNumberETag.length === allSlice) {
        this.uploadProgress = 100;
        this.endUploading();
      }
    } //for循环
  }
  uploadover: any = false; //上传完成之后提示
  //完成分块上传
  endUploading() {
    let data = this.PartNumberETag;
    let paramsData = { uploadId: this.uploadId };
    this.http
      .post(
        `/api/CompleteMultipartUpload/PlanPlatform/${this.objectName}`,
        data,
        { params: paramsData }
      )
      .subscribe((data) => {
        const config = new MatSnackBarConfig();
        config.verticalPosition = "top";
        config.duration = 3000;
        this.snackBar.open("上传成功!", "确定", config);
        this.uploadProgress = 0;
        this.uploadisLoading = false;
        this.PartNumberETag = []; //清空保存返回的信息
        this.uploadover = true;
        let level = sessionStorage.getItem("level");
        let headers = new HttpHeaders({
          "Content-Type": "text/json",
        });
        let options = {
          headers,
        };
        // console.log(level)
        let PlanLevel;
        if (level == "0") {
          PlanLevel = 1;
        }
        if (level == "1") {
          PlanLevel = 2;
        }
        if (level == "2") {
          PlanLevel = 4;
        }
        if (level == "3") {
          PlanLevel = 8;
        }
        let uploadUrl = "/api/PlanComponents";

        if (this.uploadover) {
          //如果上次成功了才创建
          this.http
            .get(`/api/PlanComponents/${this.data.id}`)
            .subscribe((yuandata) => {
              console.log(yuandata);
              this.lastyuanData = yuandata;
              this.lastyuanData.attachmentUrls[0] = this.objectName;
              this.http
                .put(
                  `/api/PlanComponents/${this.data.id}`,
                  this.lastyuanData,
                  options
                )
                .subscribe((data) => {
                  this.dialogRef.close(data);
                });
            });
        } else {
          console.log("上传出错!");
        }
      });
  }
}
//在线编制文本预案下载
@Component({
  selector: "wenbenUpload",
  templateUrl: "./upNew.html",
  styleUrls: ["./entry-plan-look.component.scss"],
})
export class wenbenUpload {
  constructor(
    private http: HttpClient,
    public dialogRef: MatDialogRef<wenbenUpload>,
    @Inject(MAT_DIALOG_DATA) public data,
    public snackBar: MatSnackBar,
    private sanitizer: DomSanitizer
  ) {}
  ngOnInit(): void {
    console.log(this.data);
    window.setTimeout(() => {
      this.dialogRef.close();
    }, 45000);
  }
  src = this.sanitizer.bypassSecurityTrustResourceUrl(this.data.src);
}