package com.xhpc.payment.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import com.xhpc.common.core.constant.StatusConstants;
import com.xhpc.common.domain.XhpcRechargeOrder;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.payment.mapper.XhpcRechargeOrderMapper;
import com.xhpc.payment.service.IXhpcRechargeOrderService;
import com.xhpc.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 充值订单信息 服务层
 *
 * @author ruoyi
 */
@Service
public class XhpcRechargeOrderServiceImpl implements IXhpcRechargeOrderService {

    @Autowired
    private XhpcRechargeOrderMapper xhpcRechargeOrderMapper;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private XhpcUserAccountStatementServiceImpl xhpcUserAccountStatementService;

    /**
     * 更新 充值订单
     *
     * @param xhpcRechargeOrder 充值订单
     */
    @Override
    @Transactional
    public int update(XhpcRechargeOrder xhpcRechargeOrder) {
        return xhpcRechargeOrderMapper.update(xhpcRechargeOrder);
    }


    /**
     * 充值订单详情
     *
     * @param rechargeOrderId 充值订单id
     * @return 结果
     */
    @Override
    public Map<String, Object> info(Long rechargeOrderId) {
        return xhpcRechargeOrderMapper.info(rechargeOrderId);
    }

    /**
     * 充值订单分页列表
     *
     * @param phone
     * @param rechargeOrderNumber
     * @param status
     * @param createTimeStart
     * @param createTimeEnd
     * @return
     */
    @Override
    public List<Map<String, Object>> page(String phone, String rechargeOrderNumber, String status, String createTimeStart, String createTimeEnd,Integer type,Integer source,Integer userId) {
        LoginUser loginUser = tokenService.getLoginUser();
        return xhpcRechargeOrderMapper.page(phone, rechargeOrderNumber, status, createTimeStart, createTimeEnd,type,source,userId,loginUser.getTenantId());
    }


    @Override
    public void export(HttpServletResponse response, String phone, String rechargeOrderNumber, String status, String createTimeStart, String createTimeEnd, Integer type,Integer source,Integer userId) throws IOException {
        LoginUser loginUser = tokenService.getLoginUser();
        List<Map<String, Object>> list = xhpcRechargeOrderMapper.page(phone, rechargeOrderNumber, status, createTimeStart, createTimeEnd,type,source,userId,loginUser.getTenantId());

        // 通过工具类创建writer，默认创建xls格式
        BigExcelWriter writer = ExcelUtil.getBigWriter("RechargeOrder_" + System.currentTimeMillis() + ".xlsx");
        writer.addHeaderAlias("rechargeOrderId", "充值订单id");
        writer.addHeaderAlias("rechargeOrderNumber", "充值订单编号");
        writer.addHeaderAlias("userId", "C端用户id");
        writer.addHeaderAlias("amount", "退款金额");
        writer.addHeaderAlias("alipayNumber", "账号");
        writer.addHeaderAlias("prepayid", "微信编号");
        writer.addHeaderAlias("type", "充值渠道（1微信 2支付宝 3平台）");
        writer.addHeaderAlias("source", "订单来源（0 C端用户 1 流量方用户 2 社区用户 3 B端用户）");
        writer.addHeaderAlias("status", "状态（0待支付 1充值成功，2充值失败）");
        writer.addHeaderAlias("createTime", "充值时间");
        writer.addHeaderAlias("phone", "账号");
        writer.addHeaderAlias("statusName", "充值状态");

        // 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
        writer.setOnlyAlias(true);
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(list, true);
        //out为OutputStream，需要写出到的目标流

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

//        //response为HttpServletResponse对象
//        response.setContentType("application/vnd.ms-excel;charset=utf-8");
//        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
//        response.setHeader("Content-Disposition", "attachment;filename=充值订单列表.xls");
        ServletOutputStream out = response.getOutputStream();

        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }


    @Override
    public Map<String, Object> sumMoney(String phone, String rechargeOrderNumber, String status, String createTimeStart, String createTimeEnd, Integer type,Integer source,Integer userId) {
        LoginUser loginUser = tokenService.getLoginUser();
        //昨日用户的活跃度
        Date newDate1 = DateUtil.offset(new Date(), DateField.DAY_OF_MONTH, -1);
        String time1 = DateUtil.format(newDate1, "yyyy-MM-dd HH:mm:ss");
        //7天用户的活跃度
        Date newDate2 = DateUtil.offset(new Date(), DateField.DAY_OF_MONTH, -7);
        String time2 = DateUtil.format(newDate2, "yyyy-MM-dd HH:mm:ss");
        //一个月用户的活跃度
        Date newDate3 = DateUtil.offset(new Date(), DateField.DAY_OF_MONTH, -30);
        String time3 = DateUtil.format(newDate3, "yyyy-MM-dd HH:mm:ss");
        //3个月天用户的活跃度
        Date newDate4 = DateUtil.offset(new Date(), DateField.DAY_OF_MONTH, -90);
        String time4 = DateUtil.format(newDate4, "yyyy-MM-dd HH:mm:ss");
        return xhpcRechargeOrderMapper.sumMoney(phone, rechargeOrderNumber, status, createTimeStart, createTimeEnd, type,source,userId,loginUser.getTenantId(),time1,time2,time3,time4);
    }

