package com.yihu.wlyy.service.common;

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

import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.yihu.wlyy.entity.message.SMS;
import com.yihu.wlyy.repository.message.SMSDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.HttpClientUtil;
import com.yihu.wlyy.util.SystemConf;
import org.springframework.util.StringUtils;

import javax.print.Doc;

@Component
@Transactional(rollbackFor = Exception.class)
public class SMSService extends BaseService {

    @Autowired
    public SMSDao smsDao;
    @Autowired
    PatientDao patientDao;
    @Autowired
    SignFamilyDao signFamilyDao;
    @Autowired
    DoctorDao doctorDao;

    /**
     * 发送短信验证码接口
     *
     * @param mobile 手机号
     * @param type   消息类型:1微信端注册，2微信端找回密码，3医生端找回密码，4患者登录，5医生登录,7用户变更手机号验证 8用户新手机号验证 9绑定手机号
     *               10 家庭成员添加验证
     * @return
     * @throws Exception
     */
    public String send(String mobile, String ip, int type, String code) throws Exception {
        // 生成6位随机验证码
        String captcha = String.valueOf(Math.random()).substring(2, 8);
        // 默认为123456
        // captcha = "123456";
        // 同一ip一天不允许超过10条短信
        String today = DateUtil.getStringDateShort();
        Date begin = DateUtil.strToDate(today + " 00:00:00", DateUtil.YYYY_MM_DD_HH_MM_SS);
        Date end = DateUtil.strToDate(today + " 23:59:59", DateUtil.YYYY_MM_DD_HH_MM_SS);
        // int count = smsDao.countByIp(ip, begin, end);
        // if (count >= SystemConf.MAX_SMS_IP) {
        // return "当前IP：[" + ip + "]今天最多发送" + SystemConf.MAX_SMS_IP + "条短信！";
        // }
        // 一天的短信数不允许超过10条
        int count = smsDao.countByMobile(mobile, begin, end);
        if (count >= SystemConf.MAX_SMS_MOBILE) {
            return "当前手机号：[" + mobile + "]今天最多发送" + SystemConf.MAX_SMS_MOBILE + "条短信！";
        }
        // 两分钟之内不允许重复发送
        PageRequest pageRequest = new PageRequest(0, 1, new Sort(Direction.DESC, "id"));
        Page<SMS> page = smsDao.findByMobileType(mobile, type, pageRequest);
        if (page != null) {
            for (SMS sms : page) {
                if (sms == null) {
                    continue;
                }
                // 计算间隔时间
                Date temp = DateUtil.getNextMin(sms.getCzrq(), SystemConf.SMS_INTERVAL);
                long leftTime = (temp.getTime() - System.currentTimeMillis()) / 1000;
                if (leftTime > 0) {
                    return "发送短信验证码间隔时间为：" + SystemConf.SMS_INTERVAL + "分钟，还剩" + leftTime + "秒";
                }
            }
        }
        // 保存验证码
        SMS sms = new SMS();
        // 1微信端注册，2微信端找回密码，3医生端找回密码，4患者登录，5医生登录
        if (type == 1) {
            // 患者注册
            sms.setContent("您的注册验证码为：" + captcha);
        } else if (type == 2 || type == 3) {
            sms.setContent("您找回密码验证码为：" + captcha);
        } else if (type == 4 || type == 5) {
            // 登录
            sms.setContent("您的登录验证码为：" + captcha);
        } else if (type == 7) {
            // 手机号变更验证
            sms.setContent("您更换手机号验证码为：" + captcha);
        } else if (type == 8) {
            // 新手机号绑定验证
            sms.setContent("您新手机号验证码为：" + captcha);
        } else if (type == 9) {
            // 新手机号绑定验证
            sms.setContent("您绑定手机号验证码为：" + captcha);
        } else if (type == 10) {
            Patient patient = patientDao.findByCode(code);
            if (patient == null) {
                throw new Exception("短信发送失败！");
            }
            // 新手机号绑定验证
            sms.setContent(patient.getName() + "欲添加您为家人，添加成功后，对方可登录您的账号，为您处理各类健康服务。如同意添加，可告知其验证码(" + captcha + ")。");
        } else {
            // 其他验证码
            sms.setContent("验证码：" + captcha);
        }
        if (type == 2 || type == 4 || type == 10) {//患者
            List<Patient> patients = patientDao.findByMobile(mobile);
            if (patients != null && patients.size() > 0) {
                SignFamily sign = signFamilyDao.findByPatient(code);
                sms.setUserType(0);
                sms.setUserCode(code);
                if (sign != null) {
                    sms.setHospital(sign.getHospital());
                }
            }
        } else if (type == 3 || type == 5 || type == 6) {//医生
            Doctor d = doctorDao.findByMobile(mobile);
            if (d != null) {
                sms.setUserType(0);
                sms.setUserCode(d.getCode());
                sms.setHospital(d.getHospital());
            }
        } else {//未知
            Doctor d = doctorDao.findByMobile(mobile);
            if (d != null) {
                sms.setUserType(0);
                sms.setUserCode(d.getCode());
                sms.setHospital(d.getHospital());
            } else {
                if (!StringUtils.isEmpty(code)) {
                    SignFamily signFamily = signFamilyDao.findByPatient(code);
                    if (signFamily != null) {
                        sms.setUserType(0);
                        sms.setUserCode(signFamily.getPatient());
                        sms.setHospital(signFamily.getHospital());
                    }
                }
            }
        }
        sms.setCaptcha(captcha);
        Date date = new Date();
        // 延后5分钟
        sms.setDeadline(DateUtil.getNextMin(date, type == 10 ? 30 : 5));
        sms.setCzrq(date);
        sms.setMobile(mobile);
        sms.setIp(ip);
        sms.setType(type);
        sms.setStatus(1);
        // 调用总部发送信息的接口
        String result = HttpClientUtil.post(SystemConf.getInstance().getSmsUrl(), buildSmsParams(sms.getContent(), mobile), "GBK");
        JSONObject json = toJson(result);
        if (json == null) {
            // 发送失败
            throw new Exception("短信发送失败！");
        } else if (json.getInt("result") != 0) {
            return json.getString("description");
        } else {
            //发送成功，保存到数据库
            smsDao.save(sms);
        }
        return "ok";
    }

