package com.yihu.wlyy.task;

import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.service.app.consult.ConsultService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import java.util.Date;
import java.util.List;

/**
 * 缴费提醒任务
 * <p>
 * Created by lyr-pc on 2017/1/16.
 */
public class RemindExpensesTask implements Runnable {
    List<Patient> patients;

    Doctor doctor;

    Hospital hospital;
    @Autowired
    WeiXinAccessTokenUtils tokenUtils;
    @Autowired
    WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    ConsultService consultService;

    public RemindExpensesTask(List<Patient> patients, Doctor doctor, Hospital hospital) {
        this.patients = patients;
        this.doctor = doctor;
        this.hospital = hospital;
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    @Override
    public void run() {
        StringBuffer sb = new StringBuffer();

        for (Patient p : patients) {
            try {
                if (StringUtils.isNotEmpty(p.getMobile())) {
                    if (sb.length() > 0) {
                        sb.append(",");
                    }
                    sb.append(p.getMobile());
                }
                // 微信提醒
                JSONObject json = new JSONObject();
                json.put("first", "缴费提醒");
                json.put("toUser", p.getCode());
                json.put("represented",p.getCode());//被代理人
                json.put("name", p.getName());
                json.put("doctor", doctor.getCode());
                json.put("doctorName", doctor.getName());
                json.put("date", DateUtil.dateToStrShort(new Date()));
                json.put("content", p.getName() + "，您好！为完成家庭医生签约，尽早为您提供家庭医生服务，请尽快到" + hospital.getName() + "（地址：" + hospital.getAddress() + "）缴费");
                json.put("remark", "");
                if (StringUtils.isNotEmpty(p.getOpenid())) {
                    // 添加到发送队列
                    PushMsgTask.getInstance().putWxMsg(tokenUtils.getAccessToken(), 8, p.getOpenid(), p.getName(), json);
                }
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(),p.getOpenid());
                if(jsonArray!=null&&jsonArray.length()>0){
                    String first = (String) json.get("doctorName");
                    for (int i = 0;i<jsonArray.length();i++){
                        JSONObject j  = jsonArray.getJSONObject(i);
                        Patient member = (Patient) j.get("member");
                        JSONObject data = json;
                        data.remove("toUser");
                        data.put("toUser",member.getCode());
                        data.remove("doctorName");
                        data.put("doctorName", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) +"\n"+first);
                        PushMsgTask.getInstance().putWxMsg(tokenUtils.getAccessToken(), 8, member.getOpenid(), p.getName(), data);
                    }
                }

                //发送IM
                consultService.sendMucMessageBySingnType(doctor.getCode(), doctor.getName(), p.getCode(), doctor.getName() + "医生提醒您：为完成家庭医生签约，" +
                        "尽早为您提供家庭医生服务，请尽快到" + doctor.getName() + "（地址：" + hospital.getAddress() + "）缴费", "1", p.getName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        JSONObject result = SMSService.sendMsg(sb.toString(), doctor.getName() + "医生提醒您：为完成家庭医生签约，" +
                "尽早为您提供家庭医生服务，请尽快到" + hospital.getName() + "（地址：" + hospital.getAddress() + "）缴费");
    }
}
