import { Component, OnInit } from "@angular/core";
import { MainService } from 'src/app/services/main.service';
import { ToolService } from 'src/app/services/tool.service';
import { NzMessageService } from 'ng-zorro-antd';

@Component({
  selector: "app-blood-products-config",
  templateUrl: "./blood-products-config.component.html",
  styleUrls: ["./blood-products-config.component.less"],
})
export class BloodProductsConfigComponent implements OnInit {
  loading:boolean = false; //页面加载的loading
  btnLoading:boolean = false; //提交按钮的loading
  tabModalName:string = 'characteristics'; //当前选中的tab
  hosId = this.tool.getCurrentHospital().id; //当前院区
  // 交接方式
  handoverMode:any;
  handoverModes:any[] = [];
  // 核对方式
  checkModes:any[] = [];
  // 签到方式
  checkInModes:any[] = [];
  // 自动关单
  automaticCustomsOrders:any[] = [];
  // 自动建单
  autoCreateOrders:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否支持领取证
  certificates:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否支持取消发血
  cancelBloods:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否必填交接人
  cancelBloodHandovers:any[] = [
    {label:'是否必填交接人',value: 0}
  ];
  // 是否指定人派单
  autoSendUsers:any[] = [
    {label:'是否指定人派单',value: 0}
  ];
  // 是否根据开通科室建单
  autoDepts:any[] = [
    {label:'是否根据开通科室建单',value: 0}
  ];
  // 是否根据起点科室建单
  autoDeptLimits:any[] = [
    {label:'是否根据起点科室建单',value: 0}
  ];
  // 是否支持按钮送达交接
  delivery:any[] = [
    {label:'是否开启',value: 0}
  ];
	// 待送达合并工单
	sendingMergeOrder:any[] = [
	  {label:'是否开启',value: 0}
	];
  // 选择起点科室
  limitDeptIds:any = [];
  // 配置
  configs:any = {};
  // 血制品任务类型
  tasktype:any = {};
  constructor(private mainService: MainService,private tool: ToolService,private msg: NzMessageService) {}

  ngOnInit():void {
    // todo
    this.getCertificate();
    this.getHandoverModes();
    this.getCheckModes();
    this.getCheckInModes();
  }

  deptList = []; //科室列表
  dLoading = false;
  dSearchText = '';
  //获取科室列表
  getDeptList(flag?, search = "", isInit = false) {
    if (!flag) {
      return;
    }
    let hosIds = this.hosId;
    let postData = {
      idx: 0,
      sum: 9999,
      department: { hospital: { id: hosIds }, dept: search, searchType: 1 },
    };
    this.dLoading = true;
    this.dSearchText = search;
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((data) => {
        if (this.dSearchText == search) {
          this.dLoading = false;
          if (data.status == 200) {
            this.deptList = data.list;
            if(isInit){
              this.limitDeptIds = this.configs.limitDeptIds ? this.configs.limitDeptIds.split(',') : [];
            }
          }
        }
      });
  }

  // 搜索科室列表
  searchDeptList(e) {
    this.getDeptList(true, e);
  }

