import {Component, OnInit} from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { AjaxService } from '../../../../core/service/ajax.service';
import { MsgService } from '../../../../core/service/msg.service';
import { FrameDetailComponent } from '../../../frame/core/detail/frame.detail';

@Component({
  selector: 'app-weixin-template-send',
  templateUrl: './weixin-template-send.component.html',
  styleUrls: ['./weixin-template-send.component.scss']
})
export class WeixinTemplateSendComponent extends FrameDetailComponent implements OnInit {
  wxTemplate: any;
  aspectArr = [];
  payArr = [];

  dictArr = [
    {dict_name: '所有考生', dict_value: '1'},
    {dict_name: '专业维度', dict_value: '2'},
    {dict_name: '准考证维度', dict_value: '3'},
    {dict_name: '初复试维度', dict_value: '4'},
    {dict_name: '定向发送', dict_value: '5'}
  ];

  ticketArr = [
    {dict_text: '所有', dict_value: '0'},
    {dict_text: '已下载', dict_value: '1'},
    {dict_text: '未下载', dict_value: '2'}
  ];

  passArr = [
    {dict_text: '所有', dict_value: '0'},
    {dict_text: '通过', dict_value: '1'},
    {dict_text: '不通过', dict_value: '2'}
  ]


  constructor(bsModalRef: BsModalRef) {
    super(bsModalRef);
  }

  initDefautEntity() {
    this.ResponseMap = {};
    this.payArr.push({'value': '', name: '全部'});
    this.payArr.push({'value': 'have', name: '已缴费考生'});
    this.payArr.push({'value': 'no', name: '未缴费考生'});
    this.listAspect();
  }

  ngOnInit() {
  }

  changeTemplate() {
    if (this.currentEntity.template_id === undefined)
      return;
    this.ResponseMap = {};
    this.currentEntity.test_flag = 'InActive';
    this.currentEntity.real_sql = '';
    AjaxService.requestEntity('weixin/template/find.htm', {template_id: this.currentEntity.template_id},
      (entity) => {
        this.wxTemplate = entity;
      });
  }

  serachWxUser() {
    this.ResponseMap = {};
    this.currentEntity.test_flag = 'InActive';
    this.currentEntity.confirm_flag = 'InActive';
    this.currentEntity.real_sql = '';
    AjaxService.requestMap('weixin/template/user/list.htm', {sql: encodeURIComponent(this.currentEntity.execute_sql)}, (map) => {
      if (!map.UserTotal || map.UserTotal === 0) {
        MsgService.warningToastr('没有找到任何目标用户！');
        return;
      }
      this.currentEntity.real_sql = encodeURIComponent(this.currentEntity.execute_sql);
      this.ResponseMap = map;
      this.currentEntity.json_value = JSON.stringify(this.ResponseMap.UserArray[0], null, 1);
    });
  }
  confirmMsg(flag) {
    this.currentEntity.confirm_flag = flag;
  }
  goSendTest() {
    const wx = Object.assign({}, this.wxTemplate);
    this.replaceValues(wx, this.ResponseMap['UserArray'][0]);
    MsgService.confirmAlert('确定要发送测试消息吗？请留意测试微信号', () => {
      AjaxService.request('weixin/template/send/test.htm', wx, (map) => {
        this.currentEntity.test_flag = 'Active';
      });

    })
  }

  sendAll() {
    const wx = Object.assign({}, this.wxTemplate);
    wx.sql = this.currentEntity.real_sql;
    MsgService.confirmAlert('确定要发送给【'+ this.ResponseMap.UserTotal +'】个考生发送微信消息？该操作不可回退，务必谨慎操作！', () => {
      AjaxService.request('weixin/template/send.htm',wx, () => {
        MsgService.successAlert('已提交到后台处理！')
        this.ResponseMap = {};
        this.currentEntity.test_flag = 'InActive';
        this.currentEntity.confirm_flag = 'InActive';
        this.currentEntity.real_sql = '';
      },{RequestWithLoading :true});

    })
  }

  replaceValues(wx, obj) {
    for (const name in obj) {
      let value = obj[name];
      // 替换
      if (wx.template_url)
        wx.template_url = wx.template_url.replace(`@{${name}}`, value);
      if (wx.content_value)
        wx.content_value = wx.content_value.replace(`@{${name}}`, value);
      if (wx.keyword1_value)
        wx.keyword1_value = wx.keyword1_value.replace(`@{${name}}`, value);
      if (wx.keyword2_value)
        wx.keyword2_value = wx.keyword2_value.replace(`@{${name}}`, value);
      if (wx.keyword3_value)
        wx.keyword3_value = wx.keyword3_value.replace(`@{${name}}`, value);
      if (wx.keyword4_value)
        wx.keyword4_value = wx.keyword4_value.replace(`@{${name}}`, value);
      if (wx.keyword5_value)
        wx.keyword5_value = wx.keyword5_value.replace(`@{${name}}`, value);
      if (wx.remark_value)
        wx.remark_value = wx.remark_value.replace(`@{${name}}`, value);
    }

  }

