package com.zhongdao.jlr.business.service.impl;

import com.util.UtilTools;
import com.util.Vo;
import com.zhongdao.jlr.business.dao.CouponDao;
import com.zhongdao.jlr.business.service.CouponService;

import com.zhongdao.jlr.business.vo.*;
import com.zhongdao.jlr.pojo.CouponConsumeJlrPO;
import com.zhongdao.jlr.pojo.CouponRechargeJlrPO;
import com.zhongdao.jlr.pojo.JLRCoupon;
import com.zhongdao.jlr.util.MTextUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.util.RequestUtil.ReturnObjStr;

/***
 * 处理代金券的业务
 */

@Service(value = "couponServiceImpl")
public class CouponServiceImpl implements CouponService {

    @Autowired
    private CouponDao dao;

    @Override
    public Vo searchConsume(String vinCode, String electronicAccounts,
                            String userPhone, int page, int raws) {

        return dao.searchConsume(vinCode, electronicAccounts,userPhone, page, raws);
    }

    @Override
    public Vo getCouponConsume(String vin, int page, int raws) {
        return dao.getCouponConsume(vin, page, raws);
    }

    @Override
    public Vo getCouponRecharge(String vin, int page, int raws) {
        return dao.getCouponRecharge(vin, page, raws);
    }

