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

import { MainService } from "../../services/main.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { NzMessageService } from "ng-zorro-antd";

@Component({
  selector: "app-unit-management",
  templateUrl: "./unit-management.component.html",
  styleUrls: ["./unit-management.component.less"],
})
export class UnitManagementComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private mainService: MainService,
    private tool: ToolService
  ) {}

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

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

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

  btnLoading: boolean = false; //提交按钮loading状态
  isShowDateType = false; //是否显示日期方案

  ngOnInit() {
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.getAllHospital();
    this.getTransTypes();
  }

  // 初始化增删改按钮
  coopBtns: any = {};
  // 表格数据
  loading1 = false;
  getList() {
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      company: {
        hosId: this.hosId,
        busiType: { key: 'company_busi_type', value: '1' },
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "company", data)
      .subscribe((data) => {
        this.loading1 = false;
        this.listOfData = data.list;
        this.listLength = data.totalNum;
      });
  }

  // 获取相应的院区
  getAllHospital() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList();
  }

  // 获取单位类型
  transTypes: Array<any> = [];
  getTransTypes() {
    var that = this;
    that.mainService.getDictionary("list", "company_trans_type").subscribe((data) => {
      that.transTypes = data;
    });
  }

  // 新增弹框
  showModal() {
    this.add = true;
    this.laborers = [];
    this.carNos = [];
    this.initForm();
    this.modal = true;
  }
  hideModal() {
    this.modal = false;
    this.laborers = [];
    this.carNos = [];
    this.initForm();
  }

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
      transType: [null, [Validators.required]],
      contacts: [null, [Validators.required]],
      mphone: [null, [Validators.required]],
      laborerName0: [null, [Validators.required]],
      laborerPhone0: [null, [Validators.required]],
      carNo0: [null, [Validators.required]],
      businessCode: [null],
      address: [null],
    });
  }
  // 选择生成方案
  transTypeChange(data) {
    this.laborers.forEach((v, i) => {
      this.removeLaborer(i);
    })
    this.carNos.forEach((v, i) => {
      this.removeCarNo(i);
    })
    if(data){
      if(data.laborers){
        let arr:any[] = data.laborers || [];
        this.validateForm.controls.laborerName0.setValue(arr[0].name);
        this.validateForm.controls.laborerPhone0.setValue(arr[0].mphone);
        if(arr.length > 1){
          arr = arr.slice(1);
          arr.forEach(v => {
            this.addLaborer(null, v.name, v.mphone);
          })
        }
      }
      if(data.carNo){
        let arr:any[] = data.carNo.split(",");
        this.validateForm.controls.carNo0.setValue(arr[0]);
        if(arr.length > 1){
          arr = arr.slice(1);
          arr.forEach(v => {
            this.addCarNo(null, v);
          })
        }
      }
    }else{
      this.validateForm.controls.laborerName0.setValue(null);
      this.validateForm.controls.laborerPhone0.setValue(null);
      this.validateForm.controls.carNo0.setValue(null);
    }
    let value = this.transTypes.find(v => v.id == this.validateForm.value.transType).value;
    this.isShowDateType = value == 1;
    if(this.isShowDateType){
      this.validateForm.get("laborerName0")!.setValidators(Validators.required);
      this.validateForm.get("laborerName0")!.markAsDirty();

      this.validateForm.get("laborerPhone0")!.setValidators(Validators.required);
      this.validateForm.get("laborerPhone0")!.markAsDirty();

      this.validateForm.get("carNo0")!.setValidators(Validators.required);
      this.validateForm.get("carNo0")!.markAsDirty();
    }else{
      this.validateForm.get("laborerName0")!.clearValidators();
      this.validateForm.get("laborerName0")!.markAsPristine();

      this.validateForm.get("laborerPhone0")!.clearValidators();
      this.validateForm.get("laborerPhone0")!.markAsPristine();

      this.validateForm.get("carNo0")!.clearValidators();
      this.validateForm.get("carNo0")!.markAsPristine();
    }
  }
  // 表单提交
  submitForm(): void {
    var that = this;
    for (const i in that.validateForm.controls) {
      that.validateForm.controls[i].markAsDirty({ onlySelf: true });
      that.validateForm.controls[i].updateValueAndValidity();
    }
    if (that.validateForm.invalid) return;
    that.btnLoading = true;
    let postData:any = {
      company:{
        name: that.validateForm.value.name,
        transType: { id: that.validateForm.value.transType },
        contacts: that.validateForm.value.contacts,
        mphone: that.validateForm.value.mphone,
        businessCode: that.validateForm.value.businessCode,
        address: that.validateForm.value.address,
        hosId: that.hosId,
        laborers: [],
        carNo: "",
        busiType: { key: 'company_busi_type', value: '1' },
      }
    };
    // 司机信息
    if(that.validateForm.value.laborerName0 && that.validateForm.value.laborerPhone0){
      postData.company.laborers = [{name: that.validateForm.value.laborerName0, mphone: that.validateForm.value.laborerPhone0}];
      this.laborers.forEach(v => {
        postData.company.laborers.push({name: that.validateForm.value[v[0].name], mphone: that.validateForm.value[v[1].name]})
      })
    }
    // 车牌号信息
    if(that.validateForm.value.carNo0){
      postData.company.carNo = that.validateForm.value.carNo0;
      this.carNos.forEach(v => {
        postData.company.carNo += "," + that.validateForm.value[v.name];
      })
    }
    if (!that.add) {
      postData.company = {...this.coopData, ...postData.company};
    }
    console.log(postData);
    that.mainService
      .coopData("addData", "company", postData)
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideModal();
        that.initForm();
        if (data.status == 200) {
          that.showPromptModal(that.add ? "新增" : "编辑", true, "");
        } else {
          that.showPromptModal(that.add ? "新增" : "编辑", false, data.msg);
        }
      });
  }

  // 编辑
  maskFlag: any = false;
  coopData:any = {};
  edit(data) {
    this.modal = true;
    this.add = false;
    this.coopId = data.id;
    this.coopData = data;
    this.validateForm.controls.name.setValue(data.name);
    this.validateForm.controls.transType.setValue(data.transType.id);
    this.validateForm.controls.contacts.setValue(data.contacts);
    this.validateForm.controls.mphone.setValue(data.mphone);
    this.validateForm.controls.businessCode.setValue(data.businessCode);
    this.validateForm.controls.address.setValue(data.address);
    this.transTypeChange(data);
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del(data) {
    this.coopId = data.id;
    this.delModal = true;
  }
  // 确认删除
  confirmDel() {
    let that = this;
    that.btnLoading = true;
    that.mainService
      .simplePost("rmvData", "company", [that.coopId])
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideDelModal();
        if (data["status"] == 200) {
          if (
            that.listOfData.length == 1 &&
            that.pageIndex == Math.ceil(that.listLength / that.pageSize)
          ) {
            that.listLength--;
            that.pageIndex = Math.ceil(that.listLength / that.pageSize) || 1;
          }
          that.showPromptModal("删除", true, "");
        } else {
          that.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();
  }

  isLoading = false;
  id:number = 1;

  // 司机信息多项
  laborers:any[] = [];
  // 新添加司机信息
  addLaborer(e: MouseEvent, laborerName = null, laborerPhone = null) {
    e && e.preventDefault();
    let id  = this.laborers.length + 1;
    // 姓名
    this.laborers.push([
      { name: `laborerName${id}`, id: ++this.id },//姓名
      { name: `laborerPhone${id}`, id: ++this.id },//电话
    ]);
    console.log(this.laborers);
    this.validateForm.addControl(
      `laborerName${id}`,
      new FormControl(laborerName, Validators.required)
    );
    // 电话
    this.validateForm.addControl(
      `laborerPhone${id}`,
      new FormControl(laborerPhone, Validators.required)
    );
  }
  // 新添加司机信息
  removeLaborer(index: number, e?: MouseEvent) {
    e && e.preventDefault();
    this.laborers.splice(index, 1);
    this.validateForm.removeControl(`laborerName${index + 1}`);
    this.validateForm.removeControl(`laborerPhone${index + 1}`);
  }

  // 车牌号多项
  carNos:any[] = [];
  // 新添加车牌号
  addCarNo(e: MouseEvent, carNo = null) {
    e && e.preventDefault();
    let id = this.carNos.length + 1;
    this.carNos.push({ name: `carNo${id}`, id: ++this.id });
    console.log(this.carNos);
    this.validateForm.addControl(
      `carNo${id}`,
      new FormControl(carNo, Validators.required)
    );
  }
  // 新添加车牌号
  removeCarNo(index: number, e?: MouseEvent) {
    e && e.preventDefault();
    this.carNos.splice(index, 1);
    this.validateForm.removeControl(`carNo${index + 1}`);
  }
}
