import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";

import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { QRCodeConfigurationService } from './qrcode-configuration.service';
import { MainService } from "../../services/main.service";

@Component({
  selector: "app-qrcode-configuration",
  templateUrl: "./qrcode-configuration.component.html",
  styleUrls: ["./qrcode-configuration.component.less"],
})
export class QRCodeConfigurationComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private tool: ToolService,
		private mainService: MainService,
    private qrCodeConfigurationService: QRCodeConfigurationService,
  ) {}

  listOfData: any[] = []; //表格数据

  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  department: any; //所属科室
  hosId: any; //院区（搜索）
  deptList: Array<any>; //所有科室
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

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

  btnLoading: boolean = false; //提交按钮loading状态
  changeInpSubject = new Subject(); //防抖

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

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getOtherTasktype(v[0]);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList(true);
		this.getPrioritys();
  }

  // 新添加地点号码
  deptPhones: any = []; //新添加的地点电话列表
  deptsPhoneId = 1; //地点电话自增id
  isAddDeptsPhone = true; //添加新的地点电话是否禁用
  addDeptPhone(e: MouseEvent) {
    e.preventDefault();
    this.deptPhones.push({ id: ++this.deptsPhoneId, phone: "" });
    this.deptsPhoneChange();
  }
  // 删除新添加地点号码
  removeDeptPhone(index: number, e: MouseEvent) {
    e.preventDefault();
    this.deptPhones.splice(index, 1);
    this.deptsPhoneChange();
  }
  //监听科室电话输入事件
  deptsPhoneChange(e?, phone?) {
    if (e !== undefined && phone !== undefined) {
      phone.phone = e;
    }
    // -------------判断添加按钮是否禁用 start
    this.isAddDeptsPhone = !this.validateForm.value.phones;
    if (!this.isAddDeptsPhone) {
      //如果没禁用
      this.isAddDeptsPhone = this.deptPhones.some((item) => item.phone === "");
    }
    // -------------判断添加按钮是否禁用 end
  }

  // 搜索
  search() {
    this.getList(true);
  }
  // 重置
  reset() {
    this.searchDto = {};
    this.getList(true);
  }
  // 表格数据
  alldepart1: any = []; //所有所属科室(搜索)
  searchDto:any =  {};
  loading1 = false;
  getList(isResetPageIndex = false) {
    isResetPageIndex && (this.pageIndex = 1);
    let data = {
      pageIndex: this.pageIndex,
      pageSize: this.pageSize,
      hosId: this.hosId,
      searchDto: this.searchDto,
    };
    this.loading1 = true;
    this.qrCodeConfigurationService
      .query(data)
      .subscribe((result) => {
        this.loading1 = false;
        result.list = result.list || [];
        this.listOfData = result.list;
        this.listLength = result.totalNum;
      });
  }

  // 获取科室列表
  getOtherTasktype(keywords = '') {
    let hosId = this.tool.getCurrentHospital().id;
    this.isLoading = true;
    this.qrCodeConfigurationService.queryOtherTasktype({
      hosId,
      keywords,
    }).subscribe((res) => {
      this.isLoading = false;
      this.deptList = res.list || [];
    });
  }
	
	// 获取优先级
	priority_c_List: any = [];
	getPrioritys() {
	  let postData = {
	    priority: {},
	    idx: 0,
	    sum: 9999,
	  };
	  this.mainService.getFetchDataList("simple/data", "priority", postData)
	    .subscribe((data) => {
	      this.isLoading = false;
	      this.priority_c_List = data.list || [];
	    });
	}
	
  // 新增弹框
  showModal() {
    this.add = true;
    this.modal = true;
    this.initForm();
    this.isAddDeptsPhone = true;
    this.deptPhones = [];
  }
  hideModal() {
    this.modal = false;
    this.initForm();
  }

  // 初始化新增form表单
  initForm() {
    if (this.add) {
      this.deptList = [];
    }
    this.validateForm = this.fb.group({
      name: ['', [Validators.required]],
      deptId: [null, [Validators.required]],
      placeCode: ['', [Validators.required]],
      phones: [null],
			priority: [null], //优先级
    });
  }
  // 表单提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty({ onlySelf: true });
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    this.btnLoading = true;
    let deptsPhone = this.deptPhones.map((item) => item.phone).join();
    if(this.add){
			let query ={
        name: this.validateForm.value.name,
        deptId: this.validateForm.value.deptId,
        placeCode: this.validateForm.value.placeCode,
				priority: {
					id:this.validateForm.value.priority
				},
        phones: deptsPhone ? this.validateForm.value.phones + "," + deptsPhone : this.validateForm.value.phones,
        hosId: this.hosId,
      }
			if(this.validateForm.value.priority){
				query.priority.id = this.validateForm.value.priority
			}else{
				delete query.priority
			}
      this.qrCodeConfigurationService
      .add(query)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideModal();
        this.initForm();
        if (data.status == 200) {
          this.showPromptModal(this.add ? "新增" : "编辑", true, "");
        } else {
          this.showPromptModal(this.add ? "新增" : "编辑", false, data.msg);
        }
      });
    }else{
			let query = {
        name: this.validateForm.value.name,
        deptId: this.validateForm.value.deptId,
        placeCode: this.validateForm.value.placeCode,
        phones: deptsPhone ? this.validateForm.value.phones + "," + deptsPhone : this.validateForm.value.phones,
        coopData: this.coopData,
				priority: {
					id:this.validateForm.value.priority
				},
      }
			if(this.validateForm.value.priority){
				query.priority.id = this.validateForm.value.priority
			}else{
				delete query.priority
			}
      this.qrCodeConfigurationService
      .update(query)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideModal();
        this.initForm();
        if (data.status == 200) {
          this.showPromptModal(this.add ? "新增" : "编辑", true, "");
        } else {
          this.showPromptModal(this.add ? "新增" : "编辑", false, data.msg);
        }
      });
    }
  }

  // 编辑
  maskFlag: any = false;
  coopData = {};
  edit(data) {
    this.isAddDeptsPhone = false;
    this.deptPhones = [];
    let phones = data.phones ? data.phones.split(",") : [];
    if (phones.length === 0) {
      this.validateForm.controls.phones.setValue("");
      this.deptPhones = [];
    } else if (phones.length === 1) {
      this.validateForm.controls.phones.setValue(phones[0]);
      this.deptPhones = [];
    } else {
      this.validateForm.controls.phones.setValue(phones[0]);
      this.deptPhones = phones.slice(1).map((item) => {
        return {
          id: ++this.deptsPhoneId,
          phone: item,
        };
      });
    }
    this.validateForm.controls.name.setValue(data.name);
    this.validateForm.controls.deptId.setValue(data.deptId);
    this.validateForm.controls.placeCode.setValue(data.placeCode);
		if(data.priority){
			this.validateForm.controls.priority.setValue(data.priority.id);
		}
    this.modal = true;
    this.add = false;
    this.coopId = data.id;
    this.coopData = data;
    this.getOtherTasktype();
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del(data) {
    this.coopId = data.id;
    this.delModal = true;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    this.qrCodeConfigurationService
      .delete({
        id: this.coopId
      })
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideDelModal();
        if (data.status == 200) {
          if (this.listOfData.length == 1 && this.pageIndex == Math.ceil(this.listLength / this.pageSize)) {
            this.listLength--;
            this.pageIndex = Math.ceil(this.listLength / this.pageSize);
          }
          this.showPromptModal("删除", true, "");
        } else {
          this.showPromptModal("删除", false, data.msg);
        }
      });
  }

  // 关闭删除模态框
  hideDelModal() {
    this.delModal = false;
  }

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

  // 边输边搜节流阀
  isLoading = false;
  changeInp(e) {
    this.changeInpSubject.next([e]);
  }

  // 打开任务类型
  openOtherTasktype(e){
    if(e){
      this.getOtherTasktype();
    }
  }
}