    @Override
    public Map<String, Object> sumUserMoney(String phone, String rechargeOrderNumber, String status, String createTimeStart, String createTimeEnd, Integer type,Integer source,Integer userId) {
        LoginUser loginUser = tokenService.getLoginUser();
        //昨日用户的活跃度
        return xhpcRechargeOrderMapper.sumUserMoney(phone, rechargeOrderNumber, status, createTimeStart, createTimeEnd, type,source,userId,loginUser.getTenantId());
    }
    /**
     * 新增 充值订单
     *
     * @param appUserId C端用户id
     * @param amount    充值金额
     * @param type      充值渠道（1微信 2支付宝）
     * @return
     */
    @Override
    @Transactional
    public XhpcRechargeOrder addRechargeOrder(String appUserId, BigDecimal amount, String type, String orderNumber,Integer userType,String serialNumber) {
        XhpcRechargeOrder xhpcRechargeOrder = new XhpcRechargeOrder();
        xhpcRechargeOrder.setUserId(Long.parseLong(appUserId));
        xhpcRechargeOrder.setAmount(amount);
        xhpcRechargeOrder.setRechargeOrderNumber(orderNumber);
        xhpcRechargeOrder.setType(Integer.parseInt(type));
        xhpcRechargeOrder.setCreateTime(new Date());
        xhpcRechargeOrder.setSource(userType);
        if(serialNumber !=null && !"".equals(serialNumber)){
            xhpcRechargeOrder.setSerialNumber(serialNumber);
            xhpcRechargeOrder.setPreRecharge(1);
        }
        xhpcRechargeOrderMapper.insert(xhpcRechargeOrder);
        return xhpcRechargeOrder;
    }

    /**
     * 修改订单状态 充值订单
     *
     * @param rechargeOrderId 充值订单id
     * @param status          状态（0待支付 1充值成功，2充值失败）
     * @param type            充值渠道（1微信 2支付宝）
     * @return
     */
    @Override
    @Transactional
    public void updateRechargeOrder(Long rechargeOrderId, String type, Integer status, String paymentNumber) {
        XhpcRechargeOrder xhpcRechargeOrder = new XhpcRechargeOrder();
        xhpcRechargeOrder.setRechargeOrderId(rechargeOrderId);
        xhpcRechargeOrder.setStatus(status);
        if (StatusConstants.OPERATION_WX_TYPE.equals(type)) {
            xhpcRechargeOrder.setPrepayId(paymentNumber);
        } else {
            xhpcRechargeOrder.setAlipayNumber(paymentNumber);
        }
//        if (StatusConstants.RECHARGE_ORDER_STATUS_SUCCESS == xhpcRechargeOrder.getStatus()) {
//            Map<String, Object> map = xhpcRechargeOrderMapper.info(rechargeOrderId);
//            String amount = StringUtils.valueOf(map.get("amount"));
//            String userId = StringUtils.valueOf(map.get("userId"));
//            xhpcUserAccountStatementService.add(rechargeOrderId, amount, userId, Integer.parseInt(type));
//        }
        xhpcRechargeOrderMapper.update(xhpcRechargeOrder);
    }

    /**
     * 修改充值订单 退款金额
     *
     * @param rechargeOrderId 充值订单id
     * @param refundFee       退款金额（元）
     * @param refundStatus    退款金额状态（0 未退款 1未退款完 2全部已退还）
     * @return
     */
    @Override
    public void updateRechargeOrderFeundFee(Long rechargeOrderId, BigDecimal refundFee, Integer refundStatus) {
        XhpcRechargeOrder xhpcRechargeOrder = new XhpcRechargeOrder();
        xhpcRechargeOrder.setRechargeOrderId(rechargeOrderId);
        xhpcRechargeOrder.setRefundFee(refundFee);
        xhpcRechargeOrder.setRefundStatus(refundStatus);
        xhpcRechargeOrderMapper.update(xhpcRechargeOrder);
    }

    /**
     * 充值订单详情
     *
     * @param rechargeOrderNumber 充值订单编号
     * @return 结果
     */
    @Override
    public XhpcRechargeOrder infoRechargeOrderNumber(String rechargeOrderNumber) {
        return xhpcRechargeOrderMapper.infoRechargeOrderNumber(rechargeOrderNumber);
    }

    @Override
    public void updateRechargeOrderStatus() {
        xhpcRechargeOrderMapper.updateRechargeOrderStatus();
    }

}
