import { Component, OnInit } from '@angular/core';
import { ToolService } from 'src/app/services/tool.service';
import { MainService } from 'src/app/services/main.service';
import { ActivatedRoute } from '@angular/router';
import { KeyValue } from '@angular/common';
import { format, startOfMinute } from 'date-fns';

@Component({
  selector: 'app-operation-notice',
  templateUrl: './operation-notice.component.html',
  styleUrls: ['./operation-notice.component.less']
})
export class OperationNoticeComponent implements OnInit {

  hosId; //当前院区
  allTaskType = []; //通知类型列表
  allTaskTypeShow; //通知类型列表选择标识
  taskTypeLoading = false; //通知类型加载中
  tabModalName = ""; //详情tab字段
  // 初始化增删改按钮
  coopBtns: any = {};

  variableNames = ['[$患者姓名$]', '[$主刀医生姓名$]', '[$麻醉医师姓名$]', '[$护士姓名$]', '[$助理医生姓名$]', '[$科室名称$]', '[$手术名称$]', '[$手术时间$]', '[$手术间名称$]'];

  tabs:any[] = [];
  tabsDefault:any[] = [
    {
      role: 'doctor',
      phoneFlag: false,
      phoneContent: '',
      wechatFlag: false,
      wechatContent: '',
      orders: 1,
			sendTime: new Date(),
			outsideFlag: false,
			outsideContent: '',
			outsideTitle:'',
    },
    {
      role: 'docAssistant',
      phoneFlag: false,
      phoneContent: '',
      wechatFlag: false,
      wechatContent: '',
      orders: 2,
			sendTime: new Date(),
			outsideFlag: false,
			outsideContent: '',
			outsideTitle:'',
    },
    {
      role: 'anesthetist',
      phoneFlag: false,
      phoneContent: '',
      wechatFlag: false,
      wechatContent: '',
      orders: 3,
			sendTime: new Date(),
			outsideFlag: false,
			outsideContent: '',
			outsideTitle:'',
    },
    {
      role: 'patient',
      phoneFlag: false,
      phoneContent: '',
      wechatFlag: false,
      wechatContent: '',
      orders: 4,
			sendTime: new Date(),
			outsideFlag: false,
			outsideContent: '',
			outsideTitle:'',
    },
  ];
  tabNames = {
    doctor: '主刀医生',
    docAssistant: '助理医生',
    anesthetist: '临床',
    patient: '手术患者',
  }

  constructor(
    private tool: ToolService,
    private mainService: MainService,
    private route: ActivatedRoute,
  ) { }

  ngOnInit() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getAllTaskType(); //通知类型列表
  }

  originalOrder = (a: KeyValue<number,string>, b: KeyValue<number,string>): number => {
    return 0;
  }

  //通知类型列表
  getAllTaskType() {
    this.allTaskType = [
			{
      id: 1,
      taskName: '手术即将开始通知',
      code: 'surgery_begin',
    },
		{
		  id: 2,
		  taskName: '下一日首台通知',
		  code: 'next_day_first_surgery',
		},
		{
		  id: 3,
		  taskName: '当日首台通知',
		  code: 'today_first_surgery',
		}
		];
    if (this.allTaskType.length) {
      this.itemChoice(this.allTaskType[0]);
    }
  }

  // 选中通知类型
  currentChoice;
  itemChoice(data){
    this.currentChoice = data;
    this.allTaskTypeShow = data.taskName;
    console.log(data);
    let postData = {
      idx: 0,
      sum: 9999,
      transportMessage: {
        hosId: this.hosId,
        code: data.code,
      },
    };
    this.taskTypeLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "transportMessage", postData)
      .subscribe((result) => {
        this.taskTypeLoading = false;
        if (result.status == 200) {
          result.list = result.list || [];
          result.list.forEach(v => {
            v.phoneFlag = v.phoneFlag === 1;
            v.wechatFlag = v.wechatFlag === 1;
						v.outsideFlag = v.outsideFlag === 1;
						v.sendTime = v.sendTime ? new Date(v.sendTime) : null; 
          })
          let tabs = result.list || [];
          if(tabs.length){
            this.tabs = tabs;
          }else{
            this.tabs = this.tabsDefault.map(v => ({...v, code: data.code, hosId: this.hosId}));
          }
          // 没有选中则默认第一项
          !this.tabModalName && this.tabModal(this.tabs[0].role);
        }
      });
  }

  //详情tab
  tabModal(name) {
    if (!this.allTaskType.length) {
      return;
    }
    this.tabModalName = name;
  }

  // 写入
  writeIn(tab, content, event, type){
    var element = event.target.parentElement.parentElement.previousElementSibling;
    if (element.selectionStart || element.selectionStart == '0') {
        var startPos = element.selectionStart;
        var endPos = element.selectionEnd;
        tab[type] = element.value.substring(0, startPos) + content + element.value.substring(endPos);
        element.focus();
        setTimeout(() => {
          element.setSelectionRange(startPos + content.length, startPos + content.length);
        },0)
    } else {
        var val = element.value + content;
        tab[type] = val;
        element.focus();
    }
  }

  // 展示信息提示框
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  errorInfo: string; //操作失败原因提示信息
  promptModalShow: boolean; //操作提示框是否展示
  showPromptModal(con, success, errorInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    if (errorInfo !== undefined) {
      this.errorInfo = errorInfo;
    }
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
  }

  //提交数据
  loading5 = false; //保存按钮loading
  submitForm() {
    this.loading5 = true;
    this.tabs.forEach(v => {
      v.phoneFlag = v.phoneFlag ? 1 : 0;
      v.wechatFlag = v.wechatFlag ? 1 : 0;
			v.outsideFlag = v.outsideFlag ? 1 : 0;
			v.sendTime = v.sendTime ? format(startOfMinute(v.sendTime), 'yyyy-MM-dd HH:mm:ss') : null
    })
    this.mainService
      .simplePost("addListData", "transportMessage", this.tabs)
      .subscribe((data) => {
        this.loading5 = false;
        if (data.status == 200) {
          this.showPromptModal("保存", true, "成功");
          this.itemChoice(this.currentChoice);
        } else {
          this.showPromptModal("保存", false, data.msg);
        }
      });
  }
}