    /**
     * 发送短信
     *
     * @param mobile
     * @param content
     * @return
     */
    public static JSONObject sendMsg(String mobile, String content) {
        // 调用总部发送信息的接口
        String result = HttpClientUtil.post(SystemConf.getInstance().getSmsUrl(), buildSmsParams(content, mobile), "GBK");
        JSONObject json = toJson(result);
        return json;
    }

    /**
     * 验证码校验
     *
     * @param mobile  手机号
     * @param type    type 消息类型:1微信端注册，2微信端找回密码，3医生端找回密码，4患者登录，5医生登录 7用户变更手机号 8用户新手机号验证 9用户绑定手机号
     * @param captcha 验证码
     * @return -1验证码过期，-1验证码错误，0验证码无效，1验证通过
     */
    public int check(String mobile, int type, String captcha) {
        // 根据手机号和验证码查询对应的短信信息
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, 1, sort);
        Page<SMS> page = smsDao.findByCaptcha(mobile, captcha, type, pageRequest);
        SMS sms = null;
        for (SMS temp : page) {
            if (temp != null) {
                sms = temp;
                break;
            }
        }
        // 验证码校验
        if (sms == null) {
            // 验证码错误
            return -1;
        } else if (type != sms.getType()) {
            // 验证码无效，也视为错误
            return -1;
        } else if (sms.getDeadline().before(new Date())) {
            // 验证码过期
            return -2;
        }
        return 1;
    }

    public static List<NameValuePair> buildSmsParams(String content, String mobile) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("SpCode", SystemConf.getInstance().getSmsCode()));
        params.add(new BasicNameValuePair("LoginName", SystemConf.getInstance().getSmsName()));
        params.add(new BasicNameValuePair("Password", SystemConf.getInstance().getSmsPassword()));
        params.add(new BasicNameValuePair("MessageContent", content));
        params.add(new BasicNameValuePair("UserNumber", mobile));
        params.add(new BasicNameValuePair("SerialNumber", String.valueOf(System.currentTimeMillis())));
        params.add(new BasicNameValuePair("ScheduleTime", ""));
        params.add(new BasicNameValuePair("f", "1"));
        return params;
    }

    public static JSONObject toJson(String result) {
        JSONObject json = new JSONObject();
        try {
            String[] temps = result.split("&");
            for (String temp : temps) {
                if (temp.split("=").length != 2) {
                    continue;
                }
                String key = temp.split("=")[0];
                String value = temp.split("=")[1];
                json.put(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    public static void main(String[] args) {

        // JSONObject params = new JSONObject();
        // params.put("SpCode", SystemConf.SMS_SP_CODE);
        // params.put("LoginName", SystemConf.SMS_LOGIN_NAME);
        // params.put("Password", SystemConf.SMS_PASSWORD);
        // params.put("MessageContent", "您的找回密码验证码为：123456");
        // params.put("UserNumber", "18559687019");
        // params.put("SerialNumber", "");
        // params.put("ScheduleTime", "");
        // params.put("f", 1);
        //
        // // String result = HttpUtil.sendPost(SystemConf.SMS_URL, params.toString(), "GBK");
        // String result = HttpClientUtil.post(SystemConf.SMS_URL, buildSmsParams("您的找回密码验证码为：123456", "18559687019"), "GBK");
        // JSONObject json = toJson(result);
        // System.out.println(json.toString());
        // System.out.println(json.getInt("result"));
        // if (json.getInt("result") != 0) {
        // System.out.println("短信发送失败！");
        // }

        System.out.println(toJson("result=0&description=发送短信成功&taskid=22624861237&faillist=&task_id=22624861237"));
    }

}
