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

import com.dubh.common.dao.hibernate.BaseDaoHibernate;
import com.util.UtilTools;
import com.util.Vo;
import com.zhongdao.jlr.business.dao.CouponDao;
import com.zhongdao.jlr.business.vo.CouponConsumeJlr;
import com.zhongdao.jlr.business.vo.CouponJlrVO;
import com.zhongdao.jlr.business.vo.CouponRechargeJlr;
import com.zhongdao.jlr.business.vo.PageInfo;
import com.zhongdao.jlr.pojo.CouponConsumeJlrPO;
import com.zhongdao.jlr.pojo.CouponRechargeJlrPO;
import com.zhongdao.jlr.util.MTextUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.util.TextUtils;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Repository("couponDaoImpl")
public class CouponDaoImpl extends BaseDaoHibernate implements CouponDao {

    @Override
    public Vo searchConsume(String vin, String electronicAccounts,String userPhone, int page, int raws) {
        //声明一个vo对象用来存储账户信息和账户数据总数
        Vo vo = new Vo();
        //声明一个分页类用来存储页数和每页多少条数据
        PageInfo pageInfo=new PageInfo();
        pageInfo.setPage(page);
        pageInfo.setRows(raws);
        try {
            //sql动态拼接
            StringBuffer sql = new StringBuffer("select cj.electronic_accounts, cj.vin_code,cj.user_name,cj.user_phone,cj.license,cj.remark,ifNull((select sum((ifNull((recharge_count),0)-ifNull((consume_count),0))) as result from jlr_coupon_recharge j where j.overdue_time>NOW() and j.vin_code=cj.vin_code),0) as result ,cj.e_password  from jlr_coupon cj where 1=1");
            if (!TextUtils.isEmpty(vin) || !TextUtils.isEmpty(electronicAccounts) || !TextUtils.isEmpty(userPhone)) {
                if (!TextUtils.isEmpty(vin)) {
                    sql.append("  and cj.vin_code like '%" + vin + "%'");
                }

                if (!TextUtils.isEmpty(electronicAccounts)) {
                    sql.append("  and cj.electronic_accounts like '%" + electronicAccounts + "%'");
                }
                if (!TextUtils.isEmpty(userPhone)) {
                    sql.append("  and cj.USER_PHONE like '%" + userPhone + "%'");
                }
            }
            String countSql=sql.toString();
            String sqlStr =sql.append(" limit "+pageInfo.getCurrentIndex()+","+pageInfo.getRows()).toString();
            List<Object[]> list = getRsBySql(sqlStr);
            //声明一个list集合用来存储账户信息对象
            List<CouponJlrVO> resultList = new ArrayList<>();
            //遍历账户信息数据，并将每一个对象放入集合中
            for (Object[] obj : list) {
                CouponJlrVO couponvo = new CouponJlrVO();
                couponvo.setElectronicAccounts(MTextUtils.objectToString(obj[0]));
                couponvo.setVinCode(MTextUtils.objectToString(obj[1]));
                couponvo.setUserName(MTextUtils.objectToString(obj[2]));
                couponvo.setUserPhone(MTextUtils.objectToString(obj[3]));
                couponvo.setLicense(MTextUtils.objectToString(obj[4]));
                couponvo.setRemark(MTextUtils.objectToString(obj[5]));
                couponvo.setCharge(MTextUtils.stringToDouble(MTextUtils.objectToString(obj[6])));
                couponvo.setPassword(MTextUtils.objectToString(obj[7]));
                resultList.add(couponvo);
            }
            vo.setRows(resultList);
            //获取账户数据总数
            int size = getRsCountsBySelectSql(countSql);
            vo.setTotal(size);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return vo;
    }

    @Override
    public Vo getCouponConsume(String vin, int page, int raws) {
        //声明一个分页类用来存储页数和每页多少条数据
        PageInfo pageInfo=new PageInfo();
        pageInfo.setPage(page);
        pageInfo.setRows(raws);
        //声明一个list集合用来存储用户代金券消费记录
        List<CouponConsumeJlr> lists=new ArrayList<>();
        //时间格式化转换
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Vo vo = new Vo();
        try {
            //获取用户代金券消费记录
            List list = getRsBySql("select vin_code,consume_count,consume_time,settlement_state,remark from jlr_coupon_consume  where VIN_CODE='" + vin + "' order by consume_time desc limit  "+pageInfo.getCurrentIndex()+","+pageInfo.getRows());
            //遍历用户代金券消费记录并将其放入list集合中
            if(list != null && list.size()>0){
                for (int i=0;i<list.size();i++){
                    Object[] objects= (Object[]) list.get(i);
                    CouponConsumeJlr couponConsumeJlr=new CouponConsumeJlr();
                    couponConsumeJlr.setVinCode(objects[0] == null ? "" : objects[0].toString());
                    couponConsumeJlr.setConsumeCount(Double.valueOf(objects[1] == null ? "0" : objects[1].toString()));
                    couponConsumeJlr.setConsumeTime(simpleDateFormat.parse(objects[2].toString()));
                    couponConsumeJlr.setSettlementState(Integer.valueOf(objects[3] == null ? "0" : objects[3].toString()));
                    couponConsumeJlr.setRemark(objects[4] == null ? "" : objects[4].toString());
                    lists.add(couponConsumeJlr);
                }
            }
            vo.setRows(lists);
            //获取用户代金券消费记录总条数
            vo.setTotal(getRsCountsBySelectSql("select vin_code,consume_count,consume_time,settlement_state,remark from jlr_coupon_consume  where VIN_CODE='" + vin + "' order by consume_time desc"));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return vo;
    }

    @Override
    public Vo getCouponRecharge(String vin, int page, int raws) {
        Vo vo = new Vo();
        //声明一个分页类用来存储页数和每页多少条数据
        PageInfo pageInfo=new PageInfo();
        //时间格式化转换
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        pageInfo.setPage(page);
        pageInfo.setRows(raws);
        //声明一个集合用来存储用户的代金券充值记录
        List<CouponRechargeJlr> lists=new ArrayList<>();
        try {
            //获取用户的代金券充值记录
            List list = getRsBySql("select task_order_id,recharge_count,service_name,overdue_time,recharge_time from jlr_coupon_recharge  where VIN_CODE='" + vin + "' limit "+pageInfo.getCurrentIndex()+","+pageInfo.getRows());
            //遍历充值信息及其放入集合中
            if(list != null && list.size()>0){
                for (int i=0;i<list.size();i++){
                    Object[] objects= (Object[]) list.get(i);
                    CouponRechargeJlr couponRechargeJlr=new CouponRechargeJlr();
                    couponRechargeJlr.setOrderCode(objects[0] == null ? "" : objects[0].toString());
                    couponRechargeJlr.setRechargeCount(Double.valueOf(objects[1] == null ? "0" : objects[1].toString()));
                    couponRechargeJlr.setServiceName(objects[2] == null ? "" : objects[2].toString());
                    couponRechargeJlr.setOverdueTime(simpleDateFormat.parse(objects[3].toString()));
                    couponRechargeJlr.setRechargeTime(simpleDateFormat.parse(objects[4].toString()));
                    lists.add(couponRechargeJlr);
                }
            }
            vo.setRows(lists);
            //获取用户充值记录总条数
            vo.setTotal(getRsCountsBySelectSql("select order_id,recharge_count,service_name,overdue_time,recharge_time from jlr_coupon_recharge  where VIN_CODE='" + vin + "'"));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return vo;
    }

    @Override
    public Vo queryCouponConsume(String vin, String account, String RecuseCompanyName, String rescueCompanyCode, String license, String phone, String state, String queryDate1, String queryDate2, int page, int raws) {
        //声明一个分页类用来存储页数和每页多少条数据
        PageInfo pageInfo=new PageInfo();
        pageInfo.setPage(page);
        pageInfo.setRows(raws);
        Vo vo = new Vo();
        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+"'");
        }
        String countSql=sql.append("ORDER BY CONSUME_TIME DESC ").toString();
        String info=sql.append("limit "+pageInfo.getCurrentIndex()+","+pageInfo.getRows()).toString();
        try {
            List list = getRsBySql(info);
            if (list != null && list.size() > 0) {
                vo.setRows(UtilTools.listTojsonArray(list, new String[]{"ID", "VIN_CODE","CONSUME_COUNT","ELECTRONIC_ACCOUNTS","USER_PHONE","LICENSE","NAME","SETTLEMENT_STATE","CONSUME_TIME","REPARIE_INFO","HITCH_INFO","SETTLE_TIME","CREATE_TIME","REMARK"}));
            }
            vo.setTotal(getRsCountsBySelectSql(countSql));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vo;
    }

    @Override
    public boolean updateConsumeState(List<CouponRechargeJlrPO> couponechargeList, String cId, String state) {
        Session session = null;
        Transaction tx = null;
        try {
            session = getSessionFactory().getCurrentSession().getSessionFactory().openSession();
            tx = session.beginTransaction();
            //sql动态拼接
            StringBuffer sql = new StringBuffer("update jlr_coupon_consume set SETTLEMENT_STATE = " + state);
            if (StringUtils.isBlank(state)) {
                return false;
            }
            if ("10".equals(state)) {
                sql.append(", settle_time = NOW()");
            }
            if (StringUtils.isBlank(cId)) {
                return false;
            } else {
                sql.append(" where id in (" + cId + ")");
            }
            //更改状态
            SQLQuery query = session.createSQLQuery(sql.toString());
            query.executeUpdate();

            //回滚充值记录
            for (CouponRechargeJlrPO c : couponechargeList) {
                session.saveOrUpdate(c);
            }
            //事务提交
            tx.commit();
            return true;
        } catch (Exception e) {
            if (tx != null) {
                //事务回滚
                tx.rollback();
            }
            e.printStackTrace();
            return false;
        } finally {
            try {
                closeResouce(session);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

    }
    @Override
    public Vo queryCouponRecharge(String vin, String account, String orderCode, String license, String phone, String queryDate1, String queryDate2, int page, int raws) {
        Vo vo = new Vo();
        //声明一个分页类用来存储页数和每页多少条数据
        PageInfo pageInfo=new PageInfo();
        pageInfo.setPage(page);
        pageInfo.setRows(raws);
        //sql动态拼接
        StringBuffer sql = new StringBuffer(
                "SELECT c.ID,c.VIN_CODE,u.code,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 " +
                        "LEFT JOIN (SELECT ID,CODE FROM user_order union SELECT ID,CODE FROM user_order_his) u on u.id = c.order_id " +
                        "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(license)) {
            sql.append("  and r.LICENSE like '%" + license + "%'");
        }
        if (StringUtils.isNotBlank(queryDate1)) {
            sql.append(" and c.RECHARGE_TIME >= '"+queryDate1+"'");
        }
        // 结束时间
        if (StringUtils.isNotBlank(queryDate2)) {
            sql.append(" and c.RECHARGE_TIME <= '"+queryDate2+"'");
        }
        String countSql=sql.append(" ORDER BY c.CREATE_TIME DESC").toString();
        String info=sql.append(" limit "+pageInfo.getCurrentIndex()+","+pageInfo.getRows()).toString();
        try {
            //获取充值记录
            List list =  getRsBySql(info);
            //获取充值记录总数
            List lists = getRsBySql(countSql);
            if (list != null && list.size() > 0) {
                vo.setRows(UtilTools.listTojsonArray(list, new String[]{"ID", "VIN_CODE", "ORDER_CODE", "RECHARGE_TIME", "RECHARGE_COUNT", "SEATE_NAME", "REMARK", "SERVICE_NAME", "OVERDUE_TIME", "CONSUME_COUNT", "ELECTRONIC_ACCOUNTS", "CREATE_TIME", "LICENSE", "USER_PHONE"}));
            }
            //获取充值记录总条数
            vo.setTotal(lists.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vo;
    }

    @Override
    public Vo getCoupon(String vin, String electronicAccounts, int page, int raws) {
        Vo vo = new Vo();
        //声明一个分页对象
        PageInfo pageInfo=new PageInfo();
        //获取页数和一页显示多少行并将其放入对象中
        pageInfo.setPage(page);
        pageInfo.setRows(raws);
        try {
//			select cj.electronic_accounts, cj.vin_code,cj.user_name,cj.user_phone,cj.license,cj.remark,
//			nvl((select sum((nvl((recharge_count),0)-nvl((consume_count),0))) as result from coupon_recharge_jlr j where j.overdue_time<SYSDATE and j.vin_code=cj.vin_code),0) as result
//			 from Coupon_Jlr cj
            StringBuffer sql = new StringBuffer("select cj.electronic_accounts, cj.vin_code,cj.user_name,cj.user_phone,cj.license,cj.remark,ifNull((select sum((ifNull((recharge_count),0)-ifNull((consume_count),0))) as result from jlr_coupon_recharge j where j.overdue_time>NOW() and j.vin_code=cj.vin_code),0) as result,cj.e_password from jlr_coupon cj where 1=1");
            if (!TextUtils.isEmpty(vin) || !TextUtils.isEmpty(electronicAccounts)) {
                if (!TextUtils.isEmpty(vin)) {
                    sql.append(" and cj.vin_code='" + vin + "'");
                }

                if (!TextUtils.isEmpty(electronicAccounts)) {
                    sql.append(" and cj.electronic_accounts='" + electronicAccounts + "'");
                }
            }
            String count=sql.toString();
            String info=sql.append(" limit "+pageInfo.getCurrentIndex()+","+pageInfo.getRows()).toString();
            List<Object[]> list = getRsBySql(info);
            List<CouponJlrVO> resultList = new ArrayList<>();
            for (Object[] obj : list) {
                CouponJlrVO couponvo = new CouponJlrVO();
                couponvo.setElectronicAccounts(MTextUtils.objectToString(obj[0]));
                couponvo.setVinCode(MTextUtils.objectToString(obj[1]));
                couponvo.setUserName(MTextUtils.objectToString(obj[2]));
                couponvo.setUserPhone(MTextUtils.objectToString(obj[3]));
                couponvo.setLicense(MTextUtils.objectToString(obj[4]));
                couponvo.setRemark(MTextUtils.objectToString(obj[5]));
                couponvo.setCharge(MTextUtils.stringToDouble(MTextUtils.objectToString(obj[6])));
                couponvo.setPassword(MTextUtils.objectToString(obj[7]));
                resultList.add(couponvo);
            }
            vo.setRows(resultList);
            List lists = getRsBySql(count);
            int size=lists.size();
            vo.setTotal(size);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return vo;
    }

    @Override
    public boolean consume(CouponConsumeJlrPO couponConsumeJlr, List<CouponRechargeJlrPO> couponRechargeJlrs) {
        Session session = null;
        Transaction tx = null;
        try {
            //获取session
            session = getSessionFactory().getCurrentSession().getSessionFactory().openSession();
            //开启事务
            tx = session.beginTransaction();
            //保存或修改
            session.saveOrUpdate(couponConsumeJlr);
            //批量保存或修改
            for (CouponRechargeJlrPO c : couponRechargeJlrs) {
                session.saveOrUpdate(c);
            }
            //提交事务
            tx.commit();
        } catch (Exception e) {
            if (tx != null) {
                //事务回滚
                tx.rollback();
            }
            e.printStackTrace();
            return false;
        } finally {
            try {
                closeResouce(session);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        return true;
    }
}
