import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";
import setSeconds from "date-fns/setSeconds";
import setMinutes from "date-fns/setMinutes";
import setHours from "date-fns/setHours";

import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import { NzMessageService } from 'ng-zorro-antd';
@Component({
  selector: "app-questionnaire-management",
  templateUrl: "./questionnaire-management.component.html",
  styleUrls: ["./questionnaire-management.component.less"],
})
export class QuestionnaireManagementComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private router: Router,
    private tool: ToolService,
    private message: NzMessageService
  ) {}

  userInfo: any = JSON.parse(localStorage.getItem("user")) || {}; //登录用户信息
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  tableHeight: number; //表格动态高
  modal: boolean = false; //新增/编辑模态框
  linkModal: boolean = false; //显示生成链接模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: any; //当前操作列
  currentHospital; //当前院区
  timeDefaultValue = setHours(setMinutes(setSeconds(new Date(), 0), 0), 0);

  btnLoading: boolean = false; //提交按钮loading状态

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  nextSchemeName = ""; //下一个开启的方案名称
  modelName = ""; //模态框名称

  ngOnInit() {
    this.currentHospital = this.tool.getCurrentHospital();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.getList(1);
    this.getSurveyTarget();
  }

  // 初始化增删改按钮
  coopBtns: any = {};

  // 获取字典数据-调查目标
  surveyTargets: any[] = [];
  getSurveyTarget() {
    this.mainService
      .getDictionary("list", "survey_target")
      .subscribe((data) => {
        this.surveyTargets = data;
      });
  }

  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      questionnaireManagement: {
        hosId: this.currentHospital.id,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("api", "questionnaireManagement", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }
      });
  }

  // 新增弹框
  addModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modal = true;
    this.copyModel = false;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }
  // 新增/编辑弹框
  timeFlag = ""; //open开启，close关闭
  addLinkModal(data) {
    this.coopId = data;
    this.linkModal = true;
  }
  //关闭定时启用设置日期弹框
  hideLinkModal() {
    this.linkModal = false;
    this.getList(0);
  }
  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      title: [null, [Validators.required]],
      surveyTarget: [null, [Validators.required]],
      surveyDescribe: [null, [Validators.required]],
    });
  }
  // 查看问题
  goToQuestions(data){
    // this.router.navigateByUrl(`/main/questions?id=${data.id}&title=${data.title}&token=${data.token}`);
    this.router.navigateByUrl(`/main/questions?id=${data.id}`);
  }
  // 回收数据
  recovery(data){
    console.log(data);
    this.router.navigateByUrl(`/main/questionnaireAnswer?id=${data.id}`);
  }
  // 发布
  publish(data){
    console.log(data);
    this.showDelModal(data,`您确认【${data.title}】要发布进行调研吗？`,'操作','publish')
  }
  // 链接生成
  generateLink(data){
    console.log(data);
    this.addLinkModal(data);
  }
  // 调研完成
  researchCompleted(data){
    console.log(data);
    this.showDelModal(data,`您确认【${data.title}】已调研完成了吗？`,'操作','complete')
  }
  // 新增/编辑表单提交
  btnLoading1 = false;
  submitForm(noGoTo=false): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      return;
    }
    if(noGoTo){
      this.btnLoading1 = true;
    }else{
      this.btnLoading = true;
    }
    let data:any = {};

    if (this.add) {
      //增加
      data = {
        questionnaireManagement: {
          title: this.validateForm.value.title,
          surveyTarget: { id: this.validateForm.value.surveyTarget },
          surveyDescribe: this.validateForm.value.surveyDescribe,
          hosId: this.currentHospital.id,
        },
      };
    } else {
      //编辑
      data = {
        questionnaireManagement: {
          title: this.validateForm.value.title,
          surveyTarget: { id: this.validateForm.value.surveyTarget },
          surveyDescribe: this.validateForm.value.surveyDescribe,
        },
      };
      data.questionnaireManagement = Object.assign(this.coopId,data.questionnaireManagement);
    }
    // if (this.copyModel) {
    //   //复制
    //   data = {
    //     workScheme: {
    //       name: this.validateForm.value.title,
    //       workType: this.validateForm.value.surveyTarget,
    //       describe: this.validateForm.value.surveyDescribe,
    //       status: 0,
    //       copy: 1,
    //       copySchemeId: this.coopId.id,
    //       hosId: this.currentHospital.id,
    //     },
    //   };
    // }
    this.mainService
      .apiPost(this.add?"addData":'updData', "questionnaireManagement", data)
      .subscribe((result) => {
        if(noGoTo){
          this.btnLoading1 = false;
        }else{
          this.btnLoading = false;
        }
        this.hideAddModal();
        this.initForm();
        if (result.status == 200) {
          // if (this.copyModel) {
          //   //复制
          //   this.listLength++;
          //   this.showPromptModal("复制", true, "");
          //   if (!noGoTo) {
          //     this.router.navigateByUrl(
          //       `/main/quickCombination?id=${result.data.id}&name=${result.data.name}&type=${result.data.workType}`
          //     );
          //   }
          //   return;
          // }
          if (!this.add) {
            //编辑
            this.showPromptModal("编辑", true, "");
            !noGoTo && this.goToQuestions(this.coopId);
            return;
          }
          if (this.add) {
            this.listLength++;
          }
          this.message.create('success', `问卷新增成功`);
          this.goToQuestions(result.data);
        } else {
          let msg = "";
          if (this.add) {
            msg = "新增";
          } else {
            msg = "修改";
          }
          if (this.copyModel) {
            msg = "复制";
          }
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  // 编辑
  edit(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modal = true;
    this.coopId = data;
    this.copyModel = false;
    this.validateForm.controls.title.setValue(data.title); //问卷标题
    this.validateForm.controls.surveyTarget.setValue(data.surveyTarget?data.surveyTarget.id.toString():''); //调查目标
    this.validateForm.controls.surveyDescribe.setValue(data.surveyDescribe); //问卷描述
  }
  //复制
  copyModel = false; //复制
  copy(data) {
    this.modelName = "复制";
    this.copyModel = true;
    this.modal = true;
    this.coopId = data;
    this.validateForm.controls.title.setValue(data.name); //名称
    this.validateForm.controls.surveyTarget.setValue(data.workType + ""); //类型
    this.validateForm.controls.surveyDescribe.setValue(data.describe); //描述
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  // promptModalUrl = '';
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    // this.promptModalUrl = url;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
    this.getList(0);
  }

  // 启用
  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  confirmDelIsSwitch: boolean; //启用/停用
  showDelModal(
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
  ) {
    this.confirmDelType = type;
    this.delModal = true;
    this.coopId = data;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏框
  hideDelModal() {
    this.delModal = false;
  }
  // 下载二维码
  downLoadQrCode(base64Img){
    let link = document.createElement('a')
    link.href = base64Img
    link.download = 'qrCode-'+ Date.now()
    let event = document.createEvent('MouseEvents')
    event.initMouseEvent('click',true,false,window,0,0,0,0,0,false,false,false,false,0,null)
    link.dispatchEvent(event);
  }
  // 确认
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      this.mainService
        .apiPost("rmvData", "questionnaireManagement", [this.coopId.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            if (
              this.listOfData.length == 1 &&
              this.pageIndex == Math.ceil(this.listLength / this.pageSize)
            ) {
              this.listLength--;
              if (this.listLength === 0) {
                this.pageIndex = 1;
              } else {
                this.pageIndex = Math.ceil(this.listLength / this.pageSize);
              }
            }
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }else if (this.confirmDelType === "publish"){
      // 发布
      this.mainService
      .managerQuestionnaire({
        survey_state: 2,//已发布
        qmId:this.coopId.id
      })
      .subscribe((data:any) => {
        this.btnLoading = false;
        this.delModal = false;
        if (data.status == 200) {
          this.message.create('success', `操作成功`);
          this.addLinkModal(data.data);
          this.getList(0);
        } else {
          this.showPromptModal(this.tipsMsg2, false, data.msg);
        }
      });
    }else if (this.confirmDelType === "complete"){
      // 发布
      this.mainService
      .managerQuestionnaire({
        survey_state: 3,//调研完成
        qmId:this.coopId.id
      })
      .subscribe((data:any) => {
        this.btnLoading = false;
        this.delModal = false;
        if (data.status == 200) {
          this.message.create('success', `操作成功`);
          this.getList(0);
        } else {
          this.showPromptModal(this.tipsMsg2, false, data.msg);
        }
      });
    }
    // if (this.confirmDelType === "del") {
    //   //删除
    //   this.mainService
    //     .apiPost("rmvData", "questionnaireManagement", [this.coopId.id])
    //     .subscribe((data) => {
    //       this.btnLoading = false;
    //       this.delModal = false;
    //       if (data.status == 200) {
    //         if (
    //           this.listOfData.length == 1 &&
    //           this.pageIndex == Math.ceil(this.listLength / this.pageSize)
    //         ) {
    //           this.listLength--;
    //           if (this.listLength === 0) {
    //             this.pageIndex = 1;
    //           } else {
    //             this.pageIndex = Math.ceil(this.listLength / this.pageSize);
    //           }
    //         }
    //         this.showPromptModal(this.tipsMsg2, true, "");
    //       } else {
    //         this.showPromptModal(this.tipsMsg2, false, data.msg);
    //       }
    //     });
    // } else if (this.confirmDelType === "switch") {
    //   //启用
    //   let data = {
    //     workScheme: {
    //       id: this.coopId.id,
    //       hosId: this.currentHospital.id,
    //       status: 1,
    //       workType: this.coopId.workType,
    //     },
    //   };
    //   this.mainService
    //     .coopConfig("activeWorkScheme", data)
    //     .subscribe((result) => {
    //       this.btnLoading = false;
    //       this.delModal = false;
    //       if (result.status == 200) {
    //         this.showPromptModal(this.tipsMsg2, true, "");
    //       } else {
    //         this.showPromptModal(this.tipsMsg2, false, result.msg);
    //       }
    //     });
    // } else if (this.confirmDelType === "switchTime") {
    //   //关闭定时启用
    //   let data = {
    //     workScheme: {
    //       id: this.coopId.id,
    //       hosId: this.currentHospital.id,
    //       timingStatus: 0,
    //     },
    //   };
    //   this.mainService
    //     .coopTypeConfig("addData", "workScheme", data)
    //     .subscribe((result) => {
    //       this.btnLoading = false;
    //       this.delModal = false;
    //       if (result.status == 200) {
    //         this.showPromptModal(this.tipsMsg2, true, "");
    //       } else {
    //         this.showPromptModal(this.tipsMsg2, false, result.msg);
    //       }
    //     });
    // }
  }

  // 查看
  detail(id) {
    this.router.navigateByUrl("/main/questionnaireManagement/questionnaireManagementDetail/" + id);
  }
}