  listAspect() {
    this.AjaxService.requestArray('conf/aspect/all.htm', {}, (array) => {
      this.aspectArr = array;
      for(const aspect of this.aspectArr) {
        aspect.aspect_full_name = aspect.aspect_code +"|" +aspect.aspect_name;
      }
      this.aspectArr.unshift({aspect_id: '', aspect_full_name : '全部'});
    });
  }

  //简单sql组装
  assemSql() {
    this.currentEntity.execute_sql = '';
    if(this.currentEntity.mode == '1') {
      this.currentEntity.execute_sql = " select weixin_id open_id,std_name,cert_id from std_reg  where weixin_id is not null ";
    } else if(this.currentEntity.mode == '2') {
      this.currentEntity.execute_sql = "select distinct weixin_id open_id,std_name,cert_id from std_reg r,std_enrol e where r.std_id=e.std_id" ;
      if(this.currentEntity.aspect_ids !='' && this.currentEntity.aspect_ids !== undefined) {
        this.currentEntity.execute_sql += " and aspect_id in (" + this.currentEntity.aspect_ids+")";
      }
      if(this.currentEntity.have_pay == 'have') {
        this.currentEntity.execute_sql += " and e.pay_status='Active'";
      } else if(this.currentEntity.have_pay == 'no') {
        this.currentEntity.execute_sql += " and e.pay_status='InActive'";
      }
    } else if (this.currentEntity.mode == '3') {
      this.currentEntity.execute_sql = 'select distinct r.weixin_id open_id,r.std_name,r.cert_id from ly_std_ticket t ,std_reg r where t.std_id=r.std_id and weixin_id is not null';
      //已下载
      if(this.currentEntity.download_flag == '1') {
        this.currentEntity.execute_sql += " and t.std_id in ( select distinct  std_id from  std_log where log_type='DownloadTicket')";
      } else if(this.currentEntity.download_flag == '2') { //未下载
        this.currentEntity.execute_sql += " and t.std_id not in ( select distinct  std_id from  std_log where log_type='DownloadTicket')";
      }
    } else if(this.currentEntity.mode == '4') {
      this.currentEntity.execute_sql = "select distinct r.weixin_id open_id,r.std_name,r.cert_id from sc_std_aspect t,std_reg r where t.std_id=r.std_id ";
      //初试
      if(this.currentEntity.batch_id == '1') {
        this.currentEntity.execute_sql += " and score_1_qualified is not null ";
        if(this.currentEntity.pass_flag == '1') {
          this.currentEntity.execute_sql += " and score_1_qualified ='Active'" ;
        } else if(this.currentEntity.pass_flag == '2') {
          this.currentEntity.execute_sql += " and score_1_qualified ='InActive'" ;
        }
      } else if(this.currentEntity.batch_id == '2') { //复试
        this.currentEntity.execute_sql += " and score_2_qualified is not null ";
        if(this.currentEntity.pass_flag == '1') {
          this.currentEntity.execute_sql += " and score_2_qualified ='Active'" ;
        } else if(this.currentEntity.pass_flag == '2') {
          this.currentEntity.execute_sql += " and score_2_qualified ='InActive'" ;
        }

      } else if(this.currentEntity.batch_id == '3') { //三试
        this.currentEntity.execute_sql += " and score_3_qualified is not null ";
        if(this.currentEntity.pass_flag == '1') {
          this.currentEntity.execute_sql += " and score_3_qualified ='Active'" ;
        } else if(this.currentEntity.pass_flag == '2') {
          this.currentEntity.execute_sql += " and score_3_qualified ='InActive'" ;
        }
      }
    } else if(this.currentEntity.mode == '5') {
      if(!this.currentEntity.cert_id) {
        this.MsgService.errorToastr('请输入考生的身份证号码！');
        return;
      }
      this.currentEntity.execute_sql = " select weixin_id open_id,std_name,cert_id from std_reg  where cert_id='" + this.currentEntity.cert_id +"'";
    }
    
    this.serachWxUser();
  }
  
}
