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

@Component({
  selector: "app-configuration-message",
  templateUrl: "./configuration-message.component.html",
  styleUrls: ["./configuration-message.component.less"],
})
export class ConfigurationMessageComponent implements OnInit {
  @Input() wechatConfigTypeValue: string;
  constructor(
    private route: ActivatedRoute,
    private mainService: MainService,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}

  coopData: any = {}; //当前操作列
  currentHospital; //当前院区

  ngOnInit() {
    this.currentHospital = this.tool.getCurrentHospital();
    setTimeout(() => {
      this.tableHeight = document.querySelector('#wechatTable').clientHeight - 8 - document.querySelector('#wechatTable .thead').clientHeight;
    }, 0)
    this.getWechatConfigTypeList();
    this.getList();
  }

  // 新增弹框
  modelName = ""; //模态框名称
  modalMessage: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  //关闭新增/编辑弹框
  hideMessageModal() {
    this.modalMessage = false;
  }

  // 选项卡
  //tabName: 名称,processTitle:标题, processContent: 内容, checkboxFlag: checkbox是否选中,,disable:遮罩是否显示
  tabs = []

  //变量参数
  varArr = [];

  // 写入
  writeIn(tab, content, event, type){
    console.log(event);
    var element = event.target.parentElement.parentElement.parentElement.previousElementSibling.children[1];
    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();
    }
  }

  // 编辑
  currentIndex = 0;
  editData:any = {};
  edit(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modalMessage = true;

    this.coopData = data;
    this.editData = {
        id: data.id,//id
        noticeCode: data.noticeCode,
        noticeRule: data.noticeRule === undefined ? 'no' : data.noticeRule,//通知规则,数字
        noticeNode: data.noticeNode,//流程节点
        processName: data.processName,//报修流程或者事件流程
        noticeState: data.noticeState,//状态
        noticeDetails: data.noticeDetails,//被通知人
        noticeProcess: data.noticeProcess,//1为报修流程、2为事件流程
        messageStationContent: data.messageStationContent,//站内消息通知内容
        shortMessageContent: data.shortMessageContent,//短信通知内容
        wechatMessageContent: data.wechatMessageContent,//微信通知内容
        messageStationFlag: data.messageStationFlag == 1 ? true : false,//站内消息是否开启
        shortMessageFlag: data.shortMessageFlag == 1 ? true : false,//短信是否开启
        wechatMessageFlag: data.wechatMessageFlag == 1 ? true : false,//微信是否开启
        messageStationTitle: data.messageStationTitle,//站内消息标题
        wechatMessageTitle: data.wechatMessageTitle,//微信标题
        flag: data.flag == 1 ? true : false,//总开关是否开启,0为关闭，1为开启
        wechatConfigTypeId: data.wechatConfigType ? data.wechatConfigType.id : null,//微信配置类型
    };

    if(this.wechatConfigTypeValue === 'hsms'){
      // 转运
      this.tabs = [
        {
          tabName: "站内消息",
          processTitle: this.editData.messageStationTitle,
          processContent: this.editData.messageStationContent,
          checkboxFlag: this.editData.messageStationFlag,
          disable: !this.editData.messageStationFlag,
          hidden: true,
        },
        {
          tabName: "短信",
          processTitle: '',
          processContent: this.editData.shortMessageContent,
          checkboxFlag: this.editData.shortMessageFlag,
          disable: !this.editData.shortMessageFlag,
          hidden: false,
        },
        {
          tabName: "微信",
          processTitle: this.editData.wechatMessageTitle,
          processContent: this.editData.wechatMessageContent,
          checkboxFlag: this.editData.wechatMessageFlag,
          disable: !this.editData.wechatMessageFlag,
          hidden: false,
        }
      ];

      this.varArr = [
        "[$患者信息$]",
        "[$建单人$]",
      ];
      if(data.noticeCode === 'pil_sign_user'){
        // 驻点人员
        this.varArr = [
          "[$患者信息$]",
          "[$建单人$]",
        ];
      }else if(data.noticeCode === 'remove_workorder'){
        // 支助人员
        this.varArr = [
          "[$工单单号$]",
          "[$申请科室$]",
          "[$起点科室$]",
          "[$终点科室$]",
          "[$发起时间$]",
          "[$执行人$]",
          "[$状态$]",
          "[$任务类型$]",
          "[$总积分$]",
          "[$执行时长$]",
          "[$患者信息$]",
          "[$删除原因$]",
        ];
      }else if(data.noticeCode === 'pil_sign_user2'){
        // 陪检签到通知驻点人员
        this.varArr = [
          "[$患者信息$]",
          "[$签到人$]",
          "[$签到科室$]",
          "[$签到时间$]",
        ];
      }else if(data.noticeCode === 'inspect_trans_receiver' || data.noticeCode ==='inspect_trans_transUser'){
				this.varArr = [
				  "[$患者信息$]",
				  "[$患者联系电话$]",
				  "[$工单单号$]",
				  "[$转派人$]",
				  "[$接收人$]",
				  "[$任务类型$]",
				  "[$发起时间$]",
				  "[$申请科室$]",
				  "[$起点科室$]",
				  "[$终点科室$]",
				];
			}else if(data.noticeCode === 'work_order_remind' || data.noticeCode ==='work_order_remind_freedom'){
				this.varArr = [
				  "[$任务类型$]",
				  "[$工单单号$]",
					"[$申请科室$]",
					"[$起点科室$]",
					"[$终点科室$]",
					"[$发起时间$]",
				  "[$是否紧急$]"
				];
			}

      this.currentIndex = 1;
    }else if(this.wechatConfigTypeValue === 'mdv2_handle'){
      // 运维
      this.tabs = [
        {
          tabName: "站内消息",
          processTitle: this.editData.messageStationTitle,
          processContent: this.editData.messageStationContent,
          checkboxFlag: this.editData.messageStationFlag,
          disable: !this.editData.messageStationFlag,
          hidden: false,
        },
        {
          tabName: "短信",
          processTitle: '',
          processContent: this.editData.shortMessageContent,
          checkboxFlag: this.editData.shortMessageFlag,
          disable: !this.editData.shortMessageFlag,
          hidden: false,
        },
        {
          tabName: "微信",
          processTitle: this.editData.wechatMessageTitle,
          processContent: this.editData.wechatMessageContent,
          checkboxFlag: this.editData.wechatMessageFlag,
          disable: !this.editData.wechatMessageFlag,
          hidden: false,
        }
      ];

      this.varArr = [
        "[$报修单号$]",
        "[$报修科室$]",
        "[$报修时间$]",
        "[$报修人$]",
        "[$详细地址$]",
        "[$不受理时间$]",
        "[$不受理原因$]",
        "[$故障描述$]",
        "[$服务台人员$]",
        "[$受理时间$]",
        "[$事件单号$]",
        "[$地点$]",
        "[$区域$]",
        "[$学工号$]",
        "[$联系人电话$]",
        "[$受理人$]",
        "[$受理人电话$]",
        "[$处理人$]",
        "[$处理人电话$]",
        "[$指派人$]",
        "[$转派人$]",
        "[$延期原因$]",
        "[$进入系统$]",
        "[$回访满意度$]",
        "[$回访备注$]",
        "[$回访处理结果$]",
        "[$评价满意度$]",
        "[$评价内容$]",
      ];

      this.currentIndex = 0;
    }
  }

  //tab页面切换
  selectTab(index) {
    this.currentIndex = index;
  };

  //checkbox选中或者取消
  selectThis(e, index) {
    this.selectTab(index);
    //遮罩切换
    this.tabs[index].disable = !this.tabs[index].checkboxFlag;
    //所有checkbox有一个选中，总开关开启
    this.editData.flag = this.tabs.some(function (v) {
        return v.checkboxFlag;
    });
};

  // 新增/编辑表单提交
  btnLoading: boolean = false; //提交按钮loading状态
  submitMessageForm(): void {
    // 微信-微信配置类型
    if(this.tabs[2].checkboxFlag && !this.editData.wechatConfigTypeId) {
      this.showPromptModal('保存', false, "请选择微信配置类型");
      return;
    }
    var filterArr = this.tabs.filter(item => {
      return item.checkboxFlag;
    });
    for (var i = 0; i < filterArr.length; i++) {
      if (filterArr[i].processContent == '') {
        this.showPromptModal('保存', false, "通知内容【" + filterArr[i].tabName + "】不能为空！");
        return;
      } else {
        var nowArr = [...new Set([...(filterArr[i].processContent.match(/\[\$[^\$\[\]]*?\$\]/g) || []), ...this.varArr])];
        if (nowArr.length !== this.varArr.length) {
          this.showPromptModal('保存', false, "【" + filterArr[i].tabName + "】请填写有效的变量名称！");
          return;
        }
      }
    }
    this.btnLoading = true;
    let postData:any = {};
    //请求参数处理(是否有输入数字控件)
    if (this.editData.noticeRule !== 'no') {
      postData = {
        // "messageManager": {
          "id": this.editData.id,
          "noticeRule": this.editData.noticeRule,
          "messageStationFlag": this.tabs[0].checkboxFlag ? 1 : 0,
          "messageStationTitle": this.tabs[0].processTitle,
          "messageStationContent": this.tabs[0].processContent,
          "shortMessageFlag": this.tabs[1].checkboxFlag ? 1 : 0,
          "shortMessageContent": this.tabs[1].processContent,
          "wechatMessageFlag": this.tabs[2].checkboxFlag ? 1 : 0,
          "wechatMessageTitle": this.tabs[2].processTitle,
          "wechatMessageContent": this.tabs[2].processContent,
          "flag": this.editData.flag ? 1 : 0,
          "wechatConfigType": this.editData.wechatConfigTypeId ? { id: this.editData.wechatConfigTypeId } : undefined,
        // }
      };
    } else {
      postData = {
        // "messageManager": {
          "id": this.editData.id,
          "messageStationFlag": this.tabs[0].checkboxFlag ? 1 : 0,
          "messageStationTitle": this.tabs[0].processTitle,
          "messageStationContent": this.tabs[0].processContent,
          "shortMessageFlag": this.tabs[1].checkboxFlag ? 1 : 0,
          "shortMessageContent": this.tabs[1].processContent,
          "wechatMessageFlag": this.tabs[2].checkboxFlag ? 1 : 0,
          "wechatMessageTitle": this.tabs[2].processTitle,
          "wechatMessageContent": this.tabs[2].processContent,
          "flag": this.editData.flag ? 1 : 0,
          "wechatConfigType": this.editData.wechatConfigTypeId ? { id: this.editData.wechatConfigTypeId } : undefined,
        // }
      };
    }
    // 关闭模态窗口并传递一个结果
    postData = Object.assign({}, this.coopData, postData);
    this.mainService
      .simplePost("updData", "messageManager", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hideMessageModal();
        let msg = "";
        if (this.add) {
          msg = "新增";
        } else {
          msg = "修改";
        }
        if (result.status == 200) {
          this.showPromptModal(msg, true, '');
        } else {
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  //获取微信配置类型
  wechatConfigTypeList:any[] = [];
  getWechatConfigTypeList() {
    this.mainService
    .getDictionary('list', 'wechat_config_type')
    .subscribe((data) => {
      this.wechatConfigTypeList = data || [];
    });
  }

  // 获取列表
  loading1:boolean = false;
  messageList: any[] = []; //表格数据
  tableHeight:number = 0;
  getList() {
    let data = {
      idx: 0,
      sum: 9999,
      messageManager: {
        "noticeProcess": 1,
        "wechatConfigType": {
          value: this.wechatConfigTypeValue,
        },
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "messageManager", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.messageList = data.list || [];
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
    this.getList();
  }
}
