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-product-management",
  templateUrl: "./assets-product-management.component.html",
  styleUrls: ["./assets-product-management.component.less"],
})
export class AssetsProductManagementComponent 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; //操作提示框是否展示
  modelName = ""; //模态框名称

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

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[1] === 'company'){
        this.getCompanyList(v[0], v[2]);
      }
    });
    this.currentHospital = this.tool.getCurrentHospital();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getList(1);
    this.getProductCategoryTypeList(1);
    this.getProductCategoryTypeList(1, 'Search');
    this.getCompanyTypeList();
  }

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

  // 常见故障
  commonFaultId:any;
  commonFault(e, data){
    e.stopPropagation();
    this.commonFaultId = data.id;
    this.showAssetsProductManagementDepartment();
  }

  // 常见故障
  assetsProductManagementPromptModalShow = false;
  showAssetsProductManagementDepartment() {
    this.assetsProductManagementPromptModalShow = true;
  }
  // 关闭弹窗
  closeModelAssetsProductManagement(e) {
    this.assetsProductManagementPromptModalShow = JSON.parse(e).show;
  }

  // 搜索
  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,
      assetProduct: {
        hosId: this.currentHospital.id,
        ...this.searchDto,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "assetProduct", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 新增弹框
  addModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modal = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      name: ['', [Validators.required, Validators.pattern(/\S/)]],
      model: ['', [Validators.required, Validators.pattern(/\S/)]],
      brand: ['', [Validators.required, Validators.pattern(/\S/)]],
      unit: ['', [Validators.required, Validators.pattern(/\S/)]],
      mainType: [null, [Validators.required]],
      subType: [null],
      description: [''],
      supplierIds: [[]],
      manufacturerIds: [[]],
    });
  }

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

  openSupplier(flag){
    if(flag){
      this.getCompanyList('1');
    }
  }

  openManufacturer(flag){
    if(flag){
      this.getCompanyList('2');
    }
  }

  // 获取三方公司
  companyList1: any = [];//供应商
  companyList2: any = [];//生产商
  getCompanyList(type, keyword = '') {
    this.isLoading = true;
    let postData:any = {
      company: {
        name: keyword,
        busiType: {key: "company_busi_type", value: "2"},
        statisticalHosId: this.currentHospital.id,
      },
      idx: 0,
      sum: 20,
    };
    let dictionary = this.companyTypeList.find(v => v.value == type);
    if(!dictionary){
      this['companyList' + type] = [];
      return;
    }
    postData.company.companyTypeIds = dictionary.id.toString();
    this.mainService
      .getFetchDataList("simple/data", "company", postData)
      .subscribe((data) => {
        this['companyList' + type] = data.list || [];
        this.isLoading = false;
      });
  }

  //获取大类/小类
  productCategoryTypeList1:any[] = [];
  productCategoryTypeListSearch1:any[] = [];
  productCategoryTypeList2:any[] = [];
  getProductCategoryTypeList(level:number, type:string = '') {
    this.isLoading = true;
    let postData = {
      dictionaryTree: {
        deleted: 0,
        level,
        parent: level == 1 ? undefined : this.validateForm.value.mainType,
        key: 'product_category_type',
      },
      idx: 0,
      sum: 9999,
    };
    this.mainService
      .getFetchDataList("simple/data", "dictionaryTree", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this['productCategoryTypeList' + type + level] = data.list || [];
      });
  }

  // 获取三方公司公司分类
  companyTypeList:any[] = [];
  getCompanyTypeList(){
    this.mainService.getDictionary("list", "company_type").subscribe((data) => {
      this.companyTypeList = data || [];
      this.getCompanyList('1');
      this.getCompanyList('2');
    });
  }

  // 修改大类
  changeMainType(id){
    console.log(id);
    this.validateForm.controls.subType.setValue(null);
    this.productCategoryTypeList2 = [];

    this.getProductCategoryTypeList(2);
  }

  // 新增/编辑表单提交
  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 = {
        // assetProduct: {
          hosId: this.currentHospital.id,
          name: this.validateForm.value.name,
          model: this.validateForm.value.model,
          brand: this.validateForm.value.brand,
          unit: this.validateForm.value.unit,
          mainType: this.validateForm.value.mainType,
          subType: this.validateForm.value.subType || undefined,
          description: this.validateForm.value.description,
          supplierIds: this.validateForm.value.supplierIds.length ? this.validateForm.value.supplierIds.toString() : undefined,
          manufacturerIds: this.validateForm.value.manufacturerIds.length ? this.validateForm.value.manufacturerIds.toString() : undefined,
        // }
      };
    } else {
      //编辑
      postData = {
        // assetProduct:{
          ...this.coopData,
          ...{
            hosId: this.currentHospital.id,
            name: this.validateForm.value.name,
            model: this.validateForm.value.model,
            brand: this.validateForm.value.brand,
            unit: this.validateForm.value.unit,
            mainType: this.validateForm.value.mainType,
            subType: this.validateForm.value.subType || undefined,
            description: this.validateForm.value.description,
            supplierIds: this.validateForm.value.supplierIds.length ? this.validateForm.value.supplierIds.toString() : undefined,
            manufacturerIds: this.validateForm.value.manufacturerIds.length ? this.validateForm.value.manufacturerIds.toString() : undefined,
          }
        // }
      };
    }
    console.log(postData);
    this.mainService
      .simplePost("addData", "assetProduct", 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);
        }
      });
  }

  // 编辑
  edit(e, data) {
    e.stopPropagation();
    console.log(data);
    this.initForm();
    this.modelName = "编辑";
    this.add = false;
    this.modal = true;
    this.coopData = data;
    this.validateForm.controls.name.setValue(data.name);
    this.validateForm.controls.model.setValue(data.model);
    this.validateForm.controls.brand.setValue(data.brand);
    this.validateForm.controls.unit.setValue(data.unit);
    this.validateForm.controls.mainType.setValue(data.mainType ? data.mainType.toString() : null);
    this.validateForm.controls.subType.setValue(data.subType ? data.subType.toString() : null);
    this.validateForm.controls.description.setValue(data.description);
    this.validateForm.controls.supplierIds.setValue(Array.isArray(data.supplierList) ? data.supplierList.map(v => v.id) : []);
    this.validateForm.controls.manufacturerIds.setValue(Array.isArray(data.manufacturerList) ? data.manufacturerList.map(v => v.id) : []);

    if(data.supplierList){
      this.companyList1 = data.supplierList || [];
    }
    if(data.manufacturerList){
      this.companyList2 = data.manufacturerList || [];
    }
    if(data.mainType){
      this.getProductCategoryTypeList(2);
    }
  }

  // 展示信息提示框（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", "assetProduct", [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);
          }
        });
    }
  }
}
