import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { MainService } from "../../services/main.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { FormBuilder, FormGroup } from "@angular/forms";
import { ToolService } from "../../services/tool.service";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { NzMessageService } from "ng-zorro-antd";
import { format, startOfSecond } from 'date-fns';
import { ColorEvent } from 'ngx-color';
import Big from 'big.js';
export interface Data {
  id: number;
  name: string;
  age: number;
  address: string;
}
@Component({
  selector: "app-task-type-management",
  templateUrl: "./task-type-management.component.html",
  styleUrls: ["./task-type-management.component.less"],
})
export class TaskTypeManagementComponent implements OnInit {
  sortableTimer = null;
  constructor(
    private mainService: MainService,
    private route: ActivatedRoute,
    private msg: NzMessageService,
    private fb: FormBuilder,
    private tool: ToolService
  ) {
    this.allTaskTypeOptions = {
      onUpdate: (event: any) => {
        // 触发一次排序
        clearTimeout(this.sortableTimer);
        this.sortableTimer = setTimeout(() => {
          console.log(this.allTaskType);
          let postData = {
            orders: [],
          };
          postData.orders = this.allTaskType.map((item, i) => {
            return {
              id: item.id,
              orders: i,
            };
          });
          this.mainService
            .coopConfig("setOrders", postData)
            .subscribe((result) => {});
        }, 500);
      },
    };
  }
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  taskTypeLoading = false; //任务类型加载中
  allTaskTypeOptions: any;
  tabModalName = "jcxx"; //详情tab字段
  responseTimeType: boolean = false; //规则信息-响应时间字段
  arriveTimeType: boolean = false; //规则信息-到达时间字段
  implementTimeType: boolean = false; //规则信息-执行时间字段
  basicsType: boolean = false; //规则信息-基础字段
  totalType: boolean = false; //规则信息-总计字段
  transportShow = false; //运送过程-详情模态框展示/隐藏
  transportTitle = ""; //运送过程-详情模态框-标题
  addItemData: Array<any> = []; //运送过程-新增简单数据
  listOfData: Array<any> = [];
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数
  index = 0;
  sums = 10;
  styleType = true;
  //基础信息请求参数
  hosId; //当前院区
  allAssociation: Array<any>; //关联类型
  allStatisticsDateType: Array<any>; //统计分类
  allRelatedBusiness: Array<any>; //关联业务
  allTaskType = []; //任务类型列表
  allTaskTypeShow; //任务类型列表选择标识
  allScheduleClass; //班次列表
  //基础信息详情字段
  taskName; //任务名称
  urgeWeight:any; //急单权重
  commonWeight:any; //普单权重
  countRemark:string = ''; //统计备注
	scorePrice:any; //积分单价
  association: any = {
    id: "",
    value: "",
  }; //关联类型
  statisticsDateType: any = {
    id: "",
    value: "",
  }; //统计分类
  relatedBusiness: any = {
    id: "",
    value: "",
  }; //关联业务
  simultaneousNumber; //同时接单数
  allowUrgent = "1"; //是否加急
  urgentAudit = "0"; //加急是否审核
  autoFlag = "0"; //调度台是否可以新建工单
	deliveryUserCreate = "0"; //是否配送人员可以新建工单
  isRemand = "0"; //是否开通自动送回
  remandTypeId = null; //开通自动送回,选择的任务类型
  defaultNullDeptId = null; //空单默认科室-标本配送
  specialCloseButton = "0"; //是否开通自动送回
  executeSwitch = 0;
  closeOrderCheckDept = 0; //是否需要验证科室码
  bindTrans = "0"; //是否关联数据
  appointmentBuildFlag = "0"; //护士端是否允许预约建单,患者陪检业务
  appointmentBuildFlagZy = "0"; //护士端是否允许预约建单,患者其他服务
  followFlag = "0"; //护士端是否能标记重点关注
  isAccompany = "0"; //是否需要医护陪同检查
  isHalfInspect = "0"; //是否半陪检
  isMoreDept = "0"; //关联检查是否允许多个科室
  isRepeatCreateOder = "2"; //限制重复建单
  isDrugsCreateTime = "0"; //药品自动建单
  isOneClickSignIn = "0"; //是否允许一键签收
  isDigitalHandover = "0"; //是否允许数字交接
  reserveSwitch = "0"; //是否预定工单
  reserveUserSwitch = "0"; //是否需要填写工号
  reserveType = "1"; //是否限制业务发起时间
  reserveTypes:any = []; //是否限制业务发起时间-字典
  reserveDate = null; //是否限制业务发起时间-时间
  reserveMsg = ''; //是否限制业务发起时间-提示
  // wechatFocusSwitch = "0"; //支助中心端是否能标记重点关注
  isRemarks: any = "0"; //是否需要备注信息(其他类型)
  remarks = ""; //备注信息提示用语(其他类型)
  quickRemarks = ""; //工单备注快捷选择输入所有(其他类型)

  quickRemarkses = []; //工单备注快捷选择输入第二条-第N条(其他类型)
  quickRemarksModal = false; //备注快捷选择输入弹窗
  quickRemarksAdd = false; //备注快捷选择输入弹窗新增还是编辑
  validateForm: FormGroup; //新增/编辑备注快捷选择输入
  isAddQRemarks = true; //添加新的备注快捷选择输入是否禁用
  qRemarksId = 1; //备注快捷选择输入自增id

  leadTime: any = 20; //提前生效时间，默认20分钟

  actionsModal = false; //动作弹窗
  actionsAdd = false; //动作弹窗新增还是编辑
  validateActionForm: FormGroup; //新增/编辑动作
  actionses = []; //动作第二条-第N条(其他类型)
  isAddActions = true; //添加新的动作是否禁用
  actionsId = 1; //动作自增id

  logRemarkses = []; //工单备注快捷选择输入第二条-第N条(其他类型)
  logRemarksModal = false; //备注快捷选择输入弹窗
  logRemarksAdd = false; //备注快捷选择输入弹窗新增还是编辑
  validateLogRemarksForm: FormGroup; //新增/编辑备注快捷选择输入
  isAddLRemarks = true; //添加新的备注快捷选择输入是否禁用
  lRemarksId = 1; //备注快捷选择输入自增id
	colorConfig:any = {
		hex: '#333',
	}
	colorShow:boolean = false;
  formatterDollar = (value) => Number(value);
  // 护士端是否允许预约建单，选中
  appointmentBuildClick() {
    this.leadTime = 20;
  }
  //规则信息
  integralDetailedRulesData; //规则信息列表字段
  integralDetailedRulesDatas = {
    integralDetailedRulesData: [
      {
        type: 1, //紧急
        responseTime: 0, //响应时长
        responseScore: 0, //积分
        level1ResponseTimeoutTime: 0, //一级超时
        level1ResponseTimeoutDeduct: 0, //一级扣分
        level2ResponseTimeoutTime: 0, //二级超时
        level2ResponseTimeoutDeduct: 0, //二级扣分
        level3ResponseTimeoutTime: 0, //三级超时
        level3ResponseTimeoutDeduct: 0, //三级扣分
        arriveTime: 0, //配送人员时长
        arriveScore: 0, //积分
        level1ArriveTimeoutTime: 0, //一级超时
        level1ArriveTimeoutDeduct: 0, //一级扣分
        level2ArriveTimeoutTime: 0, //二级超时
        level2ArriveTimeoutDeduct: 0, //二级扣分
        level3ArriveTimeoutTime: 0, //三级超时
        level3ArriveTimeoutDeduct: 0, //三级扣分
        executeTime: 0, //配送人员时长
        executeScore: 0, //积分
        level1ExecuteTimeoutTime: 0, //一级超时
        level1ExecuteTimeoutDeduct: 0, //一级扣分
        level2ExecuteTimeoutTime: 0, //二级超时
        level2ExecuteTimeoutDeduct: 0, //二级扣分
        level3ExecuteTimeoutTime: 0, //三级超时
        level3ExecuteTimeoutDeduct: 0, //三级扣分
        basicsScore: 0, //基础积分
        deptsScore: 0, //多个科室追加分
        sumTime: 0, //总时长
        sumScore: 0, //总积分
      },
      {
        type: 2, //普通
        responseTime: 0, //响应时长
        responseScore: 0, //积分
        level1ResponseTimeoutTime: 0, //一级超时
        level1ResponseTimeoutDeduct: 0, //一级扣分
        level2ResponseTimeoutTime: 0, //二级超时
        level2ResponseTimeoutDeduct: 0, //二级扣分
        level3ResponseTimeoutTime: 0, //三级超时
        level3ResponseTimeoutDeduct: 0, //三级扣分
        arriveTime: 0, //配送人员时长
        arriveScore: 0, //积分
        level1ArriveTimeoutTime: 0, //一级超时
        level1ArriveTimeoutDeduct: 0, //一级扣分
        level2ArriveTimeoutTime: 0, //二级超时
        level2ArriveTimeoutDeduct: 0, //二级扣分
        level3ArriveTimeoutTime: 0, //三级超时
        level3ArriveTimeoutDeduct: 0, //三级扣分
        executeTime: 0, //配送人员时长
        executeScore: 0, //积分
        level1ExecuteTimeoutTime: 0, //一级超时
        level1ExecuteTimeoutDeduct: 0, //一级扣分
        level2ExecuteTimeoutTime: 0, //二级超时
        level2ExecuteTimeoutDeduct: 0, //二级扣分
        level3ExecuteTimeoutTime: 0, //三级超时
        level3ExecuteTimeoutDeduct: 0, //三级扣分
        basicsScore: 0, //基础积分
        deptsScore: 0, //多个科室追加分
        sumTime: 0, //总时长
        sumScore: 0, //总积分
      },
    ],
  };
  //运送过程
  hosName; //院区名称
  departmentData; //默认科室
  checkoutData; //检验方式
  depaShow = false; //固定科室选择字段
  depaShow1 = false; //固定科室范围选择字段
  depaShow2 = false; //自助填写选择字段
  depaShow3 = false; //标本自动建单
  depaShow4 = false; //固定科室类型
  depaShow5 = false; //静配自动建单
  depaShow6 = false; //药品自动建单
  scheduleClassChecked; //已选班次
  ClassChecked = false; //班次选择模态框字段
  classChecked; //班次选择
  indexs = 0; //流程索引
  disables = false; //流程选择
  carryingCourses = []; //运送流程参数
  departmentName; //流程名称
  departmentIds; //固定科室选择字段
  departmentTypeIds; //固定科室选择字段
  departmentStrategy: any = {
    id: null,
    idv: null,
    value: null,
  }; //默认科室字段
  checkoutMethod = {
    //检验方式字段
    id: null,
  };
  addEndDeptIds: any = []; //自动(手动)建单追加终点科室
  autoAddDeptSwitch: any = false; //自动建单追加终点科室开关
  handAddDeptSwitch: any = false; //手动建单追加终点科室开关
  bagOrderSwitch: any = false; //根据对接数据自动建单(静配,药品)
  createRuleConfiguration = []; //自动建单字段
  levelData; //护理级别字段
  specimen_types = false; //标本选择显示隐藏字段
  specimenData; //标本字段
  // specimenDataNow;//标本可选列表字段
  specimens; //标本选择字段
  specimenList;
  specimen_index; //标本选择索引
  departmenShow = false; //固定科室范围
  departments; //固定科室范围选择字段
  //开通科室-列表参数
  isAllDisplayDataChecked = false;
  isOperating = false;
  isIndeterminate = false;
  listOfDisplayData: Data[] = [];
  listOfAllData: Data[] = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  numberOfChecked = 0;
  taskData; //提交数据
  courseData; //科室类型
  courseListData; //科室列表数据
  courseListDataAll = []; //科室列表数据(所有)
  courseTypeListDataAll; //科室类型列表数据(所有)
  deptIds; //开通科室选择字段
  deptName;
  deptPcode;
  deptType;

