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

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

  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopData: any; //当前操作列
  currentHospital; //当前院区

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

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

  changeInpSubject = new Subject(); //防抖
  showDropdown:boolean = false;

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[1] === 'department'){
        this.getDeparts(v[0], v[2]);
      } else if(v[1] === 'building'){
        this.getBuildings(v[0], v[2]);
      } else if(v[1] === 'floor'){
        this.getFloors(v[0], v[2], this.validateForm.value.buildId);
      } else if(v[1] === 'assetProduct'){
        this.getAssetProductList(v[0], v[2]);
      } else if(v[1] === 'hospital'){
        this.getDutyList(v[0], v[2]);
      }
    });
    this.currentHospital = this.tool.getCurrentHospital();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getList(1);
    this.getDeparts('search', '');
    this.getDeparts('add', '');
    this.getAssetProductList('add', '');
    this.getDutyList('add', '');
    this.getBuildings('add', '');
    this.getDispatchMethods();
  }

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

  // 搜索
  search() {
    this.getList(1);
  }
  // 重置
  reset() {
    this.searchDto = {};
    this.getList(1);
  }

  // 表格数据
  searchDto: any = {};
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      asset: {
        hosId: this.currentHospital.id,
        ...this.searchDto,
      },
    };
    data.asset.status = data.asset.status ? { id: data.asset.status } : undefined;
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "asset", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 新增弹框
  disableDutyId:boolean = false;
  addModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modal = true;
    this.initForm();
    let { hospital, type } = this.tool.getHospitalOrDuty();
    if(type === 'duty'){
      this.disableDutyId = true;
      this.validateForm.controls.dutyId.setValue(hospital.id);
    }else{
      this.disableDutyId = false;
    }
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }

  // 初始化新增form表单
  initForm() {
    this.floorList = [];
    this.validateForm = this.fb.group({
      code: ['', [Validators.required, Validators.pattern(/\S/)]],
      snCode: ['', [Validators.required, Validators.pattern(/\S/)]],
      productId: [null, [Validators.required]],
      name: ['', [Validators.required, Validators.pattern(/\S/)]],
      buildId: [null, [Validators.required]],
      floorId: [null, [Validators.required]],
      address: ['', [Validators.required, Validators.pattern(/\S/)]],
      status: [null, [Validators.required]],
      brand: ['', [Validators.required, Validators.pattern(/\S/)]],
      supplierId: [null, [Validators.required]],
      deptId: [null, [Validators.required]],
      dutyId: [null, [Validators.required]],
    });
  }

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

  // 获取产品列表
  assetProductList: any = [];
  getAssetProductList(type, keyword, init = false) {
    let postData:any = {
      assetProduct: {
        name: keyword,
        hosId: this.currentHospital.id,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("simple/data", "assetProduct", postData)
      .subscribe((data) => {
        this.assetProductList = data.list || [];

        this.isLoading = false;
      });
  }

  // 获取所有科室
  departmentAddList: any = []; //所有所属科室
  departmentSearchList: any = []; //所有所属科室(搜索)
  getDeparts(type, keyword, init = false) {
    let postData:any = {
      department: {
        // searchType: 1,// 简单查询
        dept: keyword,
        cascadeHosId: this.currentHospital.id,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((data) => {
        if (type == "search") {
          this.departmentSearchList = data.list;
        } else if (type == "add") {
          this.departmentAddList = data.list;
        }

        this.isLoading = false;
      });
  }

  // 获取供应商
  companyList: any = [];

  // 获取责任部门
  dutyList: any = [];
  getDutyList(type, keyword, init = false) {
    let postData:any = {
      hospital: {
        hosName: keyword,
        type: { key: 'hospital_type', value: '6' },
      },
      idx: 0,
      sum: 9999,
    };
    this.mainService
      .getFetchDataList("simple/data", "hospital", postData)
      .subscribe((data) => {
        this.dutyList = data.list || [];

        this.isLoading = false;
      });
  }

  // 获取楼栋
  buildingAddList: any = [];
  buildingSearchList: any = [];
  getBuildings(type, keyword, init = false) {
    let postData = {
      building: {
        simpleQuery: true,
        buildingName: keyword,
        cascadeHosId: this.currentHospital.id,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("simple/data", "building", postData)
      .subscribe((data) => {
        if (type == "search") {
          this.buildingSearchList = data.list;
        } else if (type == "add") {
          this.buildingAddList = data.list;
        }
        this.isLoading = false;
      });
  }

  // 修改产品
  changeAssetProduct(id){
    let obj = this.assetProductList.find(v => v.id == id);
    console.log(obj);
    this.validateForm.controls.brand.setValue(obj.brand);
    this.companyList = obj.supplierList || [];
    this.validateForm.controls.supplierId.setValue(null);
  }

  // 修改楼栋
  noChangeBuilding:boolean = false;
  changeBuilding(buildId?){
    console.log(buildId)
    if(!this.noChangeBuilding){
      this.validateForm.controls.floorId.setValue(null);
      this.getFloors('add', '', this.validateForm.value.buildId);
    }
    this.noChangeBuilding = false;
  }

  // 获取楼层
  floorList: any = [];
  getFloors(type, keyword, buildId, init = false, isNoChangeBuilding = false) {
    console.log(isNoChangeBuilding)
    if(!buildId){
      this.floorList = [];
      return;
    }
    let postData = {
      floor: {
        floorName: keyword,
        buildId,
        // hosId: this.currentHospital.id,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("simple/data", "floor", postData)
      .subscribe((data) => {
        this.floorList = data.list;
        this.isLoading = false;
      });
  }

  //获取状态
  dispatchMethods:any[] = [];
  getDispatchMethods() {
    this.isLoading = true;
    this.mainService.getDictionary("list", "asset_status").subscribe((data) => {
      this.isLoading = false;
      this.dispatchMethods = data || [];
    });
  }

  // 新增/编辑表单提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      return;
    }

    console.log(this.validateForm.value)

    this.btnLoading = true;
    let postData:any = {};

    if (this.add) {
      //增加
      postData = {
        asset: {
          hosId: this.currentHospital.id,
          code: this.validateForm.value.code,
          snCode: this.validateForm.value.snCode,
          productId: this.validateForm.value.productId,
          name: this.validateForm.value.name,
          buildId: this.validateForm.value.buildId,
          floorId: this.validateForm.value.floorId,
          address: this.validateForm.value.address,
          status: { id: this.validateForm.value.status },
          deptId: this.validateForm.value.deptId,
          dutyId: this.validateForm.value.dutyId,
          brand: this.validateForm.value.brand,
          supplierId: this.validateForm.value.supplierId,
        }
      };
    } else {
      //编辑
      postData = {
        asset:{
          ...this.coopData,
          ...{
            hosId: this.currentHospital.id,
            code: this.validateForm.value.code,
            snCode: this.validateForm.value.snCode,
            productId: this.validateForm.value.productId,
            name: this.validateForm.value.name,
            buildId: this.validateForm.value.buildId,
            floorId: this.validateForm.value.floorId,
            address: this.validateForm.value.address,
            status: { id: this.validateForm.value.status },
            deptId: this.validateForm.value.deptId,
            dutyId: this.validateForm.value.dutyId,
            brand: this.validateForm.value.brand,
            supplierId: this.validateForm.value.supplierId,
          }
        }
      };
    }
    this.mainService
      .coopData("addData", "asset", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hideAddModal();
        let msg = "";
        if (this.add) {
          msg = "新增";
        } else {
          msg = "修改";
        }
        if (result.status == 200) {
          this.showPromptModal(msg, true, "");
        } else {
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  // 展示信息提示框（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(0);
  }

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  showDelModal(
    e,
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
  ) {
    e.stopPropagation();
    this.confirmDelType = type;
    this.delModal = true;
    this.coopData = data;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      this.mainService
        .simplePost("rmvData", "asset", [this.coopData.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }
}
