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-consumable",
  templateUrl: "./assets-consumable.component.html",
  styleUrls: ["./assets-consumable.component.less"],
})
export class AssetsConsumableComponent 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] === 'assetProduct'){
        this.getAssetProductList(v[0], v[2]);
      }
    });
    this.currentHospital = this.tool.getCurrentHospital();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getList(1);
    this.getAssetProductList('search', '');
    this.getAssetProductList('add', '');
  }

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

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

  // 表格数据
  searchDto: any = {};
  productDto:any = {};
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      consumable: {
        hosId: this.currentHospital.id,
        quoteOther: 0,
        ...this.searchDto,
      },
    };
    data.consumable.status = data.consumable.status ? { id: data.consumable.status } : undefined;
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "consumable", 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.productDto = {};
    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();
  }

  // 编辑
  edit(e, data) {
    e.stopPropagation();
    console.log(data);
    this.initForm();
    this.modelName = "编辑";
    this.add = false;
    this.modal = true;
    this.coopData = data;
    this.productDto = {
      name: data.name,
      model: data.model,
      unit: data.unit,
    }
    this.validateForm.controls.productId.setValue(data.productId);
    this.validateForm.controls.supplierId.setValue(data.supplierId);
    this.validateForm.controls.stock.setValue(data.stock);
    this.validateForm.controls.price.setValue(data.price);

    if(data.assetProductDTO){
      this.companyList = data.assetProductDTO.supplierList || [];
    }

    this.getAssetProductList('add', '', true);
  }

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      productId: [null, [Validators.required]],
      supplierId: [null, [Validators.required]],
      stock: [0, [Validators.required]],
      price: [0, [Validators.required]],
    });
  }

  // 边输边搜节流阀
  isLoading = false;
  changeInp(type, model, e) {
    this.isLoading = true;
    this.changeInpSubject.next([type, model, e]);
  }
	
	// 日志列表
	listLogOfData: any[] = []; //日志数据
	pageLogIndex: number = 1; //日志当前页码
	pageLogSize: number = 10; //日志每页展示条数
	listLogLength: number = 10; //日志总数据量
	loading2:boolean = false;
	getLogList(type) {
	  if (type == 1) {
	    this.pageLogIndex = 1;
	  }
	  let data = {
	    idx: this.pageLogIndex - 1,
	    sum: this.pageLogSize,
	    assetConsumablesHistory: {
	      assetConsumablesId: this.itemData.id,
	    },
	  };
	  this.loading2 = true;
	  this.mainService
	    .getFetchDataList("simple/data", "assetConsumablesHistory", data)
	    .subscribe((data) => {
	      this.loading2 = false;
	      if (data.status == 200) {
					this.logModal = true
	        this.listLogOfData = data.list;
	        this.listLogLength = data.totalNum;
	      }else{
	        this.message.error(data.msg || "请求数据失败");
	      }
	    });
	}
	
	// 查看日志
	itemData:any = {};
	logModal:boolean = false;
	showLogModal(e, data){
		this.itemData = data;
		this.getLogList(1)
	}
	
	// 关闭日志
	hideModal() {
	  this.logModal = false;
	}
	
  // 获取产品列表
  assetProductsearchList: any = [];
  assetProductaddList: any = [];
  consumableId:any; // 大类为维修耗材id
  async getAssetProductList(type, keyword, init = false) {
    if(!this.consumableId){
      let result = await this.getProductCategoryTypeList(1);
      let productCategoryTypeList = result.list || []; // 获取大类
      // 大类为维修耗材
      let consumable = productCategoryTypeList.find(v => v.value == '维修耗材');
      if(!consumable){
        this['assetProduct' + type + 'List'] = [];
        this.isLoading = false;
        return;
      }
      this.consumableId = consumable.id;
    }
    let postData:any = {
      assetProduct: {
        name: keyword,
        hosId: this.currentHospital.id,
        mainType: this.consumableId,
      },
      idx: 0,
      sum: 20,
    };
    console.log(this.coopData)
    this.mainService
      .getFetchDataList("simple/data", "assetProduct", postData)
      .subscribe((data) => {
        this.isLoading = false;
        if(init){
          // 回显
          let assetProductList = data.list || [];
          let flag = assetProductList.some(v => v.id == this.coopData.productId);
          if(!flag){
            assetProductList.unshift(this.coopData.assetProductDTO);
            this['assetProduct' + type + 'List'] = assetProductList;
          }
        }else{
          this['assetProduct' + type + 'List'] = data.list || [];
        }
      });
  }

  //获取大类
  getProductCategoryTypeList(level:number) {
    let postData = {
      dictionaryTree: {
        deleted: 0,
        level: 1,
        key: 'product_category_type',
      },
      idx: 0,
      sum: 9999,
    };
    return this.mainService.getFetchDataList("simple/data", "dictionaryTree", postData).toPromise();
  }

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

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

  // 新增/编辑表单提交
  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 = {
        consumable: {
          hosId: this.currentHospital.id,
          name: this.productDto.name,
          model: this.productDto.model,
          unit: this.productDto.unit,
          productId: this.validateForm.value.productId,
          supplierId: this.validateForm.value.supplierId,
          stock: this.validateForm.value.stock,
          price: this.validateForm.value.price,
        }
      };
    } else {
      //编辑
      postData = {
        consumable:{
          ...this.coopData,
          ...{
            hosId: this.currentHospital.id,
            name: this.productDto.name,
            model: this.productDto.model,
            unit: this.productDto.unit,
            productId: this.validateForm.value.productId,
            supplierId: this.validateForm.value.supplierId,
            stock: this.validateForm.value.stock,
            price: this.validateForm.value.price,
          }
        }
      };
    }
    this.mainService
      .coopData("addData", "consumable", 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", "consumable", [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);
          }
        });
    }
  }
}