  // 切换tab
  tabModal(tabModalName:string){
    this.tabModalName = tabModalName;
  }
  // 修改是否自动建单
  changeAutoCreateOrders(e){
    console.log(e);
    if(!e[0].checked){
      this.autoDepts[0].checked = false;
      this.autoDeptLimits[0].checked = false;
      this.limitDeptIds = [];
    }
  }
  // 修改是否支持领取证
  changeCertificates(e){
    console.log(e);
    if(!e[0].checked){
      this.certificate = null;
    }
  }
  // 修改是否支持取消发血
  changeCancelBloods(e){
    console.log(e);
    if(!e[0].checked){
      this.cancelBloodHandovers[0].checked = false;
    }
  }
  // 修改changeAutoDeptLimits
  changeAutoDeptLimits(e){
    console.log(e);
    if(!e[0].checked){
      this.limitDeptIds = [];
    }
  }
  // 保存
  submitForm() {
    console.log(this.limitDeptIds)
    if(!this.tasktype.id){
      this.msg.create("warning", "请先配置血制品任务类型！");
      return;
    }
    if(!this.handoverMode){
      this.msg.create("warning", "请选择交接方式！");
      return;
    }
    if(!this.radioCheckModesValue){
      this.msg.create("warning", "请选择核对方式！");
      return;
    }
    if(this.autoDeptLimits[0].checked && !this.limitDeptIds.length){
      this.msg.create("warning", "请选择起点科室！");
      return;
    }
    if(this.certificates[0].checked && !this.certificate){
      this.msg.create("warning", "请选择领取证号类型！");
      return;
    }
    let signTypeIds = this.checkInModes.filter(v => v.checked).map(v => v.value).toString();
    let closeTypeIds = this.automaticCustomsOrders.filter(v => v.checked).map(v => v.value).toString();
    let postData:any = {
      id: this.configs.id,
      taskType: this.tasktype.id,
      hosId: this.hosId,
      autoCreate: this.autoCreateOrders[0].checked ? 1 : 0,
      delivery: this.delivery[0].checked ? 1 : 0,
      autoSendUser: this.autoSendUsers[0].checked ? 1 : 0,
      autoDept: this.autoDepts[0].checked ? 1 : 0,
      autoDeptLimit: this.autoDeptLimits[0].checked ? 1 : 0,
      limitDeptIds: String(this.limitDeptIds),
      handoverType: {id: this.handoverMode},
      checkType: {id: this.radioCheckModesValue},
      signTypeIds: signTypeIds || undefined,
      closeTypeIds: closeTypeIds || undefined,
      useTakeCode: this.certificates[0].checked ? 1 : 0,
      takeCodeType: {id: this.certificate},
      cancelBlood: this.cancelBloods[0].checked ? 1 : 0,
      cancelBloodHandover: this.cancelBloodHandovers[0].checked ? 1 : 0,
    };
		if(this.sendingMergeOrder[0].checked){
			postData.sendingMergeOrder = 1
		}else{
			delete postData.sendingMergeOrder
		}
    console.log(postData);
    this.btnLoading = true;
    this.mainService
      .simplePost("addData", "taskTypeConfig", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        if (result.status == 200) {
          this.getConfig();
        }
      });
  }

  //获取是否支持领取证-数据字典
  certificateList:any[] = [];
  certificate:any = null;
  getCertificate() {
    this.mainService.getDictionary("list", "blood_config_take_code_type").subscribe((data) => {
      this.certificateList = data || [];
    });
  }

  //获取交接方式
  getHandoverModes() {
    this.mainService.getDictionary("list", "ttconfig_handover_type").subscribe((data) => {
      this.handoverModes = data;
      this.handoverMode = data[0].id;
    });
  }
  //获取核对方式
  getCheckModes() {
    this.mainService.getDictionary("list", "ttconfig_check_type").subscribe((data) => {
      this.checkModes = data.map(v => ({label:v.name, value: v.id}));
    });
  }
  //获取签到方式
  getCheckInModes() {
    this.loading = true;
    this.mainService.getDictionary("list", "ttconfig_sign_type").subscribe((data) => {
      this.checkInModes = data.map(v => ({label:v.name, value: v.id}));
      this.getAutomaticCustomsOrders();
    });
  }
  //获取自动关单
  getAutomaticCustomsOrders() {
    this.mainService.getDictionary("list", "ttconfig_close_type").subscribe((data) => {
      this.automaticCustomsOrders = data.map(v => ({label:v.name, value: v.id}));
      this.getTaskType();
    });
  }
  //获取任务类型
  getTaskType() {
    let postData = {
      idx: 0,
      sum: 10,
      taskType: {
        simpleQuery: true,
        hosId: {
          id: this.hosId
        },
        ordinaryField: {
          key: 'ordinary_field',
          value: 'blood'
        }
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "taskType", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.tasktype = result.list[0] || {};
          this.getConfig();
        }
      });
  }
  // 获取配置
  radioCheckModesValue = '';
  getConfig() {
    this.loading = true;
    let postData = {
      idx: 0,
      sum: 10,
      taskTypeConfig: {
        taskTypeDTO: {
          hosId: {
            id: this.hosId
          },
          ordinaryField: {
            key: 'ordinary_field',
            value: 'blood'
          }
        }
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "taskTypeConfig", postData)
      .subscribe((result) => {
        this.loading = false;
        if (result.status == 200) {
          this.configs = result.list[0] || {};
          this.handoverMode = this.configs.handoverType?this.configs.handoverType.id:undefined;
          this.radioCheckModesValue = this.configs.checkType.id;
          this.autoCreateOrders[0].checked = this.configs.autoCreate == 1;
          this.delivery[0].checked = this.configs.delivery == 1;
					if(this.configs.sendingMergeOrder){
						this.sendingMergeOrder[0].checked = this.configs.sendingMergeOrder == 1
					}
          this.autoSendUsers[0].checked = this.configs.autoSendUser == 1;
          this.autoDepts[0].checked = this.configs.autoDept == 1;
          this.autoDeptLimits[0].checked = this.configs.autoDeptLimit == 1;

          this.certificates[0].checked = this.configs.useTakeCode == 1;
          this.certificate = this.configs.takeCodeType?this.configs.takeCodeType.id:undefined;
          this.cancelBloods[0].checked = this.configs.cancelBlood == 1;
          this.cancelBloodHandovers[0].checked = this.configs.cancelBloodHandover == 1;

          this.getDeptList(true, '', true);

          if(this.configs.signTypeIds){
            let ids = this.configs.signTypeIds.split(',');
            this.checkInModes = this.checkInModes.map(v => ({...v, checked: ids.includes(v.value.toString())}));
          }

          if(this.configs.closeTypeIds){
            let ids = this.configs.closeTypeIds.split(',');
            this.automaticCustomsOrders = this.automaticCustomsOrders.map(v => ({...v, checked: ids.includes(v.value.toString())}));
          }
        }
      });
  }
}

