import { Component, OnInit, ViewChild } from "@angular/core";
import { MainService } from "../../../services/main.service";
import { ToolService } from 'src/app/services/tool.service';
import { NzMessageService } from 'ng-zorro-antd';
import { Subject, forkJoin } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { OverlayScrollbarsComponent } from 'overlayscrollbars-ngx';

@Component({
  selector: "app-configuration-drug",
  templateUrl: "./configuration-drug.component.html",
  styleUrls: ["./configuration-drug.component.less"],
})
export class ConfigurationDrugComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;

  loading:boolean = false; //页面加载的loading
  btnLoading:boolean = false; //提交按钮的loading
  tabModalName:string = 'characteristics'; //当前选中的tab
  hosId = this.tool.getCurrentHospital().id; //当前院区

  // 配置
  configs:any = {};
  // 任务类型
  tasktype:any = {};
  constructor(private mainService: MainService,private tool: ToolService,private msg: NzMessageService) {}

  ngOnInit():void {
    this.activeDictionary = this.dictionaryKeyList[0];
    this.init();
		this.getDrugState();
		this.getMarkTypeList();
  }

  // 工单模式
  drugsModelList:any[] = [
    { label: '一单一码', value: 1 },
    { label: '一单多码', value: 2 },
  ];

	// 终点清点方式
	endClearingList:any[] = [
	  { label: '扫一扫清点', value: 1 },
	  { label: '数量核对清点', value: 2 },
	];

  // 手动填写
  drugsManualList:any[] = [];

  // 数据字典key列表
  dictionaryKeyList: any[] = [
    {
      name: '静配',
      value: 'drugsJpbag',
      postData: {
        drugsModel: undefined,//工单模式
        drugsCreateSign: [{ label:'是否开启', value: 0 }],//支持建单并签到
        drugsReceiveSign: [{ label:'是否开启', value: 0 }],//支持接单并签到
				drugsVerifyPharmacy: [{ label:'是否开启', value: 0 }],//收药是否验证发药科室
        drugsEndCountMethod: undefined,//终点清点方式
				drugsStartCheck: [{ label:'是否开启', value: 0 }],//起点科室支持核对
        drugsStartCheckScanIds: [],//起点核对方式
        drugsStartManual: undefined,//起点科室手动填写
        drugsStartPhoto: [{ label:'是否开启', value: 0 }],//起点科室支持拍照留存
        drugsEndCheck: [{ label:'是否开启', value: 0 }],//终点科室支持核对
        drugsEndCheckScanIds: [],//终点核对方式
				showPatientInfo: [{ label:'是否开启', value: 0 }],//药单显示患者
        drugsEndManual: undefined,//终点科室手动填写
        drugsEndPhoto: [{ label:'是否开启', value: 0 }],//终点科室支持拍照留存
        drugsScanHandover: [{ label:'是否开启', value: 0 }],//终点科室开通一扫交接
				showDrugsBagTypeCount: [{ label:'是否开启', value: 0 }],//是否显示药品数、种类数
				showDrugsBagDetails: [{ label:'是否开启', value: 0 }],//是否支持查看药品详情信息
				sendingMergeOrder: [{ label:'是否开启', value: 0 }],//待送达合并工单
				drugsResidueCreateOrder: [{ label:'是否开启', value: 0 }],//交接后，剩余药包是否建单
				urgentCreateOrder: [{ label:'是否开启', value: 0 }],//是否开启紧急配送建单
				autoCreate: [{ label:'是否开启', value: 0 }], // 是否自动建单
				autoCreateState: undefined, // 药品自动建单状态
				drugsCreateLimitMarkType: [], // 限制药单类型建单
			}
    },
    {
      name: '西药',
      value: 'drugsWestern',
      postData: {
        drugsModel: undefined,//工单模式
        drugsCreateSign: [{ label:'是否开启', value: 0 }],//支持建单并签到
        drugsReceiveSign: [{ label:'是否开启', value: 0 }],//支持接单并签到
				drugsVerifyPharmacy: [{ label:'是否开启', value: 0 }],//收药是否验证发药科室
        drugsEndCountMethod: undefined,//终点清点方式
				drugsStartCheck: [{ label:'是否开启', value: 0 }],//起点科室支持核对
        drugsStartCheckScanIds: [],//起点核对方式
        drugsStartManual: undefined,//起点科室手动填写
        drugsStartPhoto: [{ label:'是否开启', value: 0 }],//起点科室支持拍照留存
        drugsEndCheck: [{ label:'是否开启', value: 0 }],//终点科室支持核对
        drugsEndCheckScanIds: [],//终点核对方式
				showPatientInfo: [{ label:'是否开启', value: 0 }],//药单显示患者
        drugsEndManual: undefined,//终点科室手动填写
        drugsEndPhoto: [{ label:'是否开启', value: 0 }],//终点科室支持拍照留存
        drugsScanHandover: [{ label:'是否开启', value: 0 }],//终点科室开通一扫交接
        showDrugsBagTypeCount: [{ label:'是否开启', value: 0 }],//是否显示药品数、种类数
				showDrugsBagDetails: [{ label:'是否开启', value: 0 }],//是否支持查看药品详情信息
				sendingMergeOrder: [{ label:'是否开启', value: 0 }],//待送达合并工单
        drugsResidueCreateOrder: [{ label:'是否开启', value: 0 }],//交接后，剩余药包是否建单
        urgentCreateOrder: [{ label:'是否开启', value: 0 }],//是否开启紧急配送建单
				autoCreate: [{ label:'是否开启', value: 0 }], // 是否自动建单
				autoCreateState: undefined, // 药品自动建单状态
        drugsCreateLimitMarkType: [], // 限制药单类型建单
			}
    },
    {
      name: '退药',
      value: 'drugsReturn',
      postData: {
        drugsModel: undefined,//工单模式
        drugsCreateSign: [{ label:'是否开启', value: 0 }],//支持建单并签到
        drugsReceiveSign: [{ label:'是否开启', value: 0 }],//支持接单并签到
				drugsVerifyPharmacy: [{ label:'是否开启', value: 0 }],//收药是否验证发药科室
        drugsEndCountMethod: undefined,//终点清点方式
				drugsStartCheck: [{ label:'是否开启', value: 0 }],//起点科室支持核对
        drugsStartCheckScanIds: [],//起点核对方式
        drugsStartManual: undefined,//起点科室手动填写
        drugsStartPhoto: [{ label:'是否开启', value: 0 }],//起点科室支持拍照留存
        drugsEndCheck: [{ label:'是否开启', value: 0 }],//终点科室支持核对
        drugsEndCheckScanIds: [],//终点核对方式
				showPatientInfo: [{ label:'是否开启', value: 0 }],//药单显示患者
        drugsEndManual: undefined,//终点科室手动填写
        drugsEndPhoto: [{ label:'是否开启', value: 0 }],//终点科室支持拍照留存
        drugsScanHandover: [{ label:'是否开启', value: 0 }],//终点科室开通一扫交接
        showDrugsBagTypeCount: [{ label:'是否开启', value: 0 }],//是否显示药品数、种类数
				showDrugsBagDetails: [{ label:'是否开启', value: 0 }],//是否支持查看药品详情信息
        sendingMergeOrder: [{ label:'是否开启', value: 0 }],//待送达合并工单
        drugsResidueCreateOrder: [{ label:'是否开启', value: 0 }],//交接后，剩余药包是否建单
        urgentCreateOrder: [{ label:'是否开启', value: 0 }],//是否开启紧急配送建单
				autoCreate: [{ label:'是否开启', value: 0 }], // 是否自动建单
				autoCreateState: undefined, // 药品自动建单状态
        drugsCreateLimitMarkType: [], // 限制药单类型建单
			}
    },
    {
      name: '毒麻',
      value: 'drugsPoison',
      postData: {
        drugsModel: undefined,//工单模式
        drugsCreateSign: [{ label:'是否开启', value: 0 }],//支持建单并签到
        drugsReceiveSign: [{ label:'是否开启', value: 0 }],//支持接单并签到
				drugsVerifyPharmacy: [{ label:'是否开启', value: 0 }],//收药是否验证发药科室
        drugsEndCountMethod: undefined,//终点清点方式
				drugsStartCheck: [{ label:'是否开启', value: 0 }],//起点科室支持核对
        drugsStartCheckScanIds: [],//起点核对方式
        drugsStartManual: undefined,//起点科室手动填写
        drugsStartPhoto: [{ label:'是否开启', value: 0 }],//起点科室支持拍照留存
        drugsEndCheck: [{ label:'是否开启', value: 0 }],//终点科室支持核对
        drugsEndCheckScanIds: [],//终点核对方式
				showPatientInfo: [{ label:'是否开启', value: 0 }],//药单显示患者
        drugsEndManual: undefined,//终点科室手动填写
        drugsEndPhoto: [{ label:'是否开启', value: 0 }],//终点科室支持拍照留存
        drugsScanHandover: [{ label:'是否开启', value: 0 }],//终点科室开通一扫交接
        showDrugsBagTypeCount: [{ label:'是否开启', value: 0 }],//是否显示药品数、种类数
				showDrugsBagDetails: [{ label:'是否开启', value: 0 }],//是否支持查看药品详情信息
        sendingMergeOrder: [{ label:'是否开启', value: 0 }],//待送达合并工单
        drugsResidueCreateOrder: [{ label:'是否开启', value: 0 }],//交接后，剩余药包是否建单
        urgentCreateOrder: [{ label:'是否开启', value: 0 }],//是否开启紧急配送建单
				autoCreate: [{ label:'是否开启', value: 0 }], // 是否自动建单
				autoCreateState: undefined, // 药品自动建单状态
        drugsCreateLimitMarkType: [], // 限制药单类型建单
			}
    },
    {
      name: '中草药',
      value: 'drugsHerbal',
      postData: {
        drugsModel: undefined,//工单模式
        drugsCreateSign: [{ label:'是否开启', value: 0 }],//支持建单并签到
        drugsReceiveSign: [{ label:'是否开启', value: 0 }],//支持接单并签到
				drugsVerifyPharmacy: [{ label:'是否开启', value: 0 }],//收药是否验证发药科室
        drugsEndCountMethod: undefined,//终点清点方式
				drugsStartCheck: [{ label:'是否开启', value: 0 }],//起点科室支持核对
        drugsStartCheckScanIds: [],//起点核对方式
        drugsStartManual: undefined,//起点科室手动填写
        drugsStartPhoto: [{ label:'是否开启', value: 0 }],//起点科室支持拍照留存
        drugsEndCheck: [{ label:'是否开启', value: 0 }],//终点科室支持核对
        drugsEndCheckScanIds: [],//终点核对方式
				showPatientInfo: [{ label:'是否开启', value: 0 }],//药单显示患者
        drugsEndManual: undefined,//终点科室手动填写
        drugsEndPhoto: [{ label:'是否开启', value: 0 }],//终点科室支持拍照留存
        drugsScanHandover: [{ label:'是否开启', value: 0 }],//终点科室开通一扫交接
        showDrugsBagTypeCount: [{ label:'是否开启', value: 0 }],//是否显示药品数、种类数
				showDrugsBagDetails: [{ label:'是否开启', value: 0 }],//是否支持查看药品详情信息
        sendingMergeOrder: [{ label:'是否开启', value: 0 }],//待送达合并工单
        drugsResidueCreateOrder: [{ label:'是否开启', value: 0 }],//交接后，剩余药包是否建单
        urgentCreateOrder: [{ label:'是否开启', value: 0 }],//是否开启紧急配送建单
				autoCreate: [{ label:'是否开启', value: 0 }], // 是否自动建单
				autoCreateState: undefined, // 药品自动建单状态
        drugsCreateLimitMarkType: [], // 限制药单类型建单
			}
    },
  ];


	// 获取药品状态
	drugStateData:any = []
	getDrugState(){
		this.mainService.getDictionary("list", "drug_state").subscribe((data) => {
			this.drugStateData = data
		});
	}

  // 获取药单类型
	markTypeList:any = []
	getMarkTypeList(){
		this.mainService.getDictionary("list", "drugsbag_mark_type").subscribe((data) => {
			this.markTypeList = data
		});
	}

  // 点击数据字典key
  activeDictionary:any;
  clickDictionaryKey(item){
    this.activeDictionary = item;
    this.init();
  }

  // 修改起点科室支持核对
  changeDrugsStartCheck(e){
    console.log(e);
    if(!e[0].checked){
      this.activeDictionary.postData.drugsStartCheckScanIds = this.activeDictionary.postData.drugsStartCheckScanIds.map(v => ({...v, checked: false}));
      this.activeDictionary.postData.drugsStartManual = undefined;
      this.activeDictionary.postData.drugsStartPhoto[0].checked = false;
    }
  }

  // 修改终点科室支持核对
  changeDrugsEndCheck(e){
    console.log(e);
    if(!e[0].checked){
      this.activeDictionary.postData.drugsEndCheckScanIds = this.activeDictionary.postData.drugsEndCheckScanIds.map(v => ({...v, checked: false}));;
      this.activeDictionary.postData.drugsEndManual = undefined;
      this.activeDictionary.postData.drugsEndPhoto[0].checked = false;
      this.activeDictionary.postData.drugsScanHandover[0].checked = false;
    }
  }

  // 切换tab
  tabModal(tabModalName:string){
    this.tabModalName = tabModalName;
  }
  // 保存
  submitForm() {
    if(!this.tasktype.id){
      this.msg.create("warning", "请先配置任务类型！");
      return;
    }

    if(!this.activeDictionary.postData.drugsModel){
      this.msg.create("warning", "请选择工单模式！");
      return;
    }

    if(this.activeDictionary.postData.drugsStartCheck[0].checked && !this.activeDictionary.postData.drugsStartCheckScanIds.filter(v => v.checked).length){
      this.msg.create("warning", "请选择起点科室的核对方式！");
      return;
    }

    if(!this.activeDictionary.postData.drugsEndCheck[0].checked){
      this.msg.create("warning", "终点科室支持核对必填！");
      return;
    }

    if(this.activeDictionary.postData.drugsEndCheck[0].checked && !this.activeDictionary.postData.drugsEndCheckScanIds.filter(v => v.checked).length){
      this.msg.create("warning", "请选择终点科室的核对方式！");
      return;
    }

		if(this.activeDictionary.postData.drugsModel==2 && !this.activeDictionary.postData.drugsEndCountMethod){
		  this.msg.create("warning", "请选择终点清点方式！");
		  return;
		}

    let postData:any = {
      id: this.configs.id,
      taskType: this.tasktype.id,
      hosId: this.hosId,
      drugsModel: this.activeDictionary.postData.drugsModel || undefined,
			drugsEndCountMethod: this.activeDictionary.postData.drugsEndCountMethod || undefined,
      drugsCreateSign: this.activeDictionary.postData.drugsCreateSign[0].checked ? 1 : 0,
      drugsReceiveSign: this.activeDictionary.postData.drugsReceiveSign[0].checked ? 1 : 0,
			drugsVerifyPharmacy: this.activeDictionary.postData.drugsVerifyPharmacy[0].checked ? 1 : 0,
      drugsStartCheck: this.activeDictionary.postData.drugsStartCheck[0].checked ? 1 : 0,
      drugsStartCheckScanIds: this.activeDictionary.postData.drugsStartCheckScanIds.filter(v => v.checked).map(v => v.value).toString() || undefined,
      drugsStartManual: this.activeDictionary.postData.drugsStartManual ? { id: this.activeDictionary.postData.drugsStartManual } : undefined,
      drugsStartPhoto: this.activeDictionary.postData.drugsStartPhoto[0].checked ? 1 : 0,
      drugsEndCheck: this.activeDictionary.postData.drugsEndCheck[0].checked ? 1 : 0,
      drugsEndCheckScanIds: this.activeDictionary.postData.drugsEndCheckScanIds.filter(v => v.checked).map(v => v.value).toString() || undefined,
      drugsEndManual: this.activeDictionary.postData.drugsEndManual ? { id: this.activeDictionary.postData.drugsEndManual } : undefined,
      drugsEndPhoto: this.activeDictionary.postData.drugsEndPhoto[0].checked ? 1 : 0,
      drugsScanHandover: this.activeDictionary.postData.drugsScanHandover[0].checked ? 1 : 0,
			showPatientInfo: this.activeDictionary.postData.showPatientInfo[0].checked ? 1 : 0,
			showDrugsBagTypeCount: this.activeDictionary.postData.showDrugsBagTypeCount[0].checked ? 1 : 0,
			showDrugsBagDetails: this.activeDictionary.postData.showDrugsBagDetails[0].checked ? 1 : 0,
			sendingMergeOrder: this.activeDictionary.postData.sendingMergeOrder[0].checked ? 1 : 0,
			drugsResidueCreateOrder: this.activeDictionary.postData.drugsResidueCreateOrder[0].checked ? 1 : 0,
			urgentCreateOrder: this.activeDictionary.postData.urgentCreateOrder[0].checked ? 1 : 0,
			autoCreate: this.activeDictionary.postData.autoCreate[0].checked ? 1 : 0,
			autoCreateState:{
				id:this.activeDictionary.postData.autoCreateState || undefined
			},
      drugsCreateLimitMarkType: this.activeDictionary.postData.drugsCreateLimitMarkType.length ? this.activeDictionary.postData.drugsCreateLimitMarkType.toString() : undefined,
		};
    this.btnLoading = true;
    this.mainService
      .simplePost("addData", "taskTypeConfig", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        if (result.status == 200) {
          this.getConfig();
        }
      });
  }

  //初始化
  init() {
    this.loading = true;
    let drugs_bag_check_scan_type$ = this.mainService.getDictionary('list', 'drugs_bag_check_scan_type', true);
    let drugs_bag_manual_type$ = this.mainService.getDictionary('list', 'drugs_bag_manual_type', true);
    forkJoin(drugs_bag_check_scan_type$, drugs_bag_manual_type$).subscribe((data:any[]) => {
      let drugs_bag_check_scan_type = data[0] || [];
      let drugs_bag_manual_type = data[1] || [];

      this.activeDictionary.postData.drugsStartCheckScanIds = drugs_bag_check_scan_type.map(v => ({ label:v.name, value: v.id }));
      this.activeDictionary.postData.drugsEndCheckScanIds = drugs_bag_check_scan_type.map(v => ({ label:v.name, value: v.id }));
      this.drugsManualList = drugs_bag_manual_type.map(v => ({ label:v.name, value: v.id }));

      this.getTaskType();
    })
  }

  //获取任务类型
  getTaskType() {
    this.loading = true;
    let postData = {
      idx: 0,
      sum: 1,
      taskType: {
        simpleQuery: true,
        hosId: {
          id: this.hosId
        },
        ordinaryField: {
          key: 'ordinary_field',
          value: this.activeDictionary.value,
        }
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "taskType", postData)
      .subscribe((result) => {
        this.loading = false;
        if (result.status == 200) {
          this.tasktype = result.list[0] || {};
          this.getConfig();
        }
      });
  }

  // 获取配置
  getConfig() {
    this.loading = true;
    let postData = {
      idx: 0,
      sum: 1,
      taskTypeConfig: {
        taskTypeDTO: {
          hosId: {
            id: this.hosId
          },
          ordinaryField: {
            key: 'ordinary_field',
            value: this.activeDictionary.value,
          }
        }
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "taskTypeConfig", postData)
      .subscribe((result) => {
        this.loading = false;
        if (result.status == 200) {
          this.configs = result.list[0] || {};
          this.activeDictionary.postData.drugsModel = this.configs.drugsModel || undefined;
					 this.activeDictionary.postData.drugsEndCountMethod = this.configs.drugsEndCountMethod || undefined;
					this.activeDictionary.postData.drugsCreateSign[0].checked = this.configs.drugsCreateSign == 1;
          this.activeDictionary.postData.drugsReceiveSign[0].checked = this.configs.drugsReceiveSign == 1;
					this.activeDictionary.postData.drugsVerifyPharmacy[0].checked = this.configs.drugsVerifyPharmacy == 1;
          this.activeDictionary.postData.drugsStartCheck[0].checked = this.configs.drugsStartCheck == 1;
          this.activeDictionary.postData.drugsStartCheckScanIds = this.activeDictionary.postData.drugsStartCheckScanIds.map(v => ({...v, checked: (this.configs.drugsStartCheckScanIds || '').split(',').includes(v.value.toString())}));
          this.activeDictionary.postData.drugsStartManual = this.configs.drugsStartManual ? this.configs.drugsStartManual.id : undefined;
          this.activeDictionary.postData.drugsStartPhoto[0].checked = this.configs.drugsStartPhoto == 1;

          this.activeDictionary.postData.drugsEndCheck[0].checked = this.configs.drugsEndCheck == 1;
          this.activeDictionary.postData.drugsEndCheckScanIds = this.activeDictionary.postData.drugsEndCheckScanIds.map(v => ({...v, checked: (this.configs.drugsEndCheckScanIds || '').split(',').includes(v.value.toString())}));
          this.activeDictionary.postData.drugsEndManual = this.configs.drugsEndManual ? this.configs.drugsEndManual.id : undefined;
          this.activeDictionary.postData.drugsEndPhoto[0].checked = this.configs.drugsEndPhoto == 1;
          this.activeDictionary.postData.drugsScanHandover[0].checked = this.configs.drugsScanHandover == 1;
					this.activeDictionary.postData.showPatientInfo[0].checked = this.configs.showPatientInfo == 1;
					this.activeDictionary.postData.showDrugsBagTypeCount[0].checked = this.configs.showDrugsBagTypeCount == 1;
					this.activeDictionary.postData.showDrugsBagDetails[0].checked = this.configs.showDrugsBagDetails == 1;
					this.activeDictionary.postData.sendingMergeOrder[0].checked = this.configs.sendingMergeOrder == 1;
					this.activeDictionary.postData.drugsResidueCreateOrder[0].checked = this.configs.drugsResidueCreateOrder == 1;
					this.activeDictionary.postData.urgentCreateOrder[0].checked = this.configs.urgentCreateOrder == 1;
					this.activeDictionary.postData.autoCreate[0].checked = this.configs.autoCreate == 1;
					this.activeDictionary.postData.autoCreateState = this.configs.autoCreateState && this.configs.autoCreateState.id || undefined;
          this.activeDictionary.postData.drugsCreateLimitMarkType = this.configs.drugsCreateLimitMarkType ? this.configs.drugsCreateLimitMarkType.split(',').map(v => +v) : [];
				}
      });
  }

  // 是否自动建单
  changeAutoCreate(e, item){
    item.postData.autoCreateState = null;
    item.postData.drugsCreateLimitMarkType = [];
  }
}
