import { Component, OnInit, ViewChild, ElementRef } 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-questions",
  templateUrl: "./questions.component.html",
  styleUrls: ["./questions.component.less"],
})
export class QuestionsComponent implements OnInit {
  @ViewChild("inputElement", { static: false }) inputElement: ElementRef;
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private router: Router,
    private tool: ToolService
  ) {
    this.route.queryParams.subscribe((res) => {
      this.queryParamsId = res.id;
      this.queryParamsToken = res.token;
      this.queryParamsName = res.title;
    });
  }
  searchCriteria = {
    //搜索条件
    name: "",
    workModel: null,
  };
  allWorkModel = [
    { id: 1, name: "自由抢单" },
    { id: 2, name: "指定分组" },
    { id: 3, name: "科室绑定人员" },
    { id: 4, name: "科室绑定分组" },
  ];
  quickCombinationModel;
  requireGroup = false;
  requireDept = false;
  queryParamsId = ""; //方案id
  queryParamsToken = ""; //方案token
  queryParamsName = ""; //方案名称
  userInfo: any = JSON.parse(localStorage.getItem("user")) || {}; //登录用户信息
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  tableHeight: number; //表格动态高
  modal: boolean = false; //新增/编辑模态框
  personModal: boolean = false; //定时启用设置日期模态框
  groupsModal: boolean = false; //定时启用设置日期模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  validateDateForm: FormGroup; //定时启动设置日期表单
  validatePersonForm: FormGroup; //
  validateGroupForm: FormGroup; //
  coopId: number; //当前操作列id
  timeDefaultValue = setHours(setMinutes(setSeconds(new Date(), 0), 0), 0);

  btnLoading: boolean = false; //提交按钮loading状态
  currentHospital; //当前院区

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  showLoading = false; //操作是否显示loading

  classList = []; //班次列表
  maskFlag: any = false;
  qItems: any = []; //10个选项
  // -----------------------

  ngOnInit() {
    this.getOneQuestionnaireManagement();
    Array(10).fill('').forEach((v, i)=>{
      this.qItems.push({id:i+1, value:''});
    })
    console.log(this.qItems)
    this.currentHospital = this.tool.getCurrentHospital();
    this.initForm();
    this.getList(1);
    this.getAnswerModes();
  }
  // 获取问卷数据
  getOneQuestionnaireManagement(){
    this.mainService.getFetchData('api', "questionnaireManagement", this.queryParamsId).subscribe(res=>{
      if(res.status == 200){
        this.queryParamsToken = res.data.token;
        this.queryParamsName = res.data.title;
      }
    })
  }
  // 重置
  reset() {
    this.searchCriteria = {
      //搜索条件
      name: "",
      workModel: null,
    };
    this.getList(1);
  }
  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      questionnaireInfo: {
        managementId: this.queryParamsId,
      },
      idx: this.pageIndex - 1,
      sum: this.pageSize,
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("api", "questionnaireInfo", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }
      });
  }

  // 新增/编辑弹框
  addModal() {
    this.add = true; //新增
    this.modal = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    this.copyFlag = false;
    this.initForm();
  }
  // 修改排序号
  onChange(value: string): void {
    if (value !== "") {
      let oValue = parseInt(value);
      this.inputElement.nativeElement.value = isNaN(oValue)?'':(oValue?oValue:'');
    }
  }
  // 获取字典数据-答题方式
  answerModes: any[] = [];
  answerModesRadioValue;
  getAnswerModes() {
    this.mainService.getDictionary("list", "answer_mode").subscribe((data) => {
      this.answerModes = data;
      this.answerModesRadioValue = data.find((v) => v.value == 1).id;
    });
  }
  // 初始化新增form表单
  initForm() {
    this.quickCombinationModel = "";
    this.validateForm = this.fb.group({
      describe: [null, [Validators.required]],
      orders: [null, [Validators.required]],
      answerMode: [null, [Validators.required]],
    });
  }
  // 初始化新增form表单
  initPersonForm() {
    this.validatePersonForm = this.fb.group({
      quickCombinationPerson: [null, [Validators.required]],
    });
  }
  // 初始化新增form表单
  initGroupsForm() {
    this.validateGroupForm = this.fb.group({
      quickCombinationGroups: [null, [Validators.required]],
    });
  }
  // 新增/编辑表单提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    console.log(this.validateForm);
    this.btnLoading = true;

    if (this.validateForm.invalid) {
      this.btnLoading = false;
      return;
    }
    let data:any = {};
    if(this.add){
      data = { 
        questionnaireInfo: {
          hosId: this.currentHospital.id,
          managementId: this.queryParamsId,
          describe: this.validateForm.value.describe,
          orders: this.validateForm.value.orders,
          answerMode: {id: this.validateForm.value.answerMode},
        }
      };
      if(this.validateForm.value.answerMode == this.answerModesRadioValue){
        this.qItems.forEach((v, i)=>{
          data.questionnaireInfo['option' + (i + 1)] = v.value;
        })
      }
    }else{
      data = { 
        questionnaireInfo: {
          describe: this.validateForm.value.describe,
          orders: this.validateForm.value.orders,
          answerMode: {id: this.validateForm.value.answerMode},
        }
      };
      if(this.validateForm.value.answerMode == this.answerModesRadioValue){
        this.qItems.forEach((v, i)=>{
          data.questionnaireInfo['option' + (i + 1)] = v.value;
        })
      }else{
        Array(10).fill('').forEach((v, i)=>{
          data.questionnaireInfo['option' + (i + 1)] = v
        })
      }
      data.questionnaireInfo = Object.assign(this.info,data.questionnaireInfo);
      console.log(data);
    }
    this.mainService
      .coopTypeConfig(
        this.add || (!this.add && this.copyFlag) ? "addData" : "updData",
        "questionnaireInfo",
        data
      )
      .subscribe((result) => {
        this.btnLoading = false;
        if (result.status == 200) {
          console.log(this.copyFlag);
          if (this.add) {
            this.showPromptModal("新增", true, "");
            this.listLength++;
          } else if (this.copyFlag) {
            this.showPromptModal("复制", true, "");
            this.listLength++;
          } else if (!this.copyFlag) {
            //编辑
            this.showPromptModal("编辑", true, "");
          }
        } else {
          let msg = "";
          if (this.add) {
            msg = "新增";
          } else if (!this.copyFlag) {
            msg = "修改";
          } else if (this.copyFlag) {
            msg = "复制";
          }
          this.showPromptModal(msg, false, result.msg);
        }
        this.hideAddModal();
        this.initForm();
      });
  }
  // 复制
  copyFlag = false;
  copy(e, data) {
    e.stopPropagation();
    console.log(data);
    this.add = false;
    this.copyFlag = true;
    this.coopId = data.id;
    this.info = data;
  }
  // 编辑
  info; //编辑时候保存的信息
  edit(e, data) {
    e.stopPropagation();
    console.log(data);
    this.add = false;
    this.coopId = data.id;
    this.info = data;
    this.validateForm.controls.describe.setValue(data.describe); //问卷描述
    this.validateForm.controls.orders.setValue(data.orders); //排序号
    this.validateForm.controls.answerMode.setValue(data.answerMode?data.answerMode.id.toString():''); //答题方式
    if(data.answerMode && data.answerMode.id){
      this.qItems.forEach((v, i)=>{
        v.value = data['option'+ (i+1)]
      })
    }
    this.modal = true;
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  // promptModalUrl = '';
  showPromptModal(con, success, promptInfo?, loading?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    if (loading !== undefined) {
      this.showLoading = loading;
    } else {
      this.showLoading = false;
      this.getList(0);
    }
    // this.promptModalUrl = url;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
  }
  // 选中表格中快捷建单
  isAllDisplayDataChecked = false; //当前页是否全选
  mapOfCheckedId = {};
  checkedDepIds = []; //已选中快捷建单id
  refreshStatus(): void {
    this.isAllDisplayDataChecked = this.listOfData.every(
      (item) => this.mapOfCheckedId[item.id]
    );
    let arr = [];
    for (var k in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[k]) {
        arr.push(Number(k));
      }
    }
    this.checkedDepIds = arr;
    console.log(this.checkedDepIds, this.isAllDisplayDataChecked);
  }
  // 整行选中或不选中
  selectedListData(id) {
    this.mapOfCheckedId[id] = !this.mapOfCheckedId[id];
    this.refreshStatus();
  }
  // 全选
  checkAll(value: boolean): void {
    this.listOfData.forEach((item) => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }

  // 删除轮巡计划
  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  confirmDelIsSwitch: boolean; //启用/停用
  showDelModal(
    e,
    id: any,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
    isSwitch?: boolean
  ) {
    e.stopPropagation();
    this.confirmDelIsSwitch = isSwitch;
    this.confirmDelType = type;
    this.delModal = true;
    this.coopId = id;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      let arrData = [];
      if (Array.isArray(this.coopId)) {
        arrData = this.coopId;
      } else {
        arrData = [this.coopId];
      }
      this.mainService
        .coopTypeConfig("rmvData", "questionnaireInfo", arrData)
        .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, "");
            this.isAllDisplayDataChecked = false;
            this.checkedDepIds = [];
            this.mapOfCheckedId = {};
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }
  // ----------返回拦截------------
  tipModal = false;
  // tipMsg1 = '是否确定离开该界面，如果未点击生效，数据可能会遗失？';
  // 隐藏模态框
  hideTipModal() {
    // this.tipModal = false;
  }
  // 返回
  goToWorkAssignment() {
    // this.tipModal = true;
    this.router.navigateByUrl(`/main/questionnaireManagement`);
  }
  // 模态框确认
  confirmTip() {
    // this.tipModal = false;
    // this.router.navigateByUrl(`/main/workAssignment`);
  }
}