  mrksType; //默认科室type
  jyfsType; //检验方式type

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  errorInfo: string; //操作失败原因提示信息
  promptModalShow: boolean; //操作提示框是否展示
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  autoClass = []; //标本配送自动建单选择的所有班次
  // autoClassFlag = true;//标本配送自动建单选择的班次，只能计算一次
  changeInpSubject = new Subject();
  changeSearchDeptListSubject = new Subject();
  changeSearchTaskListSubject = new Subject();
  ngOnInit() {
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getAllDepartment(this.hosId, v);
    });
    this.changeSearchDeptListSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getSearchDeptList(v);
    });
    this.changeSearchTaskListSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getSearchTaskList(v);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.listOfData = [{ A: 1 }];
    for (let i = 0; i < 100; i++) {
      this.listOfAllData.push({
        id: i,
        name: `Edward King ${i}`,
        age: 32,
        address: `London, Park Lane no. ${i}`,
      });
    }

    this.getAllHospital(); // 获取所有院区
    this.getAllAssociation(); // 获取所有关联类型
    this.getallStatisticsDateType(); // 获取统计分类
    this.getAllRelatedBusiness(); // 获取所有关联业务
    // this.getAllGoods(); //获取携带设备
    this.getAllScheduleClass(); //获取班次列表
    this.getAllTaskType(); //任务类型列表
    this.getSearchTaskList(); //任务类型列表,可搜索
    this.getSearchDeptList(); //标本配送，空单默认科室列表
    this.getReserveType(); //获取是否限制业务发起时间-字典
		this.changeInp("")
  }

	handleChange($event: ColorEvent){
		console.log($event.color)
		this.colorConfig.hex = $event.color.hex
	}

	showSketch(){
		this.colorShow = true
	}

	hideColorModal(){
		this.colorConfig.hex = '#333'
		this.colorShow = false
	}

	submitFormColor(){
		this.colorShow = false
	}

  // 搜索科室
  optionList = [];
  isLoading = false;
  onSearch(value) {
    this.isLoading = true;
    let postData = {
      idx: 0,
      sum: 5,
      department: { hospital: { id: this.hosId }, dept: value },
    };
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((result) => {
        this.isLoading = false;
        if (result.status == 200) {
          this.optionList = result.list;
        }
      });
  }
  // 备注快速选择输入------------------------------------------------------------------
  // 新添加备注快速选择输入
  addQRemarks(e: MouseEvent) {
    e.preventDefault();
    this.quickRemarkses.push({ id: ++this.qRemarksId, content: "" });
    this.qRemarksChange();
  }
  // 删除新添加备注快速选择输入
  removeQRemarks(index: number, e: MouseEvent) {
    e.preventDefault();
    this.quickRemarkses.splice(index, 1);
    this.qRemarksChange();
  }
  //监听备注快速选择输入输入事件
  qRemarksChange(e?, quickRemark?) {
    if (e !== undefined && quickRemark !== undefined) {
      quickRemark.content = e;
    }
    // -------------判断添加按钮是否禁用 start
    this.isAddQRemarks = !this.validateForm.value.quickRemarks;
    if (!this.isAddQRemarks) {
      //如果没禁用
      this.isAddQRemarks = this.quickRemarkses.some(
        (item) => item.content === ""
      );
    }
    // -------------判断添加按钮是否禁用 end
  }
  //备注快速选择输入-新增
  addQuickRemarks() {
    this.quickRemarksAdd = true;
    this.quickRemarksModal = true;
    this.quickRemarkses = [];
    this.initForm();
  }
  hideQuickRemarksModal() {
    this.quickRemarksModal = false;
  }

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      quickRemarks: [null],
    });
  }

  // 新增/编辑表单提交
  submitFormQuickRemarks(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      return;
    }
    this.hideQuickRemarksModal();
    let arr = this.quickRemarkses.map((item) => item.content);
    if (this.validateForm.value.quickRemarks) {
      arr.unshift(this.validateForm.value.quickRemarks);
    }
    this.quickRemarks = arr.join("$");
  }

  // 编辑
  editQuickRemarks() {
    this.initForm();
    this.isAddQRemarks = false;
    this.quickRemarksAdd = false;
    this.quickRemarksModal = true;
    let arr = this.quickRemarks.split("$");
    if (arr.length === 1) {
      this.validateForm.controls.quickRemarks.setValue(arr[0]);
    } else {
      this.validateForm.controls.quickRemarks.setValue(arr[0]);
      this.quickRemarkses = arr.slice(1).map((item) => {
        return { id: ++this.qRemarksId, content: item };
      });
    }
  }
  // 备注快速选择输入---------------------------------------------------------------------

  // 运输过程---备注快速选择输入------------------------------------------------------------------
  // 新添加备注快速选择输入
  addLRemarks(e: MouseEvent) {
    e.preventDefault();
    this.logRemarkses.push({ id: ++this.lRemarksId, content: "" });
    this.lRemarksChange();
  }
  // 删除新添加备注快速选择输入
  removeLRemarks(index: number, e: MouseEvent) {
    e.preventDefault();
    this.logRemarkses.splice(index, 1);
    this.lRemarksChange();
  }
  //监听备注快速选择输入输入事件
  lRemarksChange(e?, logRemark?) {
    if (e !== undefined && logRemark !== undefined) {
      logRemark.content = e;
    }
    // -------------判断添加按钮是否禁用 start
    this.isAddLRemarks = !this.validateLogRemarksForm.value.logRemarks;
    if (!this.isAddLRemarks) {
      //如果没禁用
      this.isAddLRemarks = this.logRemarkses.some(
        (item) => item.content === ""
      );
    }
    // -------------判断添加按钮是否禁用 end
  }
  //备注快速选择输入-新增
  addLogRemarks() {
    this.logRemarksAdd = true;
    this.logRemarksModal = true;
    this.logRemarkses = [];
    this.initLogRemarksForm();
  }
  hideLogRemarksModal() {
    this.logRemarksModal = false;
  }

  // 初始化新增form表单
  initLogRemarksForm() {
    this.validateLogRemarksForm = this.fb.group({
      logRemarks: [null],
    });
  }

  // 新增/编辑表单提交
  submitFormLogRemarks(): void {
    for (const i in this.validateLogRemarksForm.controls) {
      this.validateLogRemarksForm.controls[i].markAsDirty();
      this.validateLogRemarksForm.controls[i].updateValueAndValidity();
    }
    if (this.validateLogRemarksForm.invalid) {
      return;
    }
    this.hideLogRemarksModal();
    let arr = this.logRemarkses.map((item) => item.content);
    if (this.validateLogRemarksForm.value.logRemarks) {
      arr.unshift(this.validateLogRemarksForm.value.logRemarks);
    }
    this.carryingCourses[this.indexs].logRemarks = arr.join("$");
  }

  // 修改是否开通备注填写
  changeLogSwitch(e){
    if(!e){
      this.carryingCourses[this.indexs].logPrompts = '';
      this.carryingCourses[this.indexs].logRemarks = '';
    }
  }

  // 编辑
  editLogRemarks() {
    this.initLogRemarksForm();
    this.isAddLRemarks = false;
    this.logRemarksAdd = false;
    this.logRemarksModal = true;
    let arr = this.carryingCourses[this.indexs].logRemarks.split("$");
    if (arr.length === 1) {
      this.validateForm.controls.logRemarks.setValue(arr[0]);
    } else {
      this.validateForm.controls.logRemarks.setValue(arr[0]);
      this.logRemarkses = arr.slice(1).map((item) => {
        return { id: ++this.lRemarksId, content: item };
      });
    }
  }
  // 运输过程---备注快速选择输入---------------------------------------------------------------------

  // 动作------------------------------------------------------------------start
  // 新添加动作快速选择输入
  addAction(e: MouseEvent) {
    e.preventDefault();
    this.actionses.push({ id: ++this.actionsId, content: "" });
    this.actionsChange();
  }
  // 删除新添加动作快速选择输入
  removeActions(index: number, e: MouseEvent) {
    e.preventDefault();
    this.actionses.splice(index, 1);
    this.actionsChange();
  }
  //监听动作快速选择输入输入事件
  actionsChange(e?, action?) {
    if (e !== undefined && action !== undefined) {
      action.content = e;
    }
    // -------------判断添加按钮是否禁用 start
    this.isAddActions = !this.validateActionForm.value.actions;
    if (!this.isAddActions) {
      //如果没禁用
      this.isAddActions = this.actionses.some(
        (item) => item.content === ""
      );
    }
    // -------------判断添加按钮是否禁用 end
  }
  //动作快速选择输入-新增
  addActions() {
    this.actionsAdd = true;
    this.actionsModal = true;
    this.actionses = [];
    this.initActionForm();
  }
  hideActionsModal() {
    this.actionsModal = false;
  }
  // 初始化新增form表单
  initActionForm() {
    this.validateActionForm = this.fb.group({
      actions: [null],
    });
  }

  // 新增/编辑表单提交
  submitFormActions(): void {
    for (const i in this.validateActionForm.controls) {
      this.validateActionForm.controls[i].markAsDirty();
      this.validateActionForm.controls[i].updateValueAndValidity();
    }
    if (this.validateActionForm.invalid) {
      return;
    }
    this.hideActionsModal();
    let arr = this.actionses.map((item) => item.content);
    if (this.validateActionForm.value.actions) {
      arr.unshift(this.validateActionForm.value.actions);
    }
    this.carryingCourses[this.indexs].actionRemarks = arr.join("$");
  }

  // 编辑
  editActions() {
    this.initActionForm();
    this.isAddActions = false;
    this.actionsAdd = false;
    this.actionsModal = true;
    let arr = this.carryingCourses[this.indexs].actionRemarks.split("$");
    if (arr.length === 1) {
      this.validateActionForm.controls.actions.setValue(arr[0]);
    } else {
      this.validateActionForm.controls.actions.setValue(arr[0]);
      this.actionses = arr.slice(1).map((item) => {
        return { id: ++this.actionsId, content: item };
      });
    }
  }
  // 动作---------------------------------------------------------------------end

  // 初始化增删改按钮
  coopBtns: any = {};
  // 获取所有院区
  getAllHospital() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.hosName = this.tool.getCurrentHospital().hosName;
    this.onSearch("");
  }
  // 获取所有关联类型
  getAllAssociation() {
    var that = this;
    that.mainService
      .getDictionary("list", "association_types")
      .subscribe((data) => {
        that.allAssociation = data;
      });
  }
  // 获取统计分类
  getallStatisticsDateType() {
    var that = this;
    that.mainService
      .getDictionary("list", "statistics_date_type")
      .subscribe((data) => {
        that.allStatisticsDateType = data;
      });
  }
  // 获取是否限制业务发起时间-字典
  getReserveType() {
    this.mainService
      .getDictionary("list", "reserveType")
      .subscribe((data) => {
        this.reserveTypes = data;
      });
  }
  // 获取所有关联业务
  getAllRelatedBusiness() {
    this.mainService
      .getDictionary("list", "ordinary_field")
      .subscribe((data) => {
        this.allRelatedBusiness = data;
      });
  }
  //任务类型列表
  getAllTaskType() {
    let list = {
      idx: 0,
      sum: 1000,
      taskType: {
        hosIds: this.hosId + "",
      },
    };
    this.taskTypeLoading = true;
    this.mainService
      .getFetchDataList("configuration", "taskType", list)
      .subscribe((data) => {
        this.taskTypeLoading = false;
        if (data.status == 200) {
          this.allTaskType = data.list; //任务类型
          if (this.allTaskType.length === 0) {
            this.tabModalName = "jcxx";
          }
          for (var i = 0; i < this.allTaskType.length; i++) {
            if (!this.allTaskType[i].integralDetailedRules) {
              this.allTaskType[i]["integralDetailedRules"] = JSON.parse(
                JSON.stringify(
                  this.integralDetailedRulesDatas.integralDetailedRulesData
                )
              );
            } else {
              var arr = [];
              for (
                var k = 0;
                k < this.allTaskType[i].integralDetailedRules.length;
                k++
              ) {
                if (this.allTaskType[i].integralDetailedRules[k].type == 1) {
                  arr[0] = this.allTaskType[i].integralDetailedRules[k];
                }
                if (this.allTaskType[i].integralDetailedRules[k].type == 2) {
                  arr[1] = this.allTaskType[i].integralDetailedRules[k];
                }
              }
              arr[0].sumTime =
                arr[0].responseTime + arr[0].arriveTime + arr[0].executeTime;
              arr[1].sumTime =
                arr[1].responseTime + arr[1].arriveTime + arr[1].executeTime;
              arr[0].sumScore =
                Big(arr[0].responseScore)
                .plus(arr[0].arriveScore)
                .plus(arr[0].executeScore)
                .plus(arr[0].basicsScore)
                .plus(arr[0].deptsScore);
              arr[1].sumScore =
                Big(arr[1].responseScore)
                .plus(arr[1].arriveScore)
                .plus(arr[1].executeScore)
                .plus(arr[1].basicsScore)
                .plus(arr[1].deptsScore);
              this.allTaskType[i].integralDetailedRules = arr;
            }
          }
          if (this.allTaskType.length == 0) {
            this.styleType = false;
            this.styleDes(this.styleType);
          }
          if (data.list.length) {
            this.itemChoice(data.list[this.index], this.index);
          }
        }
      });
  }
  //获取班次列表
  getAllScheduleClass() {
    var that = this;
    var list = {
      idx: 0,
      scheduleClass: { hospital: { id: this.hosId } },
      sum: 1000,
    };
    that.mainService
      .getFetchDataList("configuration", "scheduleClass", list)
      .subscribe((data) => {
        if (data.status == 200) {
          this.allScheduleClass = data.list;
          for (var i = 0; i < this.allScheduleClass.length; i++) {
            this.allScheduleClass[i]["label"] = this.allScheduleClass[i].name;
          }
        }
      });
  }
  //多选框
  // logs(value, data): void {}
  //急查多选
  log2(value, data, index): void {
    data["urgentTypeIds"] = [];
    if (value.length > 0) {
      for (var i = 0; i < value.length; i++) {
        var id = {
          id: "",
          name: "",
        };
        for (var k = 0; k < this.levelData.length; k++) {
          if (this.levelData[k].id + "" == value[i]) {
            id.name = this.levelData[k].name;
          }
        }
        id.id = value[i];
        data.urgentTypeIds.push(id);
      }
    } else {
      delete data.urgentTypeIds;
    }
    this.createRuleConfiguration[index] = data;
  }
  //普查多选
  log3(value, data, index): void {
    data["ordinaryTypeIds"] = [];
    if (value.length > 0) {
      for (var i = 0; i < value.length; i++) {
        var id = {
          id: "",
          name: "",
        };
        for (var k = 0; k < this.levelData.length; k++) {
          if (this.levelData[k].id + "" == value[i]) {
            id.name = this.levelData[k].name;
          }
        }
        id.id = value[i];
        data.ordinaryTypeIds.push(id);
      }
    } else {
      delete data.ordinaryTypeIds;
    }
    this.createRuleConfiguration[index] = data;
  }
  //类型选择
  asso(id): void {
    this.association = this.allAssociation.find(v=>v.id == id);
    this.relatedBusiness = {
      id:'',
      value:''
    }
    if (id == 260) {
      this.carryingCourses = [
        {
          nodeId: { id: 261 },
          name: "起点科室",
        },
        {
          nodeId: { id: 262 },
          name: "执行中",
        },
        {
          nodeId: { id: 263 },
          name: "终点科室",
        },
      ];
    } else {
      this.carryingCourses = [
        {
          nodeId: { id: 261 },
          name: "起点科室",
        },
        {
          nodeId: { id: 263 },
          name: "终点科室",
        },
      ];
    }
  }
  // 选择自动送回的任务类型
  openSearchTaskList(flag) {
    if (flag) {
      this.getSearchTaskList();
    }
  }
  //选择类型
  currentChoice;
  itemChoice(data, index) {
    console.log('点击了任务类型', data);
    if (data === undefined) {
      return;
    }
    this.index = index;
    this.allTaskTypeShow = data.taskName;
    this.currentChoice = data;
    this.add = false;
    this.taskData = {
      taskType: {},
    };
    this.taskData.taskType["id"] = data.id;
    this.taskName = data.taskName;
    this.urgeWeight = data.urgeWeight;
    this.commonWeight = data.commonWeight;
    this.countRemark = data.countRemark || '';
		this.colorConfig.hex = data.renderColors || '#333';
		this.scorePrice = data.scorePrice || '';
    this.association = {
      id: data.associationType.id + "",
      value: data.associationType.value,
    };
    if(data.statisticsDateType){
      this.statisticsDateType = {
        id: data.statisticsDateType.id + "",
        value: data.statisticsDateType.value,
      };
    }else{
      this.statisticsDateType = {
        id: null,
        value: "",
      };
    }
    this.getType();
    this.departments = [];
    this.mapOfCheckedId = {};
    this.pageIndex = 1;
    this.styleType = true;
    this.styleDes(this.styleType);
    this.createRuleConfiguration = [];
    if(data.ordinaryField){
      this.relatedBusiness.id = data.ordinaryField.id + "";
      this.relatedBusiness.value = data.ordinaryField.value;
    }
    if (data.deptIds) {
      this.deptIds = data.deptIds;
    } else {
      this.deptIds = null;
    }
    this.integralDetailedRulesData = data.integralDetailedRules;
    if (!data.integralDetailedRules[0].taskTypeId) {
      this.integralDetailedRulesData[0]["taskTypeId"] = data.id;
      this.integralDetailedRulesData[1]["taskTypeId"] = data.id;
    }
    if (this.tabModalName == "ysgc") {
      this.getDepartment().subscribe((res) => {
        this.departmentData = res;
      });
      this.getcheckout();
      if (data.associationType.value == "specimen" && this.indexs == 0) {
        this.depaShow3 = true;
      } else {
        this.depaShow3 = false;
      }
      if (data.associationType.value == "jPBag" && this.indexs == 0) {
        this.depaShow5 = true;
      } else {
        this.depaShow5 = false;
      }
      if (data.associationType.value == "drugsBag" && this.indexs == 0) {
        this.depaShow6 = true;
      } else {
        this.depaShow6 = false;
      }
    }
    if (this.tabModalName == "ktks") {
      this.getCourseList(this.pageSize);
    }
    // this.simultaneousNumber = data.simultaneousNumber;

    this.scheduleClassChecked = [];
    this.autoClass = [];
    for (var i = 0; i < this.allScheduleClass.length; i++) {
      this.allScheduleClass[i]["label"] = this.allScheduleClass[i].name;
      this.allScheduleClass[i]["checked"] = false;
      if (data.classesIds) {
        for (var k = 0; k < data.classesIds.length; k++) {
          if (this.allScheduleClass[i].name == data.classesIds[k].name) {
            this.allScheduleClass[i]["checked"] = true;
          }
        }
      }

      if (this.allScheduleClass[i].checked) {
        this.scheduleClassChecked.push(this.allScheduleClass[i]);
        if (data.associationType.value == "specimen") {
          this.autoClass.push(this.allScheduleClass[i]);
        }
      }
    }
    if (data.associationType.value == "specimen") {
      let ids = data.carryingCourses[0].createRuleConfiguration
        ? data.carryingCourses[0].createRuleConfiguration.map(
            (item) => item.classesId
          )
        : [];
      this.scheduleClassChecked = this.scheduleClassChecked.filter(
        (item) => !ids.includes(item.id)
      );
    }
    this.allowUrgent = data.allowUrgent + "";
    this.urgentAudit = data.urgentAudit + "";
    this.autoFlag = data.autoFlag + "";
		this.deliveryUserCreate = data.deliveryUserCreate ? data.deliveryUserCreate + "" : "0";
    this.isRemand = data.isRemand ? data.isRemand + "" : "0";
    if (data.remandTypeId) {
      this.remandTypeId = `${data.remandTypeId.id}__${data.remandTypeId.taskName}`;
      let findItem = this.searchTaskList.find(
        (item) => item.id.split("__")[0] == data.remandTypeId.id
      );
      if (!findItem) {
        this.searchTaskList.unshift({
          id: `${data.remandTypeId.id}__${data.remandTypeId.taskName}`,
          taskName: data.remandTypeId.taskName,
        });
      }
    } else {
      this.remandTypeId = null;
    }
    if (data.defaultNullDeptId) {
      this.defaultNullDeptId = `${data.defaultNullDeptId.id}__${data.defaultNullDeptId.dept}`;
      let findItem = this.searchDeptList.find(
        (item) => item.id.split("__")[0] == data.defaultNullDeptId.id
      );
      if (!findItem) {
        this.searchDeptList.unshift({
          id: `${data.defaultNullDeptId.id}__${data.defaultNullDeptId.dept}`,
          dept: data.defaultNullDeptId.dept,
        });
      }
    }
    this.specialCloseButton = data.specialCloseButton
      ? data.specialCloseButton + ""
      : "0";
    this.executeSwitch = data.executeSwitch ? data.executeSwitch : 0;
    this.closeOrderCheckDept = data.closeOrderCheckDept ? data.closeOrderCheckDept : 0;
    this.bindTrans = data.bindTrans
      ? data.bindTrans + ""
      : "0";
    this.appointmentBuildFlag =
      data.appointmentSwitch === undefined ? "0" : data.appointmentSwitch + ""; //护士端是否允许预约建单,患者陪检业务
    this.appointmentBuildFlagZy =
      data.appointmentOtherSwitch === undefined
        ? "0"
        : data.appointmentOtherSwitch + ""; //护士端是否允许预约建单,患者其他服务
    this.followFlag =
      data.focusSwitch === undefined ? "0" : data.focusSwitch + ""; //护士端是否能标记重点关注
    this.isAccompany =
      data.isAccompany === undefined ? "0" : data.isAccompany + ""; //是否需要医护陪同检查
    this.isHalfInspect =
      data.isHalfInspect === undefined ? "0" : data.isHalfInspect + ""; //是否半陪检
    this.isMoreDept =
      data.isMoreDept === undefined ? "0" : data.isMoreDept + ""; //关联检查是否允许多个科室
    this.isRepeatCreateOder =
      data.isRepeatCreateOder === undefined
        ? "2"
        : data.isRepeatCreateOder + ""; //限制重复建单
    this.isDrugsCreateTime =
      !data.isDrugsCreateTime
        ? "0"
        : data.isDrugsCreateTime + ""; //药品自动建单
    this.isOneClickSignIn =
      !data.isOneClickSignIn
        ? "0"
        : data.isOneClickSignIn + ""; //是否允许一键签收
    this.isDigitalHandover =
      !data.isDigitalHandover
        ? "0"
        : data.isDigitalHandover + ""; //是否允许数字交接
    this.reserveSwitch =
      !data.reserveSwitch
        ? "0"
        : data.reserveSwitch + ""; //是否预定工单
    this.reserveUserSwitch =
      !data.reserveUserSwitch
        ? "0"
        : data.reserveUserSwitch + ""; //是否需要填写工号
    this.reserveType =
      !data.reserveType
        ? '1'
        : data.reserveType.value + ""; //是否限制业务发起时间
    this.reserveDate =  data.reserveDate === undefined ? null : new Date(data.reserveDate); //是否限制业务发起时间-时间
    this.reserveMsg =  data.reserveMsg === undefined ? '' : data.reserveMsg; //是否限制业务发起时间-提示
    // this.wechatFocusSwitch =
    //   data.wechatFocusSwitch === undefined ? "0" : data.wechatFocusSwitch + ""; //支助中心端是否能标记重点关注
    this.leadTime =
      data.appointmentTime === undefined ? "0" : data.appointmentTime + ""; //提前生效时间，默认20分钟
    this.isRemarks =
      data.remarksSwitch === undefined ? "0" : data.remarksSwitch + ""; //是否需要备注信息
    this.remarks =
      data.remarksPrompts === undefined ? "" : data.remarksPrompts + ""; //备注信息提示用语
    this.quickRemarks =
      data.customRemarks === undefined ? "" : data.customRemarks; //备注快速输入
    let addEndDeptIdsArr = data.carryingCourses[0].endDepartmentList || [];
    let ids = [];
    let arrMiddle = [];
    addEndDeptIdsArr.forEach((item1) => {
      ids.push(item1.id);
      let flag = this.optionList.every((item2) => item1.id != item2.id);
      if (flag) {
        arrMiddle.unshift(item1);
      }
    });
    this.optionList = [...arrMiddle, ...this.optionList];
    this.addEndDeptIds = ids; //自动(手动)建单追加终点科室
    this.autoAddDeptSwitch =
      data.carryingCourses[0].autoAddDeptSwitch == 1 ? true : false; //自动建单追加终点科室开关
    this.handAddDeptSwitch =
      data.carryingCourses[0].handAddDeptSwitch == 1 ? true : false; //手动建单追加终点科室开关
    this.bagOrderSwitch =
      data.carryingCourses[0].bagOrderSwitch == 1 ? true : false; //根据对接数据自动建单(静配,药品)
    if (data.carryingCourses) {
      if (this.indexs == 2 && this.association.value != "inspect") {
        this.indexs = 1;
      }
			if(data.carryingCourses[0].multipleHospital==1){
				data.carryingCourses[0].multipleHospital = true
			}else{
				data.carryingCourses[0].multipleHospital = false
			}
			if(data.carryingCourses[1].multipleHospital==1){
				data.carryingCourses[1].multipleHospital = true
			}else{
				data.carryingCourses[1].multipleHospital = false
			}
			if(data.carryingCourses[0].digitalHandover==1){
				data.carryingCourses[0].digitalHandover = true
			}else{
				data.carryingCourses[0].digitalHandover = false
			}
      this.carryingCourses = data.carryingCourses;
      this.ysgcData(this.carryingCourses[this.indexs]);
      this.depa(
        this.carryingCourses[this.indexs].departmentStrategy,
        this.carryingCourses[this.indexs].departmentStrategy.id +
          "__" +
          this.carryingCourses[this.indexs].departmentStrategy.value
      );
    }
  }
  // 获取科室类型
  loading4 = false;
  getType() {
    this.loading4 = true;
    this.mainService.getDictionary("list", "dept_type").subscribe((result) => {
      this.loading4 = false;
      this.courseTypeListDataAll = result;
    });
  }
  //防抖,搜索
  changeInp(e) {
    this.loading1 = true;
    this.changeInpSubject.next(e);
  }
  //搜索
  changeSearchDeptList(e) {
    this.searchDeptLoading = true;
    this.changeSearchDeptListSubject.next(e);
  }
  //搜索
  changeSearchTaskList(e) {
    this.searchTaskLoading = true;
    this.changeSearchTaskListSubject.next(e);
  }
  //打开
  changeFormEnd(flag) {
    if (flag) {
      // this.changeInp("");
    }
  }
  // 获取院区下所有的科室
  loading1 = false;
  getAllDepartment(id, e) {
    let postData = {
      idx: 0,
      sum: 9999,
      department: {
        dept: e,
        cascadeHosId: id
      },
    };
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.courseListDataAll = data.list;
        }
      });
  }
  //提交数据
  loading5 = false; //保存按钮loading
  submitForm() {
    if (this.reserveType == "3" && !this.reserveDate) {
      this.showPromptModal(this.add ? "新增" : "编辑", false, "<span class='red'>是否限制业务发起时间</span>选择<span class='red'>根据时间限制</span>时需要选择时间");
      return;
    }
    if (this.reserveType == "3" && !this.reserveMsg) {
      this.showPromptModal(this.add ? "新增" : "编辑", false, "<span class='red'>是否限制业务发起时间</span>选择<span class='red'>根据时间限制</span>时需要填写超出时间提示用语");
      return;
    }
    //选择自动送回后，必须选择任务类型
    //空单默认科室必选
    if (
      (this.isRemand == "1" && !this.remandTypeId) ||
      (this.association.value == 'specimen' && !this.defaultNullDeptId)
    ) {
      return;
    }
    var that = this;
    if (this.hosId) {
      this.taskData.taskType["hosId"] = { id: this.hosId };
    } else {
      that.showPromptModal(that.add ? "新增" : "编辑", false, "请选择所属院区");
      return;
    }
    if (this.taskName == "") {
      that.showPromptModal(
        that.add ? "新增" : "编辑",
        false,
        "类型名称不能为空"
      );
      return;
    } else {
      this.taskData.taskType["taskName"] = this.taskName;
    }
    this.taskData.taskType["urgeWeight"] = this.urgeWeight;
    this.taskData.taskType["commonWeight"] = this.commonWeight;
    this.taskData.taskType["countRemark"] = this.countRemark;
		this.taskData.taskType["renderColors"]  = this.colorConfig.hex || '#333';
		this.taskData.taskType["scorePrice"] = this.scorePrice;
    if (this.association.id) {
      this.taskData.taskType["associationType"] = this.association;
    } else {
      that.showPromptModal(that.add ? "新增" : "编辑", false, "请选择关联类型");
      return;
    }
    if (this.statisticsDateType.id) {
      this.taskData.taskType["statisticsDateType"] = this.statisticsDateType;
    }
    if (this.tabModalName == "ysgc") {
      if (!this.departmentStrategy.idv) {
        that.showPromptModal(
          that.add ? "新增" : "编辑",
          false,
          "请选择默认科室"
        );
        return;
      }
      if (this.checkoutMethod.id || this.taskData.taskType.associationType.value == 'ordinary') {
      } else {
        that.showPromptModal(
          that.add ? "新增" : "编辑",
          false,
          "请选择检验方式"
        );
        return;
      }
      let vv = this.departmentStrategy.idv.split('__')[1];
      if (vv == 2) {
        if (!this.departmentIds && this.departments.length === 0) {
          that.showPromptModal(
            that.add ? "新增" : "编辑",
            false,
            "请选择固定科室"
          );
          return;
        }
      }
      if (vv == 5) {
        if (!this.departmentTypeIds) {
          that.showPromptModal(
            that.add ? "新增" : "编辑",
            false,
            "请选择固定科室类型"
          );
          return;
        }
      }
      if (vv == 3) {
        if (!this.departmentIds && this.departments.length === 0) {
          that.showPromptModal(
            that.add ? "新增" : "编辑",
            false,
            "请选择固定科室范围"
          );
          return;
        }
      }
    }

    this.taskData.taskType["integralDetailedRules"] =
      this.integralDetailedRulesData;
    this.taskData.taskType["carryingCourses"] = this.carryingCourses;

    if (this.allScheduleClass.length > 0) {
      this.taskData.taskType["classesIds"] = [];
      for (var i = 0; i < this.allScheduleClass.length; i++) {
        var Class = {
          id: "",
        };
        if (this.allScheduleClass[i].checked == true) {
          Class.id = this.allScheduleClass[i].id;
          this.taskData.taskType.classesIds.push(Class);
        }
      }
    }
    if (!this.taskData.taskType.classesIds) {
      that.showPromptModal(that.add ? "新增" : "编辑", false, "请选择关联班次");
      return;
    }
    if (this.taskData.taskType.classesIds.length == 0) {
      that.showPromptModal(that.add ? "新增" : "编辑", false, "请选择关联班次");
      return;
    }
    this.taskData.taskType["allowUrgent"] = parseInt(this.allowUrgent);
    this.taskData.taskType["urgentAudit"] = parseInt(this.urgentAudit);
    this.taskData.taskType["autoFlag"] = parseInt(this.autoFlag);
		this.taskData.taskType["deliveryUserCreate"] = parseInt(this.deliveryUserCreate);
    this.taskData.taskType["isRemand"] = parseInt(this.isRemand);
    if (this.isRemand == "1") {
      let arr = this.remandTypeId.split("__");
      this.taskData.taskType["remandTypeId"] = { id: arr[0], taskName: arr[1] };
    }
    if (this.association.value == 'specimen') {
      let arr = this.defaultNullDeptId.split("__");
      this.taskData.taskType["defaultNullDeptId"] = {
        id: arr[0],
        dept: arr[1],
      };
    }
    // 万能交接服务
    if (this.association.value == 'ordinary') {
      console.log(this.relatedBusiness, this.allRelatedBusiness);
      if(this.relatedBusiness.id){
        let relatedBusiness = this.allRelatedBusiness.find(v => v.id == this.relatedBusiness.id);
        this.taskData.taskType["ordinaryField"] = relatedBusiness;
      }else{
        this.showPromptModal(this.add ? "新增" : "编辑", false, "请选择关联业务");
        return;
      }
    }else{
      delete this.taskData.taskType["ordinaryField"];
    }
    this.taskData.taskType["specialCloseButton"] = this.specialCloseButton;
    this.taskData.taskType["executeSwitch"] = this.executeSwitch;
    this.taskData.taskType["closeOrderCheckDept"] = this.closeOrderCheckDept;
    this.taskData.taskType["bindTrans"] = this.bindTrans;
    if (this.departmentStrategy.idv) {
      this.taskData.taskType.carryingCourses[this.indexs].departmentStrategy = {
        id: this.departmentStrategy.idv.split('__')[0],
      };
    }
    if (!this.departments || !this.departments.length) {
      if (this.departmentIds) {
        this.taskData.taskType.carryingCourses[this.indexs].departmentIds =
          this.departmentIds;
      }
      if (this.departmentTypeIds) {
        this.taskData.taskType.carryingCourses[this.indexs].deptTypeId = {
          id: this.departmentTypeIds,
        };
      }
    }
    if (this.checkoutMethod.id) {
      this.taskData.taskType.carryingCourses[this.indexs].checkoutMethod =
        this.checkoutMethod;
    }
    if (this.createRuleConfiguration.length > 0) {
      this.createRuleConfiguration.forEach((item) => {
        if (item.limitDeptIds) {
          item.limitDeptIds = item.limitDeptIds.map((v) => {
            return { id: v.id };
          });
        } else {
          item.limitDeptIds = [];
        }
        item.ordinaryFlag = item.ordinaryFlag ? 1 : 0;
        item.urgentFlag = item.urgentFlag ? 1 : 0;
        item.autoDeptLimit = item.autoDeptLimit ? 1 : 0;
        delete item.specimenDataNowordinaryTypeIds;
        delete item.specimenDataNowurgentTypeIds;
        delete item.specimenDataNowlimitDeptIds;
        if (item.urgentTypeIds && item.urgentTypeIds.length === 0) {
          delete item.urgentTypeIds;
        }
        if (item.ordinaryTypeIds && item.ordinaryTypeIds.length === 0) {
          delete item.ordinaryTypeIds;
        }
        if (item.limitDeptIds && item.limitDeptIds.length === 0) {
          delete item.limitDeptIds;
        }
      });
      this.taskData.taskType.carryingCourses[this.indexs][
        "createRuleConfiguration"
      ] = this.createRuleConfiguration;
    } else {
      delete this.taskData.taskType.carryingCourses[this.indexs][
        "createRuleConfiguration"
      ];
    }
    // 类型转换
    let o =
      this.taskData.taskType.carryingCourses[0] &&
      this.taskData.taskType.carryingCourses[0].createRuleConfiguration;
    if (o) {
      o.forEach((item) => {
        item.ordinaryFlag = item.ordinaryFlag ? 1 : 0;
        item.urgentFlag = item.urgentFlag ? 1 : 0;
        item.autoDeptLimit = item.autoDeptLimit ? 1 : 0;
      });
    }
    this.taskData.taskType.appointmentOtherSwitch =
      this.appointmentBuildFlagZy === "1" ? 1 : 0; //预约开关
    this.taskData.taskType.appointmentSwitch =
      this.appointmentBuildFlag === "1" ? 1 : 0; //预约开关
    this.taskData.taskType.appointmentTime =
      this.appointmentBuildFlag === "1" ? Number(this.leadTime) : 0; //生效时间
    this.taskData.taskType.focusSwitch = this.followFlag === "1" ? 1 : 0; //护士端重点关注开关
    this.taskData.taskType.isAccompany = this.isAccompany === "1" ? 1 : 0; //是否需要医护陪同检查
    this.taskData.taskType.isHalfInspect = this.isHalfInspect === "1" ? 1 : 0; //是否半陪检
    this.taskData.taskType.isMoreDept = this.isMoreDept === "1" ? 1 : 0; //关联检查是否允许多个科室
    if (this.isRepeatCreateOder !== "2") {
      this.taskData.taskType.isRepeatCreateOder =
        this.isRepeatCreateOder === "1" ? 1 : 0; //限制重复建单
    }
    if (!this.isDrugsCreateTime ||this.isDrugsCreateTime === '0') {
      this.taskData.taskType.isDrugsCreateTime = null;
    }else{
      this.taskData.taskType.isDrugsCreateTime = parseInt(this.isDrugsCreateTime); //药品自动建单
    }
    if (!this.isOneClickSignIn ||this.isOneClickSignIn === '0') {
      this.taskData.taskType.isOneClickSignIn = null;
    }else{
      this.taskData.taskType.isOneClickSignIn = parseInt(this.isOneClickSignIn); //是否允许一键签收
    }
    this.taskData.taskType.isDigitalHandover = this.isDigitalHandover === "1" ? 1 : 0; //是否允许数字交接
    this.taskData.taskType.reserveSwitch = this.reserveSwitch === "1" ? 1 : 0; //是否预定工单
    this.taskData.taskType.reserveUserSwitch = this.reserveUserSwitch === "1" ? 1 : 0; //是否需要填写工号
    this.taskData.taskType.reserveType = this.reserveTypes.find(v => v.value == this.reserveType); //是否限制业务发起时间-字典

    // 根据时间限制
    if(this.reserveType == '3'){
      this.taskData.taskType.reserveDate = this.reserveDate ? format(startOfSecond(this.reserveDate), 'yyyy-MM-dd HH:mm:ss') : undefined; //是否限制业务发起时间-时间
      this.taskData.taskType.reserveMsg = this.reserveMsg; //是否限制业务发起时间-提示
    }
    // this.taskData.taskType.wechatFocusSwitch =
    //   this.wechatFocusSwitch === "1" ? 1 : 0; //支助中心端重点关注开关
    this.taskData.taskType.remarksSwitch = this.isRemarks === "1" ? 1 : 0; //是否需要备注信息
    this.taskData.taskType.remarksPrompts = this.remarks; //备注信息提示用语
    this.taskData.taskType.customRemarks = this.quickRemarks; //备注快速输入
    this.taskData.taskType.carryingCourses[0].bagOrderSwitch = this
      .bagOrderSwitch
      ? 1
      : 0; //根据对接数据自动建单(静配,药品)
    if (this.addEndDeptIds.length) {
      this.taskData.taskType.carryingCourses[0].addEndDeptIds =
        this.addEndDeptIds.join(","); //自动(手动)建单追加终点科室
      this.taskData.taskType.carryingCourses[0].autoAddDeptSwitch = this
        .autoAddDeptSwitch
        ? 1
        : 0; //自动建单追加终点科室开关
      this.taskData.taskType.carryingCourses[0].handAddDeptSwitch = this
        .handAddDeptSwitch
        ? 1
        : 0; //手动建单追加终点科室开关
    } else {
      this.taskData.taskType.carryingCourses[0].addEndDeptIds = ""; //自动(手动)建单追加终点科室
      this.taskData.taskType.carryingCourses[0].autoAddDeptSwitch = 0; //自动建单追加终点科室开关
      this.taskData.taskType.carryingCourses[0].handAddDeptSwitch = 0; //手动建单追加终点科室开关
    }
    for(let i = 0; i < this.taskData.taskType.carryingCourses.length; i++){
      // 其他临床服务，是否支持多动作签到开启后，必须配置至少确认动作，拍照动作
      if(this.taskData.taskType.associationType.value === 'other'){
				if(i==0 && this.taskData.taskType.carryingCourses[i].actionsSwitch && !this.taskData.taskType.carryingCourses[i].actionConfirmSwitch && !this.taskData.taskType.carryingCourses[i].actionPhotoSwitch && !this.taskData.taskType.carryingCourses[i].digitalHandover){
					this.showPromptModal("提示", false, `【起点科室】是否支持多动作签到开启后，请配置确认动作或拍照动作或数字交接！`);
					return;
				}else if(i==1 && this.taskData.taskType.carryingCourses[i].actionsSwitch && !this.taskData.taskType.carryingCourses[i].actionConfirmSwitch && !this.taskData.taskType.carryingCourses[i].actionPhotoSwitch){
					this.showPromptModal("提示", false, `【终点科室】是否支持多动作签到开启后，请配置确认动作或拍照动作！`);
					return;
				}
			}

      // 其他临床服务，多动作开启后，必须配置至少一个动作
      if(this.taskData.taskType.associationType.value === 'other' && this.taskData.taskType.carryingCourses[i].actionConfirmSwitch && !this.taskData.taskType.carryingCourses[i].actionRemarks){
        this.showPromptModal("提示", false, `【${i == 0 ? '起点科室' : '终点科室'}】确认动作开启后，至少配置一个动作！`);
        return;
      }
      // 其他临床服务，多动作开启后，必须配置确认动作模式
      if(this.taskData.taskType.associationType.value === 'other' && this.taskData.taskType.carryingCourses[i].actionConfirmSwitch && !this.taskData.taskType.carryingCourses[i].actionConfirmType){
        this.showPromptModal("提示", false, `【${i == 0 ? '起点科室' : '终点科室'}】确认动作开启后，请配置确认动作模式！`);
        return;
      }
    }
		let newData = JSON.parse(JSON.stringify(this.taskData))
		if(newData.taskType.carryingCourses[0].multipleHospital){
			newData.taskType.carryingCourses[0].multipleHospital = 1
		}else{
			newData.taskType.carryingCourses[0].multipleHospital = 0
		}
		if(newData.taskType.carryingCourses[1].multipleHospital){
			newData.taskType.carryingCourses[1].multipleHospital = 1
		}else{
			newData.taskType.carryingCourses[1].multipleHospital = 0
		}

		if(newData.taskType.carryingCourses[0].digitalHandover){
			newData.taskType.carryingCourses[0].digitalHandover = 1
		}else{
			newData.taskType.carryingCourses[0].digitalHandover = 0
		}

    console.log(newData.taskType.carryingCourses[this.indexs]);
    this.loading5 = true;
    that.mainService
      .coopTypeConfig("addData", "taskType", newData)
      .subscribe((data) => {
        this.loading5 = false;
        if (data.status == 200) {
          that.showPromptModal(that.add ? "新增" : "编辑", true, "成功");
          if (!that.add) {
            this.itemChoice(this.currentChoice, this.index);
          }
          this.getAllTaskType();
          if (!this.taskData.taskType.id) {
            this.itemChoice(
              this.allTaskType[this.allTaskType.length],
              this.allTaskType.length
            );
          }
          this.checkoutMethod.id = null;
          this.departmentIds = "";
          this.departmentTypeIds = "";
        } else {
          that.showPromptModal(that.add ? "新增" : "编辑", false, data.msg);
        }
      });
  }
  //删除数据
  btnLoading: boolean = false;
  showDelModal() {
    if (this.taskData && this.taskData.taskType.id) {
      var data = [this.taskData.taskType.id];
      this.btnLoading = true;
      this.mainService
        .coopTypeConfig("rmvData", "taskType", data)
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.data && data.data[0]) {
            if (!data.data[0].msg) {
              this.showPromptModal("删除", true, "");
              this.getAllTaskType();
              this.itemChoice(this.allTaskType[0], this.index);
            } else {
              this.showPromptModal("删除", false, data.data[0].msg);
            }
          } else {
            this.showPromptModal("删除", false, "");
          }
        });
    } else {
      this.delModal = false;
      this.showPromptModal("删除", false, "请选择任务类型");
    }
  }
  //新增数据
  showCoopModal() {
    this.tabModalName = "jcxx";
    this.allTaskTypeShow = "";
    this.add = true;
    this.taskData = {
      taskType: {},
    };
    this.checkoutMethod.id = null;
    this.departmentStrategy.idv = null;
    this.departmentIds = "";
    this.departmentTypeIds = "";
    this.taskName = ""; //任务名称
    this.urgeWeight = '';
    this.commonWeight = '';
    this.countRemark = '';
		this.colorConfig.hex = '#333';
		this.scorePrice = '';
    this.association = {
      id: null,
      value: "",
    }; //关联类型
    // this.getAllGoods(); //获取携带设备
    this.getAllScheduleClass(); //获取班次列表
    this.allowUrgent = "1"; //是否加急
    this.urgentAudit = "0"; //加急是否审核
    this.autoFlag = "0"; //调度台是否可以新建工单
		this.deliveryUserCreate = "0"; //是否配送人员可以新建工单
    this.isRemand = "0"; //是否开通自动送回
    this.remandTypeId = null; //自动送回，选择任务类型
    this.defaultNullDeptId = null; //标本配送空单默认值
    this.specialCloseButton = "0"; //是否特殊情况关闭
    this.executeSwitch = 0;
    this.closeOrderCheckDept = 0;
    this.bindTrans = "0"; //是否关联数据
    this.appointmentBuildFlag = "0"; //护士端是否允许预约建单,患者陪检
    this.appointmentBuildFlagZy = "0"; //护士端是否允许预约建单，患者其他
    this.followFlag = "0"; //护士端是否能标记重点关注
    // this.wechatFocusSwitch = "0"; //支助中心端是否能标记重点关注
    this.leadTime = "20"; //提前生效时间，默认20分钟
    this.isRemarks = "0"; //提前生效时间，默认20分钟
    this.addEndDeptIds = []; //自动(手动)建单追加终点科室
    this.autoAddDeptSwitch = false; //自动建单追加终点科室开关
    this.handAddDeptSwitch = false; //手动建单追加终点科室开关
    this.bagOrderSwitch = false; //根据对接数据自动建单(静配,药品)
    this.remarks = ""; //提前生效时间，默认20分钟
    this.quickRemarks = ""; //备注快速输入
    this.styleType = false;
    this.isRepeatCreateOder = '2';
    this.reserveType = '1';
    this.reserveSwitch = '0';
    this.reserveUserSwitch = '0';
    this.styleDes(this.styleType);
    this.carryingCourses = [
      {
        nodeId: { id: 261 },
        name: "起点科室",
      },
      {
        nodeId: { id: 263 },
        name: "终点科室",
      },
    ];
    this.integralDetailedRulesData = [
      {
        type: 1, //紧急
        responseTime: 0, //响应时长
        responseScore: 0, //积分
        level1ResponseTimeoutTime: 0, //一级超时
        level1ResponseTimeoutDeduct: 0, //一级扣分
        level2ResponseTimeoutTime: 0, //二级超时
        level2ResponseTimeoutDeduct: 0, //二级扣分
        level3ResponseTimeoutTime: 0, //三级超时
        level3ResponseTimeoutDeduct: 0, //三级扣分
        arriveTime: 0, //配送人员时长
        arriveScore: 0, //积分
        level1ArriveTimeoutTime: 0, //一级超时
        level1ArriveTimeoutDeduct: 0, //一级扣分
        level2ArriveTimeoutTime: 0, //二级超时
        level2ArriveTimeoutDeduct: 0, //二级扣分
        level3ArriveTimeoutTime: 0, //三级超时
        level3ArriveTimeoutDeduct: 0, //三级扣分
        executeTime: 0, //配送人员时长
        executeScore: 0, //积分
        level1ExecuteTimeoutTime: 0, //一级超时
        level1ExecuteTimeoutDeduct: 0, //一级扣分
        level2ExecuteTimeoutTime: 0, //二级超时
        level2ExecuteTimeoutDeduct: 0, //二级扣分
        level3ExecuteTimeoutTime: 0, //三级超时
        level3ExecuteTimeoutDeduct: 0, //三级扣分
        basicsScore: 0, //基础积分
        deptsScore: 0, //多个科室追加分
        sumTime: 0, //总时长
        sumScore: 0, //总积分
      },
      {
        type: 2, //普通
        responseTime: 0, //响应时长
        responseScore: 0, //积分
        level1ResponseTimeoutTime: 0, //一级超时
        level1ResponseTimeoutDeduct: 0, //一级扣分
        level2ResponseTimeoutTime: 0, //二级超时
        level2ResponseTimeoutDeduct: 0, //二级扣分
        level3ResponseTimeoutTime: 0, //三级超时
        level3ResponseTimeoutDeduct: 0, //三级扣分
        arriveTime: 0, //配送人员时长
        arriveScore: 0, //积分
        level1ArriveTimeoutTime: 0, //一级超时
        level1ArriveTimeoutDeduct: 0, //一级扣分
        level2ArriveTimeoutTime: 0, //二级超时
        level2ArriveTimeoutDeduct: 0, //二级扣分
        level3ArriveTimeoutTime: 0, //三级超时
        level3ArriveTimeoutDeduct: 0, //三级扣分
        executeTime: 0, //配送人员时长
        executeScore: 0, //积分
        level1ExecuteTimeoutTime: 0, //一级超时
        level1ExecuteTimeoutDeduct: 0, //一级扣分
        level2ExecuteTimeoutTime: 0, //二级超时
        level2ExecuteTimeoutDeduct: 0, //二级扣分
        level3ExecuteTimeoutTime: 0, //三级超时
        level3ExecuteTimeoutDeduct: 0, //三级扣分
        basicsScore: 0, //基础积分
        deptsScore: 0, //多个科室追加分
        sumTime: 0, //总时长
        sumScore: 0, //总积分
      },
    ];
  }
  //新增禁用tab按钮
  styleDes(type) {
    var style = document.getElementById("itemDes").childNodes;
    if (type) {
      Array.from(document.getElementById("itemDes").children).forEach(function (
        item
      ) {
        item.setAttribute("style", "pointer-events:auto");
      });
    } else {
      Array.from(document.getElementById("itemDes").children).forEach(function (
        item
      ) {
        item.setAttribute("style", "pointer-events:none");
      });
    }
  }
  //详情tab
  tabModal(name) {
    if (!this.allTaskType.length) {
      return;
    }
    this.departments = [];
    this.tabModalName = name;
    if (name == "gzxx") {
      this.itemChoice(this.allTaskType[this.index], this.index);
    } else if (name == "ktks") {
      this.getCourse();
      this.getCourseList(this.pageSize);
    } else if (name == "ysgc") {
      this.patient_level();
			// this.changeInp("");
      this.getDepartment().subscribe((res) => {
        this.departmentData = res;
        this.getcheckout();
        this.itemChoice(this.allTaskType[this.index], this.index);
      });
    }
  }
  //数据计算
  Change(data) {
    data.sumTime = data.responseTime + data.arriveTime + data.executeTime;
    data.sumScore =
      Big(data.responseScore)
      .plus(data.arriveScore)
      .plus(data.executeScore)
      .plus(data.basicsScore)
      .plus(data.deptsScore);
  }
  Change1(data) {
    data.sumTime = data.responseTime + data.arriveTime + data.executeTime;
    data.sumScore =
    Big(data.responseScore)
    .plus(data.arriveScore)
    .plus(data.executeScore)
    .plus(data.basicsScore)
    .plus(data.deptsScore);
  }
  getList1() {
    this.getCourseList(this.pageSize);
  }
  //自动建单复选框
  changeFlag(e, classesId, type) {
    console.log(e);
    console.log(this.createRuleConfiguration, classesId);
    this.createRuleConfiguration.forEach((item) => {
      if (item.classesId == classesId) {
        console.log(item, item.ordinaryFlag, item.urgentFlag);
        if (
          (type == "urgentFlag" && !e && !item.ordinaryFlag) ||
          (type == "ordinaryFlag" && !e && !item.urgentFlag) ||
          e
        ) {
          item.flag = 0;
        }
        if (
          (type == "urgentFlag" &&
            !e &&
            !item.ordinaryFlag &&
            type == "ordinaryFlag" &&
            !e &&
            !item.urgentFlag) ||
          e
        ) {
          item.autoDeptLimit = false;
        }
      }
    });
  }
  // 自动建单-标本送检配置--确定
  newOrderOk1(): void {
    this.transportShow = false;
    console.log(this.createRuleConfiguration, "---确定----");
  }
  //规则信息-------
  //响应时间
  responseTimes(type) {
    this.responseTimeType = type;

    this.arriveTimeType = false;
    this.implementTimeType = false;
    this.basicsType = false;
    this.totalType = false;
    // alert(this.responseTimeType)
  }
  //到达时间
  arriveTime(type) {
    this.arriveTimeType = type;

    this.responseTimeType = false;
    this.implementTimeType = false;
    this.basicsType = false;
    this.totalType = false;
  }
  //执行时间
  implementTime(type) {
    this.implementTimeType = type;

    this.responseTimeType = false;
    this.arriveTimeType = false;
    this.basicsType = false;
    this.totalType = false;
  }
  //基础
  basics(type) {
    this.basicsType = type;

    this.responseTimeType = false;
    this.implementTimeType = false;
    this.arriveTimeType = false;
    this.totalType = false;
  }
  //总计
  total(type) {
    this.totalType = type;
    this.basicsType = false;
    this.responseTimeType = false;
    this.implementTimeType = false;
    this.arriveTimeType = false;
  }

  //运送过程------
  //快速建单
  addIncident() {
    this.transportShow = true;
    if (
      this.association.value == "jPBag" ||
      this.association.value == "drugsBag"
    ) {
      this.transportTitle = "自动建单-药品及静配送检配置";
    }
    if (this.association.value == "inspect") {
      this.transportTitle = "自动建单-患者陪检配置";
      for (var i = 0; i < this.createRuleConfiguration.length; i++) {
        this.createRuleConfiguration[i]["levelData1"] = JSON.parse(
          JSON.stringify(this.levelData)
        );
        this.createRuleConfiguration[i]["levelData2"] = JSON.parse(
          JSON.stringify(this.levelData)
        );
        if (this.createRuleConfiguration[i].urgentTypeIds) {
          for (
            var k = 0;
            k < this.createRuleConfiguration[i].urgentTypeIds.length;
            k++
          ) {
            for (
              var j = 0;
              j < this.createRuleConfiguration[i].levelData1.length;
              j++
            ) {
              if (this.createRuleConfiguration[i].urgentTypeIds[j]) {
                if (
                  this.createRuleConfiguration[i].urgentTypeIds[j].id ==
                  this.createRuleConfiguration[i].levelData1[j].id
                ) {
                  this.createRuleConfiguration[i].levelData1[j]["checked"] =
                    true;
                } else {
                  this.createRuleConfiguration[i].levelData1[j]["checked"] =
                    false;
                }
              } else {
                if (
                  this.createRuleConfiguration[i].urgentTypeIds[k].id ==
                  this.createRuleConfiguration[i].levelData1[j].id
                ) {
                  this.createRuleConfiguration[i].levelData1[j]["checked"] =
                    true;
                } else {
                  this.createRuleConfiguration[i].levelData1[j]["checked"] =
                    false;
                }
              }
            }
          }
        }
        if (this.createRuleConfiguration[i].ordinaryTypeIds) {
          for (
            var k = 0;
            k < this.createRuleConfiguration[i].ordinaryTypeIds.length;
            k++
          ) {
            for (
              var j = 0;
              j < this.createRuleConfiguration[i].levelData2.length;
              j++
            ) {
              if (this.createRuleConfiguration[i].ordinaryTypeIds[j]) {
                if (
                  this.createRuleConfiguration[i].ordinaryTypeIds[j].id ==
                  this.createRuleConfiguration[i].levelData2[j].id
                ) {
                  this.createRuleConfiguration[i].levelData2[j]["checked"] =
                    true;
                } else {
                  this.createRuleConfiguration[i].levelData2[j]["checked"] =
                    false;
                }
              } else {
                if (
                  this.createRuleConfiguration[i].ordinaryTypeIds[k].id ==
                  this.createRuleConfiguration[i].levelData2[j].id
                ) {
                  this.createRuleConfiguration[i].levelData2[j]["checked"] =
                    true;
                } else {
                  this.createRuleConfiguration[i].levelData2[j]["checked"] =
                    false;
                }
              }
            }
          }
        }
      }
    }
    if (
      this.association.value == "specimen" ||
      this.association.value == "specimenPlan"
    ) {
      console.log(this.createRuleConfiguration);
      this.createRuleConfiguration.forEach((item) => {
        item.specimenDataNowordinaryTypeIds = []; //展示普标
        item.specimenDataNowurgentTypeIds = []; //展示急标
        item.specimenDataNowlimitDeptIds = []; //展示开通科室
      });
      this.transportTitle = "自动建单-标本送检配置";
    }
    this.specimen_type();
    this.dept_type();
  }
  //固定科室范围
  adddepartment() {
    this.departmenShow = true;
    console.log(this.carryingCourses, this.indexs);
    let d = this.carryingCourses[this.indexs].departmentDTOS || [];
    this.departments = d
		// .map(i=>{
		// 	return i.id
		// });
		console.log(111,this.departments);
  }
  //默认科室获取
  getDepartment() {
    var that = this;
    //静配type
    if (
      this.carryingCourses[this.indexs].nodeId.id == 261 &&
      this.association.value == "jPBag"
    ) {
      this.mrksType = "jPBag_start_dept";
    }
    if (
      this.carryingCourses[this.indexs].nodeId.id == 263 &&
      this.association.value == "jPBag"
    ) {
      this.mrksType = "jPBag_end_dept";
    }
    //药品type
    if (
      this.carryingCourses[this.indexs].nodeId.id == 261 &&
      this.association.value == "drugsBag"
    ) {
      this.mrksType = "drugsBag_start_dept";
    }
    if (
      this.carryingCourses[this.indexs].nodeId.id == 263 &&
      this.association.value == "drugsBag"
    ) {
      this.mrksType = "drugsBag_end_dept";
    }
    //标本type
    if (
      this.carryingCourses[this.indexs].nodeId.id == 261 &&
      this.association.value == "specimen"
    ) {
      this.mrksType = "specimen_start_dept";
    }
    if (
      this.carryingCourses[this.indexs].nodeId.id == 263 &&
      this.association.value == "specimen"
    ) {
      this.mrksType = "specimen_end_dept";
    }
    //标本轮巡type
    if (
      this.carryingCourses[this.indexs].nodeId.id == 261 &&
      this.association.value == "specimenPlan"
    ) {
      this.mrksType = "specimen_start_dept";
    }
    if (
      this.carryingCourses[this.indexs].nodeId.id == 263 &&
      this.association.value == "specimenPlan"
    ) {
      this.mrksType = "specimen_end_dept";
    }
    //患者陪检type
    if (
      this.carryingCourses[this.indexs].nodeId.id == 261 &&
      this.association.value == "inspect"
    ) {
      this.mrksType = "inspect_start_dept";
    }
    if (
      this.carryingCourses[this.indexs].nodeId.id == 262 &&
      this.association.value == "inspect"
    ) {
      this.mrksType = "inspect_middle_dept";
    }
    if (
      this.carryingCourses[this.indexs].nodeId.id == 263 &&
      this.association.value == "inspect"
    ) {
      this.mrksType = "inspect_end_dept";
    }
    //其他type
    if (this.association.value == "other") {
      this.mrksType = "department_strategy";
    }
    //患者转运
    if (this.association.value == "patientTransport") {
      this.mrksType = "department_strategy_other";
    }
    //万能交接服务
    if (this.association.value == "ordinary") {
      this.mrksType = "ordinary_strategy";
    }

    return that.mainService.getDictionary("list", this.mrksType);
  }
  //检验方式获取
  yNum = 0;
  yLoading = false;
  getcheckout() {
    var that = this;
    //静配type
    if (
      this.carryingCourses[this.indexs].nodeId.id == 261 &&
      this.association.value == "jPBag"
    ) {
      this.jyfsType = "jPBag_start_method";
    }
    if (
      this.carryingCourses[this.indexs].nodeId.id == 263 &&
      this.association.value == "jPBag"
    ) {
      this.jyfsType = "jPBag_end_method";
    }
    //药品type
    if (
      this.carryingCourses[this.indexs].nodeId.id == 261 &&
      this.association.value == "drugsBag"
    ) {
      this.jyfsType = "drugsBag_start_method";
    }
    if (
      this.carryingCourses[this.indexs].nodeId.id == 263 &&
      this.association.value == "drugsBag"
    ) {
      this.jyfsType = "drugsBag_end_method";
    }
    //标本type
    if (this.association.value == "specimen") {
      if(this.carryingCourses[this.indexs].nodeId.value == 'start'){
        this.jyfsType = "specimen_method";
      } else if(this.carryingCourses[this.indexs].nodeId.value == 'finish'){
        this.jyfsType = "specimen_end_method";
      }
    }
    if (this.association.value == "specimenPlan") {
      this.jyfsType = "specimen_method";
    }
    //患者陪检type
    if (
      this.carryingCourses[this.indexs].nodeId.id == 261 &&
      this.association.value == "inspect"
    ) {
      this.jyfsType = "inspect_start_method";
    }
    if (
      this.carryingCourses[this.indexs].nodeId.id == 262 &&
      this.association.value == "inspect"
    ) {
      this.jyfsType = "inspect_middle_method";
    }
    if (
      this.carryingCourses[this.indexs].nodeId.id == 263 &&
      this.association.value == "inspect"
    ) {
      this.jyfsType = "inspect_end_method";
    }
    //患者转运type
    if (
      this.carryingCourses[this.indexs].nodeId.id == 261 &&
      this.association.value == "patientTransport"
    ) {
      this.jyfsType = "patientTransport_start_method";
    }
    if (
      this.carryingCourses[this.indexs].nodeId.id == 263 &&
      this.association.value == "patientTransport"
    ) {
      this.jyfsType = "patientTransport_end_method";
    }
    //其他type
    if (this.association.value == "other") {
      this.jyfsType = "other_method";
    }
    //万能交接服务
    if (this.association.value == "ordinary") {
      this.jyfsType = "ordinary_strategy";
    }
    this.yNum++;
    this.yLoading = true;
    that.mainService.getDictionary("list", this.jyfsType).subscribe((data) => {
      this.yNum--;
      if (this.yNum === 0) {
        this.yLoading = false;
      }
      this.checkoutData = data;
    });
  }
  //起终点科室流程选择
  onIndexChange(index: number): void {
    this.indexs = index;
    if (index == 0 && this.currentChoice.associationType.value == "specimen") {
      this.depaShow3 = true;
    } else {
      this.depaShow3 = false;
    }
    if (index == 0 && this.currentChoice.associationType.value == "jPBag") {
      this.depaShow5 = true;
    } else {
      this.depaShow5 = false;
    }
    if (index == 0 && this.currentChoice.associationType.value == "drugsBag") {
      this.depaShow6 = true;
    } else {
      this.depaShow6 = false;
    }
    this.getcheckout();
    this.getDepartment().subscribe((res) => {
      this.departmentData = res;
      this.ysgcData(this.carryingCourses[this.indexs]);
      this.depa(
        this.carryingCourses[this.indexs].departmentStrategy,
        this.carryingCourses[this.indexs].departmentStrategy.id +
          "__" +
          this.carryingCourses[this.indexs].departmentStrategy.value
      );
    });
  }
	clysData:any;
  //处理运送过程字段
  ysgcData(data) {
		this.clysData = data;
    console.log(data, "---运送过程自动建单字段(包含各个班次的信息)-----");
    console.log(this.indexs, "----索引(起点科室，终点科室对应数组的索引)----");
    if (data.departmentStrategy) {
      this.departmentStrategy.idv =
        data.departmentStrategy.id + "__" + data.departmentStrategy.value;
    } else {
      this.departmentStrategy.idv = null;
    }
    if (data.checkoutMethod) {
      this.checkoutMethod.id = data.checkoutMethod.id + "";
    } else {
      this.checkoutMethod.id = null;
    }
    if (data.departmentIds) {
      let arr = [
        ...data.departmentDTOS,
        ...this.courseListDataAll,
      ];
			const result = [];
			for (let i = 0; i < arr.length; i++) {
				let isUnique = true;
				for (let j = 0; j < result.length; j++) {
					if (arr[i].id === result[j].id) {
						isUnique = false;
						break;
					}
				}
				if (isUnique) {
					result.push(arr[i]);
				}
			}
			// console.log(1234,arr)
			// console.log(89898,result)
			this.courseListDataAll = result
      this.departmentIds = data.departmentIds;
    } else {
      this.departmentIds = null;
    }
    if (data.deptTypeId) {
      this.departmentTypeIds = data.deptTypeId.id + "";
    } else {
      this.departmentTypeIds = null;
    }
    // 自动建单
    if (data.createRuleConfiguration) {
      data.createRuleConfiguration.forEach((item) => {
        // mock start
        // item.autoDeptLimit = 1;
        // item.limitDeptIds = [{ id: 72, dept: "皮肤实验室" }, { id: 100, dept: "检验科室" }];
        // mock end
        item.ordinaryFlag = Boolean(item.ordinaryFlag); //普单
        item.urgentFlag = Boolean(item.urgentFlag); //急单
        item.autoDeptLimit = Boolean(item.autoDeptLimit); //开通科室
      });
      this.createRuleConfiguration = data.createRuleConfiguration;
      console.log(this.createRuleConfiguration, 1111111);
      let checkedScheduleClass = this.allScheduleClass.filter(
        (item) => item.checked
      );
      let k1 = checkedScheduleClass.map((item) => item.id);
      let k2 = this.createRuleConfiguration.map((item) => item.classesId);
      k2.forEach((item) => {
        if (!k1.includes(item)) {
          this.createRuleConfiguration = this.createRuleConfiguration.filter(
            (item1) => item != item1.classesId
          );
        }
      });
    } else {
      this.createRuleConfiguration = [];
    }
  }
  //获取护理级别数据
  patient_level() {
    var that = this;
    that.mainService
      .getDictionary("list", "patient_level")
      .subscribe((data) => {
        this.levelData = data;
        for (var i = 0; i < this.levelData.length; i++) {
          this.levelData[i]["label"] = this.levelData[i].name;
        }
      });
  }
  //获取标本类型数据(完整的)
  specimen_type() {
    this.mainService
      .getDictionary("list", "specimen_type")
      .subscribe((data) => {
        this.specimenData = data;
        console.log(this.createRuleConfiguration, this.specimenData);
        this.createRuleConfiguration.forEach((item) => {
          item.specimenDataNowordinaryTypeIds = JSON.parse(
            JSON.stringify(this.specimenData)
          );
          item.specimenDataNowurgentTypeIds = JSON.parse(
            JSON.stringify(this.specimenData)
          );
        });
      });
  }
  //获取开通科室是检验科室(完整的)
  jy_dept = [];
  dept_type(e = "") {
    let postData = {
      idx: 0,
      sum: 100,
      department: {
        dept: e,
        hospital: {
          id: this.hosId,
        },
        type: {
          id: "282",
        },
      },
    };
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((data) => {
        if (data.status == 200) {
          this.jy_dept = data.list;
        } else {
          this.jy_dept = [];
        }
        this.createRuleConfiguration.forEach((item) => {
          item.specimenDataNowlimitDeptIds = JSON.parse(
            JSON.stringify(this.jy_dept)
          );
        });
      });
  }
  // 获取可选择的任务类型列表
  searchTaskList = [];
  searchTaskLoading = false;
  getSearchTaskList(keyword: any = "") {
    let postData = {
      idx: 0,
      sum: 10,
      taskType: {
        taskName: keyword,
        hosIds: this.hosId,
        simpleQuery: true,
        associationType: { id: 255 },
      },
    };
    this.mainService
      .getFetchDataList("configuration", "taskType", postData)
      .subscribe((result) => {
        this.searchTaskLoading = false;
        if (result.status == 200) {
          if (this.currentChoice) {
            this.searchTaskList = result.list.filter(
              (item) => item.id != this.currentChoice.id
            );
          }
          this.searchTaskList.forEach((item) => {
            item.id = `${item.id}__${item.taskName}`;
          });
        }
      });
  }
  // 获取空值默认科室列表
  searchDeptList = [];
  searchDeptLoading = false;
  getSearchDeptList(keyword: any = "") {
    let postData = {
      idx: 0,
      sum: 10,
      department: { hospital: { id: this.hosId }, dept: keyword },
    };
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((result) => {
        this.searchDeptLoading = false;
        if (result.status == 200) {
          this.searchDeptList = result.list;
          this.searchDeptList.forEach((item) => {
            item.id = `${item.id}__${item.dept}`;
          });
        }
      });
  }
  //标本搜索
  specimen_ss(data, type, index) {
    data[type] = data[type] || [];
    data["specimenDataNow" + type] = JSON.parse(
      JSON.stringify(this.specimenData)
    );
    this.specimenData.forEach((item1) => {
      data[type].forEach((item2) => {
        if (item1.id == item2.id) {
          let i = data["specimenDataNow" + type].findIndex(
            (item) => item.id == item1.id
          );
          data["specimenDataNow" + type].splice(i, 1);
        }
      });
    });
    this.specimen_index = index;
    this.specimenList = type;
    this.specimen_types = true;
  }
  //开通科室搜索
  dept_index; //开通科室索引
  dept_types = false; //显示隐藏
  deptList;
  dps;
  dept_ss(data, type, index) {
    data[type] = data[type] || [];
    data["specimenDataNow" + type] = JSON.parse(JSON.stringify(this.jy_dept));
    this.jy_dept.forEach((item1) => {
      data[type].forEach((item2) => {
        if (item1.id == item2.id) {
          let i = data["specimenDataNow" + type].findIndex(
            (item) => item.id == item1.id
          );
          data["specimenDataNow" + type].splice(i, 1);
        }
      });
    });
    this.dept_index = index;
    this.deptList = type;
    this.dept_types = true;
  }
  //默认科室选择
	selectValue:boolean = false;
	multipleShow:boolean = false;
  depa(data, e, doing?): void {
    let arr = e.split("__");
    if (doing === "clear") {
      if(e){
        data.idv = e;
        data.id = arr[0] - 0;
        data.value = arr[1] - 0;
      }else{
        data.idv = null;
        data.id = null;
        data.value = null;
      }
			// this.carryingCourses[this.indexs].multipleHospital = false
    }
		console.log(999999, data);
    let value = arr[1];
    if (value) {
      if (value == "2") {
        this.depaShow = true;
        if (doing === "clear") {
          //固定科室
          this.departmentIds = null;
          this.departmentTypeIds = null;
          this.departments = [];
          this.carryingCourses[this.indexs].departmentIds = "";
          this.carryingCourses[this.indexs].deptTypeId = {};
          this.carryingCourses[this.indexs].departmentDTOS = [];
        }
        this.depaShow1 = false;
        this.depaShow4 = false;
      } else if (value == "5") {
        //固定科室类型
        this.depaShow4 = true;
        if (doing === "clear") {
          //固定科室类型
          this.departmentIds = null;
          this.departmentTypeIds = null;
          this.departments = [];
          this.carryingCourses[this.indexs].departmentIds = "";
          this.carryingCourses[this.indexs].deptTypeId = {};
          this.carryingCourses[this.indexs].departmentDTOS = [];
        }
        this.depaShow = false;
        this.depaShow1 = false;
      } else if (value == "3") {
        this.depaShow1 = true;
        if (doing === "clear") {
          //固定科室范围
          this.departmentIds = null;
          this.departmentTypeIds = null;
          this.departments = [];
          this.carryingCourses[this.indexs].departmentIds = "";
          this.carryingCourses[this.indexs].deptTypeId = {};
          this.carryingCourses[this.indexs].departmentDTOS = [];
        }
        this.depaShow = false;
        this.depaShow4 = false;
      } else {
        this.depaShow1 = false;
        this.depaShow = false;
        this.depaShow4 = false;
      }
			if(value == 4 || value == 5){
				this.multipleShow = true
			}else{
				this.multipleShow = false;
			}
    } else {
      this.depaShow = false;
      this.depaShow1 = false;
      this.depaShow4 = false;
			this.multipleShow = false;
    }
  }
  //删除标本类型
  remItem(list, index, type, data) {
    data["specimenDataNow" + type].push(list);
    for (var i = 0; i < data[type].length; i++) {
      if (data[type][i].id == list.id) {
        data[type].splice(i, 1);
      }
    }
    if (data[type].length === 0 || !data[type]) {
      data.flag = 0;
    }
  }
  // 新建自动建单班次-确定
  newOrderOk2() {
    var item = {
      classesId: "",
      className: "",
      flag: 0,
      ordinaryFlag: false,
      urgentFlag: false,
      autoDeptLimit: false,
      ordinaryTypeIds: [],
      specimenDataNowordinaryTypeIds: JSON.parse(
        JSON.stringify(this.specimenData)
      ),
      specimenDataNowurgentTypeIds: JSON.parse(
        JSON.stringify(this.specimenData)
      ),
      specimenDataNowlimitDeptIds: JSON.parse(JSON.stringify(this.jy_dept)),
      urgentTypeIds: [],
      limitDeptIds: [],
    };
    if (this.classChecked) {
      this.ClassChecked = false;
      this.transportShow = true;
      console.log(this.scheduleClassChecked);
      for (var i = 0; i < this.scheduleClassChecked.length; i++) {
        if (this.scheduleClassChecked[i].id == this.classChecked) {
          item.classesId = this.scheduleClassChecked[i].id;
          item["className"] = this.scheduleClassChecked[i].name;
          this.createRuleConfiguration.push(item);
        }
      }
      if (item.classesId) {
        let autoIndex = this.scheduleClassChecked.findIndex(
          (pro) => pro.id == item.classesId
        );
        this.scheduleClassChecked.splice(autoIndex, 1);
      }
    } else {
      this.showPromptModal("提交", false, "请选择班次");
    }
    this.classChecked = null; //清空
  }
  // 标本选择->确定
  newOrderOk3() {
    let obj =
      this.createRuleConfiguration[this.specimen_index][
        "specimenDataNow" + this.specimenList
      ];
    console.log(this.specimens, obj, 11111);
    for (var i = 0; i < this.specimenData.length; i++) {
      for (var k = 0; k < this.specimens.length; k++) {
        if (this.specimenData[i].id == this.specimens[k]) {
          let index = obj.findIndex((item) => item.id == this.specimens[k]);
          obj.splice(index, 1);
          if (this.specimenList == "urgentTypeIds") {
            this.createRuleConfiguration[
              this.specimen_index
            ].urgentTypeIds.push(this.specimenData[i]);
          }
          if (this.specimenList == "ordinaryTypeIds") {
            this.createRuleConfiguration[
              this.specimen_index
            ].ordinaryTypeIds.push(this.specimenData[i]);
          }
        }
      }
    }
    this.specimens = [];
    this.specimen_types = false;
  }
  // 开通科室选择->确定
  newOrderOk31() {
    let obj =
      this.createRuleConfiguration[this.dept_index][
        "specimenDataNow" + this.deptList
      ];
    for (var i = 0; i < this.jy_dept.length; i++) {
      for (var k = 0; k < this.dps.length; k++) {
        if (this.jy_dept[i].id == this.dps[k]) {
          let index = obj.findIndex((item) => item.id == this.dps[k]);
          obj.splice(index, 1);
          if (this.deptList == "limitDeptIds") {
            this.createRuleConfiguration[this.dept_index].limitDeptIds.push(
              this.jy_dept[i]
            );
          }
        }
      }
    }
    this.dps = [];
    this.dept_types = false;
  }
  newOrderOk5() {
    let that = this;
    var aa = "";
    if (this.departments.length > 0) {
      this.carryingCourses[this.indexs]["departmentDTOS"] = this.departments;
      for (var i = 0; i < this.departments.length; i++) {
        aa += this.departments[i].id + ",";
      }
      if (aa.length > 0) {
        aa = aa.substr(0, aa.length - 1);
        this.carryingCourses[this.indexs]["departmentIds"] = aa;
      }
      this.departmenShow = false;
    } else {
      that.showPromptModal("提交", false, "请选择固定科室范围");
    }
  }
  newOrder1Cancel(): void {
    this.transportShow = false;
  }
  hideModal() {
    this.transportShow = false;
  }
  newOrderCancel2(): void {
    this.ClassChecked = false;
  }
  hideModal2() {
    this.ClassChecked = false;
  }
  hideModal3(type) {
    this[type] = false;
  }
  newOrderCancel4(): void {
    this.departmenShow = false;
  }
  hideModal4() {
    this.departmenShow = false;
  }
  addItem() {
    this.ClassChecked = true;
  }
  item_start(index) {
    let obj = this.createRuleConfiguration[index];
    if (
      obj.ordinaryFlag &&
      (obj.ordinaryTypeIds === undefined || obj.ordinaryTypeIds.length === 0)
    ) {
      this.showPromptModal(
        "启用",
        false,
        `【${obj.className}】→【普查】→【自动标本类型】不能为空`
      );
      return;
    }
    if (
      obj.urgentFlag &&
      (obj.urgentTypeIds === undefined || obj.urgentTypeIds.length === 0)
    ) {
      this.showPromptModal(
        "启用",
        false,
        `【${obj.className}】→【急查】→【自动标本类型】不能为空`
      );
      return;
    }
    if (
      obj.autoDeptLimit &&
      (obj.limitDeptIds === undefined || obj.limitDeptIds.length === 0)
    ) {
      this.showPromptModal(
        "启用",
        false,
        `【${obj.className}】→【开通科室列表】不能为空`
      );
      return;
    }
    this.createRuleConfiguration[index].flag = 1;
  }
  item_stop(index) {
    this.createRuleConfiguration[index].flag = 0;
  }
  item_delete(index) {
    let item = this.createRuleConfiguration.splice(index, 1);
    console.log(item, this.scheduleClassChecked);
    this.scheduleClassChecked.push({
      id: item[0]["classesId"],
      name: item[0]["className"],
    });
  }
  //开通科室------列表
  //获取科室类型
  getCourse() {
    var that = this;
    that.mainService.getDictionary("list", "dept_type").subscribe((data) => {
      this.courseData = data;
    });
  }

  //获取科室列表
  loading2 = false;
  getCourseList(sums) {
    this.courseListData = [];
    var that = this;
    var data = {
      department: {
        cascadeHosId: this.hosId,
        pcode: this.deptPcode || undefined,
        dept: this.deptName || undefined,
        type: this.deptType ? { id: this.deptType } : undefined,
      },
      idx: this.pageIndex - 1,
      sum: sums,
    };

    var bb = [];
    this.loading2 = true;
    that.mainService
      .getFetchDataList("data", "department", data)
      .subscribe((data) => {
        this.loading2 = false;
        this.mapOfCheckedId = {};
        var cc = {};
        if (data.status == 200) {
          this.courseListData = data.list;
          if (this.deptIds) {
            bb = this.deptIds.split(",");
            bb.map(function (e, item) {
              cc[e] = true;
            });
            this.mapOfCheckedId = cc;
          }
          this.listLength = data.totalNum; //总条数
        }
      });
  }
  //科室列表搜索
  search() {
    this.pageIndex = 1;
    this.getCourseList(this.pageSize);
  }
  // 重置
  reset() {
    this.deptName = "";
    this.deptPcode = "";
    this.deptType = null;
    this.getCourseList(this.pageSize);
  }
  currentPageDataChange($event: Data[]): void {
    this.listOfDisplayData = this.courseListData; //改变页数，长度也要变
    this.refreshStatus();
  }

  refreshStatus(): void {
    this.isAllDisplayDataChecked = this.listOfDisplayData.every(
      (item) => this.mapOfCheckedId[item.id]
    );
    this.isIndeterminate =
      this.listOfDisplayData.some((item) => this.mapOfCheckedId[item.id]) &&
      !this.isAllDisplayDataChecked;
    // this.numberOfChecked = this.listOfAllData.filter(item => this.mapOfCheckedId[item.id]).length;
    this.numberOfChecked = Object.values(this.mapOfCheckedId).filter(
      (item) => item
    ).length;
    this.ChangeList(this.listOfDisplayData, this.mapOfCheckedId);
  }
  // 开通科室选择整行
  selectedListData(id) {
    this.mapOfCheckedId[id] = !this.mapOfCheckedId[id];
    this.refreshStatus();
  }

  checkAll(value: boolean): void {
    this.listOfDisplayData.forEach(
      (item) => (this.mapOfCheckedId[item.id] = value)
    );
    this.refreshStatus();
  }

  operateData(): void {
    this.isOperating = true;
    setTimeout(() => {
      this.listOfAllData.forEach(
        (item) => (this.mapOfCheckedId[item.id] = false)
      );
      this.refreshStatus();
      this.isOperating = false;
    }, 1000);
  }

  //处理表格数据
  ChangeList(A, B) {
    var aa = "";
    if (A.length > 0) {
      for (var i in B) {
        if (B[i]) {
          aa += i + ",";
        }
      }
      if (aa.length > 0) {
        aa = aa.substr(0, aa.length - 1);
        this.taskData.taskType["deptIds"] = aa;
      } else {
        this.taskData.taskType["deptIds"] = "";
      }
    } else {
      this.numberOfChecked = 0;
    }
  }

  delModal: boolean = false; //删除模态框
  showConfimModal() {
    if (!this.allTaskType.length) {
      this.msg.create("warning", "请选择需要删除的任务类型！");
      return;
    }
    this.delModal = true;
  }
  hideDelModal() {
    this.delModal = false;
  }
  confirmDel() {
    this.showDelModal();
  }
  // 选择是否半陪检
  isHalfInspectChange(e) {
    this.isHalfInspect = e;
    //半陪检，则关联检查不允许多个科室
    // if (e === "1") {
    //   this.isMoreDept = "0";
    // }
  }
  // 关联检查是否允许多个科室
  isMoreDeptChange(e) {
    this.isMoreDept = e;
    //关联检查允许多个科室,则不允许半陪检
    // if (e === "1") {
    //   this.isHalfInspect = "0";
    // }
  }

  // 展示信息提示框
  showPromptModal(con, success, errorInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    if (errorInfo !== undefined) {
      this.errorInfo = errorInfo;
    }
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
  }

  //修改是否需要填写工号
  isReserveUserSwitchChange(){
    if(this.reserveUserSwitch == '1'){
      this.isRemarks = '1';
    }
  }

  //修改是否特殊情况关闭
  changeSpecialCloseButton(){
    this.closeOrderCheckDept = 0;
  }

  // 修改是否支持多院区签到
  changeActionsSwitch(e){
    if(!e){
      this.carryingCourses[this.indexs].actionRemarks = '';
      this.carryingCourses[this.indexs].actionConfirmSwitch = false;
      this.carryingCourses[this.indexs].actionPhotoSwitch = false;
    }
  }

  // 修改是否确认动作
  changeActionConfirmSwitch(e){
    if(!e){
      this.carryingCourses[this.indexs].actionRemarks = '';
    }
  }

  // 修改是否限制业务发起时间
  changeReserveType(e){
    if(!e){
      this.reserveDate = null;
      this.reserveMsg = '';
    }
  }
}