    @Override
    public Vo queryCouponConsume(String vin, String account, String RecuseCompanyName, String rescueCompanyCode, String license, String phone, String state, String qureyDate1, String queryDate2, int page, int raws) {
        return dao.queryCouponConsume(vin, account, RecuseCompanyName, rescueCompanyCode, license, phone, state, qureyDate1, queryDate2, page, raws);
    }
    @Override
    public JSONObject exportData(HttpServletRequest request, String vin, String account, String RecuseCompanyName, String rescueCompanyCode, String license, String phone, String state, String queryDate1, String queryDate2) {
        //声明一个json对象用来存储导出报表的信息
        JSONObject jsonObject = new JSONObject();
        //声明一个集合用来接收代金券消费记录的数据
        List list = null;
        //声明一个导出报表集合用来存储代金券消费记录信息
        List listExcel = new ArrayList();
        //sql动态拼接
        StringBuffer sql = new StringBuffer(
                "SELECT c.id,c.vin_code,c.consume_count,c.electronic_accounts,r.user_phone,r.license,e.NAME,c.settlement_state,c.CONSUME_TIME,c.reparie_info,c.hitch_info,c.settle_time,c.create_time,c.remark\n" +
                        "FROM jlr_coupon_consume c LEFT JOIN jlr_coupon r ON c.VIN_CODE = r.VIN_CODE\n" +
                        "LEFT JOIN jlr_enterprise e on c.enterprise_id = e.ID\n where 1=1 ");
        if (StringUtils.isNotBlank(vin)) {
            sql.append("  and c.VIN_CODE like '%" + vin + "%'");
        }
        if (StringUtils.isNotBlank(account)) {
            sql.append("  and c.electronic_accounts like '%" + account + "%'");
        }
        if (StringUtils.isNotBlank(RecuseCompanyName)) {
            sql.append("  and e.NAME like '%" + RecuseCompanyName + "%'");
        }
        if (StringUtils.isNotBlank(phone)) {
            sql.append("  and r.USER_PHONE like '%" + phone + "%'");
        }
        if (StringUtils.isNotBlank(license)) {
            sql.append("  and r.LICENSE like '%" + license + "%'");
        }
        if (StringUtils.isNotBlank(state)) {
            sql.append("  and c.settlement_state = '" + state + "'");
        }
        if (StringUtils.isNotBlank(rescueCompanyCode)) {
            sql.append("  and c.enterprise_id = '" + rescueCompanyCode + "'");
        }
        if (StringUtils.isNotBlank(queryDate1)) {
            sql.append(" and c.CONSUME_TIME >= '"+queryDate1+"'");
        }

        // 结束时间
        if (StringUtils.isNotBlank(queryDate2)) {
            sql.append(" and c.CONSUME_TIME <= '"+queryDate2+"'");
        }
        try {
            //获取代金券消费记录信息
            list = dao.getRsBySql(sql.toString());
            //遍历代金券消费记录数据，并将其放入消费记录实体类中，再将实体类加入集合中
            if (list != null && list.size() > 0) {
                ConsumeQueryExcelVO header = new ConsumeQueryExcelVO("VIN码", "电子账户", "手机号码", "车牌号", "消费时间", "消费金额", "经销商", "审批状态");
                listExcel.add(header);
                for (int i = 0; i < list.size(); i++) {
                    ConsumeQueryExcelVO consumeQueryExcelVO = new ConsumeQueryExcelVO();
                    Object[] objects = (Object[]) list.get(i);
                    consumeQueryExcelVO.setVinCode(ReturnObjStr(objects[1]));
                    consumeQueryExcelVO.setElectronicccounts(ReturnObjStr(objects[3]));
                    consumeQueryExcelVO.setUserPhone(ReturnObjStr(objects[4]));
                    consumeQueryExcelVO.setLicense(ReturnObjStr(objects[5]));
                    //格式化日期
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    Date date=sdf.parse(ReturnObjStr(objects[8]));
                    consumeQueryExcelVO.setConsumeTime(sdf.format(date));
                    consumeQueryExcelVO.setConsumeCount(ReturnObjStr(objects[2]));
                    consumeQueryExcelVO.setName(ReturnObjStr(objects[6]));
                    consumeQueryExcelVO.setState(transState(ReturnObjStr(objects[7])));
                    listExcel.add(consumeQueryExcelVO);
                }
                //时间格式转换
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                //获取当前时间并将其转换为string字符串
                String dateTime = simpleDateFormat.format(new Date());
                //导出报表路径
                String path = request.getRealPath("attached") + File.separator + "consumption_record_" + dateTime + ".xlsx";
                String webUrl = UtilTools.getWebAddress(request) + File.separator
                        + "attached" + File.separator + "consumption_record_" + dateTime + ".xlsx";
                boolean b = new ConsumeQueryExcelVO().saveAll(listExcel, path);
                if (b) {
                    jsonObject.put("result", "0");// 0:成功，1失败
                    jsonObject.put("msg", "导出成功！");
                    jsonObject.put("webUrl", webUrl);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;

    }

    /****
     * 根据状态码返回对应的结果信息
     * @param value
     * @return
     */
    private String transState(String value) {
        switch (value) {
            case "0":
                return "未结算";
            case "1":
                return "未结算";
            case "5":
                return "提交结算";
            case "10":
                return "同意付款";
            case "100":
                return "已付款";
            case "101":
                return "已撤销";
            default:
                break;
        }
        return "";
    }

    @Override
    public boolean updateConsumeState(String cId, String state) {
        List<CouponRechargeJlrPO> couponRechargeJlrList = new ArrayList<CouponRechargeJlrPO>();
        //如果是撤销这需要撤销充值记录的变动
        if ("101".equals(state)) {
            //以,分割id
            String[] ids = cId.split(",");
            for (String id : ids) {
                CouponConsumeJlrPO consumejlr = null;
                try {
                    //获取消费记录信息
                    consumejlr = (CouponConsumeJlrPO) dao.getObjectHql("from CouponConsumeJlrPO where id=" + id);
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
                //获取充值记录信息
                List<CouponRechargeJlrPO> list = revokeRecharge(consumejlr.getVin_code(), consumejlr.getConsume_count());
                if (list != null) {
                    couponRechargeJlrList.addAll(list);
                }
            }
            if (couponRechargeJlrList.size() == 0) {
                return false;
            }
        }
        //更改状态（撤销充值记录）
        return dao.updateConsumeState(couponRechargeJlrList, cId, state);
    }

    @Override
    public List<CouponRechargeJlrPO> revokeRecharge(String vinCode, double revokeRechargeCount) {
        //声明一个集合用来存储充值记录信息
        List<CouponRechargeJlrPO> couponRechargeJlrList = null;
        try {
            //获取用户的充值记录
            couponRechargeJlrList = dao.getRsByHql("from CouponRechargeJlrPO where CONSUME_COUNT>0 and VIN_CODE='" + vinCode + "' and  overdue_time>NOW() order by overdue_time desc");
        } catch (Exception e) {
            e.printStackTrace();
            return couponRechargeJlrList;
        }
        //计算代金劵充值应该退回的充值记录
        List<CouponRechargeJlrPO> revokeCouponRechargeJlrList = new ArrayList<CouponRechargeJlrPO>();
        double b = revokeRechargeCount;
        //遍历用户的代金券充值记录
        for (CouponRechargeJlrPO couponRechargeJlr : couponRechargeJlrList) {
            //获取用户的消费金额
            double c = couponRechargeJlr.getConsume_count();
            if (c > 0) {
                //如果用户的代金券充值金额大于用户的代金券消费金额
                if (b >= c) {
                    //更新用户代金券的消费金额为0.0
                    couponRechargeJlr.setConsume_count(0.0F);
                    b = b - c;
                    revokeCouponRechargeJlrList.add(couponRechargeJlr);
                    continue;
                } else {
                    //更新用户的代金券消费金额
                    couponRechargeJlr.setConsume_count(Float.valueOf(String.valueOf(Double.parseDouble(couponRechargeJlr.getConsume_count().toString()) - b)));
                    revokeCouponRechargeJlrList.add(couponRechargeJlr);
                    b = 0;
                    break;
                }

            }
        }
        return couponRechargeJlrList;
    }
    @Override
    public boolean sendMsg(String phoneNum, String msgContent) {
        //String send_url = "http://sms.10690221.com/hy/?uid=20016&auth=8827d737029bc0950a90cf9ce5946ce9&expid=0&encode=GBK";
        String send_url = "http://sms.10690221.com/hy/?uid=20016&auth=093627dd3b2b54900dcd355fd92b8f91&expid=0&encode=GBK";
        BufferedReader reader = null;
        try {
            send_url += "&mobile=" + phoneNum + "&msg=" + URLEncoder.encode(msgContent, "GBK");
            StringBuffer readOneLineBuff = new StringBuffer();
            String content = "";
            URL url = new URL(send_url);
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(1000);
            conn.setReadTimeout(1000);
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                readOneLineBuff.append(line);
            }
            reader.close();

            content = readOneLineBuff.toString();

            if ("0".equals(content.split(",")[0])) {
                return true;
            }
        } catch (Exception e2) {
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    @Override
    public Vo queryCouponRecharge(String vin, String account, String orderCode, String license, String phone, String qureyDate1, String queryDate2, int page, int raws) {
        return dao.queryCouponRecharge(vin, account, orderCode, license, phone, qureyDate1, queryDate2, page, raws);
    }

    @Override
    public JSONObject rechangeExportData(HttpServletRequest request, String vin, String account, String orderCode,  String phone, String queryDate1, String queryDate2) throws Exception {
        {
            JSONObject jsonObject = new JSONObject();
            List list = null;
            List listExcel = new ArrayList();
            //sql动态拼接
            StringBuffer sql = new StringBuffer(
                    "SELECT c.ID,c.VIN_CODE,c.task_order_id,c.RECHARGE_TIME,c.RECHARGE_COUNT,c.SEATE_NAME,c.REMARK,c.SERVICE_NAME,c.OVERDUE_TIME,c.CONSUME_COUNT,r.ELECTRONIC_ACCOUNTS,c.CREATE_TIME, " +
                            "r.LICENSE, r.USER_PHONE\n" +
                            "FROM jlr_coupon_recharge c LEFT JOIN jlr_coupon r ON c.VIN_CODE = r.VIN_CODE where 1=1 ");
            if (StringUtils.isNotBlank(vin)) {
                sql.append("  and c.VIN_CODE like '%" + vin + "%'");
            }
            if (StringUtils.isNotBlank(account)) {
                sql.append("  and r.ELECTRONIC_ACCOUNTS like '%" + account + "%'");
            }
            if (StringUtils.isNotBlank(orderCode)) {
                sql.append("  and c.task_order_id like '%" + orderCode + "%'");
            }
            if (StringUtils.isNotBlank(phone)) {
                sql.append("  and r.USER_PHONE like '%" + phone + "%'");
            }
            if (StringUtils.isNotBlank(queryDate1)) {
                sql.append(" and c.RECHARGE_TIME >= '"+queryDate1+"'");
            }
            // 结束时间
            if (StringUtils.isNotBlank(queryDate2)) {
                sql.append(" and c.RECHARGE_TIME <= '"+queryDate2+"'");
            }

            sql.append("ORDER BY CREATE_TIME DESC");
            try {
                list = dao.getRsBySql(sql.toString());
                //获取充值记录信息并将其遍历，放入实例化对象中，再将对象加入集合中
                if (list != null && list.size() > 0) {
                    RechangeQueryExcelVO header = new RechangeQueryExcelVO("VIN码", "电子账户", "手机号码", "车牌号", "服务类型", "案件编号", "充值金额", "充值时间", "到期时间");
                    listExcel.add(header);
                    for (int i = 0; i < list.size(); i++) {
                        RechangeQueryExcelVO rechangeQueryExcelVO = new RechangeQueryExcelVO();
                        Object[] objects = (Object[]) list.get(i);
                        rechangeQueryExcelVO.setVinCode(ReturnObjStr(objects[1]));
                        rechangeQueryExcelVO.setElectronicAccounts(ReturnObjStr(objects[10]));
                        rechangeQueryExcelVO.setUserPhone(ReturnObjStr(objects[13]));
                        rechangeQueryExcelVO.setLicense(ReturnObjStr(objects[12]));
                        rechangeQueryExcelVO.setServiceType(ReturnObjStr(objects[5]));
                        rechangeQueryExcelVO.setcaseCode(ReturnObjStr(objects[2]));
                        //格式化日期
                        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                        Date date=sdf.parse(ReturnObjStr(objects[3]));
                        rechangeQueryExcelVO.setRechargeTime(sdf.format(date));
                        rechangeQueryExcelVO.setRechargeCount(ReturnObjStr(objects[4]));
                        Date overDate=sdf.parse(ReturnObjStr(objects[8]));
                        rechangeQueryExcelVO.setOverdueTime(sdf.format(overDate));
                        listExcel.add(rechangeQueryExcelVO);
                    }

                    //String s = URLEncoder.encode("充值记录", "GBK");
                    //时间格式转换
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    //获取当前时间并转换为字符串
                    String dateTime = simpleDateFormat.format(new Date());
                    //到处报表路径
                    String path = request.getRealPath("attached") + File.separator + "recharge_record_" + dateTime + ".xlsx";
                    String webUrl = UtilTools.getWebAddress(request) + File.separator
                            + "attached" + File.separator + "recharge_record_" + dateTime + ".xlsx";
                    boolean b = new RechangeQueryExcelVO().saveAll(listExcel, path);
                    if (b) {
                        jsonObject.put("result", "0");// 0:成功，1失败
                        jsonObject.put("msg", "导出成功！");
                        jsonObject.put("webUrl", webUrl);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return jsonObject;

        }
    }

    @Override
    public Vo getCoupon(String vin, String electronicAccounts, int page, int raws) {
        return dao.getCoupon(vin, electronicAccounts, page, raws);
    }

    @Override
    public Map consume(String consumeTime, String vinCode, Double consumeCount,
                       Integer enterpriseJlrId, String reparieInfo, String hitchInfo, String remark, String epassword) {
        //声明一个Map集合用来存储结果集信息
        Map<String, Object> map = new HashMap();
        map.put("status", false);
        try {
            //判断密码是否正确
            JLRCoupon conponjlr = (JLRCoupon) dao.getObjectHql("from JLRCoupon where vin_code='" + vinCode + "' and e_password='" + epassword + "'");
            if (conponjlr == null) {
                map.put("msg", "消费密码不正确");
                return map;
            }

            //查询该用户的充值记录
            List<CouponRechargeJlrPO> couponRechargeJlrList = dao.getRsByHql("from CouponRechargeJlrPO where VIN_CODE='" + vinCode + "' and recharge_count>ifNull(consume_count,0) and overdue_time>NOW() order by overdue_time");
            double balance = 0;//余额
            if (couponRechargeJlrList != null && couponRechargeJlrList.size() > 0) {
                for (CouponRechargeJlrPO couponRechargeJlr : couponRechargeJlrList) {
                    balance += (couponRechargeJlr.getRecharge_count() - MTextUtils.stringToDouble(couponRechargeJlr.getConsume_count()));
                }
            } else {
                map.put("msg", "余额不足");
                return map;
            }


            //余额小于消费金额
            if (balance < consumeCount) {
                map.put("msg", "余额不足");
                return map;
            }


            //计算代金劵消费
            List<CouponRechargeJlrPO> consumeCouponRechargeJlrList = new ArrayList<CouponRechargeJlrPO>();
            //声明本次的消费金额
            double b = consumeCount;
            //遍历所有的充值信息（充值金额大于消费金额且没有过期）
            for (CouponRechargeJlrPO couponRechargeJlr : couponRechargeJlrList) {
                double c = couponRechargeJlr.getRecharge_count() - MTextUtils.stringToDouble(couponRechargeJlr.getConsume_count());
                if (c > 0) {
                    if (c >= b) {
                        String s=String.valueOf(b + MTextUtils.stringToDouble(couponRechargeJlr.getConsume_count()));
                        couponRechargeJlr.setConsume_count(Float.valueOf(s));
                        consumeCouponRechargeJlrList.add(couponRechargeJlr);
                        break;
                    } else {
                        b = b - c;
                        couponRechargeJlr.setConsume_count(couponRechargeJlr.getRecharge_count());
                        consumeCouponRechargeJlrList.add(couponRechargeJlr);
                        continue;
                    }

                }
            }
            //声明一个消费记录实体类
            CouponConsumeJlrPO conponConsumejlr = new CouponConsumeJlrPO();
            conponConsumejlr.setElectronic_accounts(conponjlr.getElectronic_accounts());
            conponConsumejlr.setVin_code(vinCode);
            conponConsumejlr.setConsume_count(Float.valueOf(String.valueOf(consumeCount)));
            conponConsumejlr.setHitch_info(hitchInfo);
            conponConsumejlr.setEnterprise_id(enterpriseJlrId);
            conponConsumejlr.setReparie_info(reparieInfo);
            conponConsumejlr.setRemark(remark);
            conponConsumejlr.setSettlement_state(0);
            conponConsumejlr.setCreate_time(new Date());
            conponConsumejlr.setUpdate_time(new Date());
            conponConsumejlr.setSettle_time(new Date());
            DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
            conponConsumejlr.setConsume_time(format1.parse(consumeTime));
            //临时主键生成
            conponConsumejlr.setId(Integer.valueOf((System.currentTimeMillis() / 10 + "").substring(3)));
            if (dao.consume(conponConsumejlr, consumeCouponRechargeJlrList)) {
                map.put("status", true);
                return map;
            } else {
                map.put("msg", "数据出错！");
                return map;
            }

        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "数据出错！");
            return map;
        }
    }

}
