package com.community.huiju.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.community.commom.mode.ResponseBean;
import com.community.commom.session.UserElement;
import com.community.huiju.dao.BillInvoiceMapper;
import com.community.huiju.dao.TpBillOrderMapper;
import com.community.huiju.model.BillInvoice;
import com.community.huiju.model.BillStatement;
import com.community.huiju.dao.BillStatementMapper;
import com.community.huiju.model.TpBillOrder;
import com.community.huiju.service.IBillStatementService;
import com.google.common.collect.Maps;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 账单流水表 服务实现类
 * </p>
 *
 * @author weiximei
 * @since 2019-02-13
 */
@Service
public class BillStatementServiceImpl extends ServiceImpl<BillStatementMapper, BillStatement> implements IBillStatementService {

    @Autowired
    private BillStatementMapper billStatementMapper;

    @Autowired
    private TpBillOrderMapper tpBillOrderMapper;

    @Autowired
    private BillInvoiceMapper billInvoiceMapper;

    @Override
    public ResponseBean getBillStatement(UserElement userElement, String parameter) {
        ResponseBean responseBean = new ResponseBean();
        JSONObject jsonObject = JSONObject.parseObject(parameter);

        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        // 订单号 orderBumber
        String orderBumber = jsonObject.getString("orderBumber");
        // 缴费项 id
        Integer billId = jsonObject.getInteger("billId");
        // 缴费项 名称
        String billName = jsonObject.getString("billName");
        // 缴费单 编号
        Integer billInvoiceId = jsonObject.getInteger("billInvoiceId");
        // 缴费人手机号
        String payPhone = jsonObject.getString("payPhone");

        // 参数
        Map<String, Object> map = Maps.newHashMap();
        map.put("orderBumber", orderBumber);
        map.put("billId", billId);
        map.put("billName", billName);
        map.put("billInvoiceId", billInvoiceId);
        map.put("payPhone", payPhone);
        map.put("communityId", userElement.getCommunityId());

        Page<TpBillOrder> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        IPage<TpBillOrder> billOrderIPage = tpBillOrderMapper.getBillOrderAll(page, map);
        // 这里拿到的订单数据，都是进过去重之后的
        List<TpBillOrder> orderRecords = billOrderIPage.getRecords();

        /**
         * 根据去重之后的订单，再去查询每个订单的缴费信息
         */

        // 1.查询缴费组id集合
        // 2.查询缴费单id集合
        // 3.缴费单总金额

        orderRecords.forEach(e-> {
            QueryWrapper<TpBillOrder> billOrderQueryWrapper = new QueryWrapper<>();
            billOrderQueryWrapper.eq("order_bumber", e.getOrderBumber());
            List<TpBillOrder> childBillOrderList = tpBillOrderMapper.selectList(billOrderQueryWrapper);

            // 缴费组id集合
            List<Integer> billIdCollect = childBillOrderList.stream().map(billOrder -> billOrder.getTpBillId()).collect(Collectors.toList());
            // 缴费单id集合
            List<Integer> billInvoiceIdCollect = childBillOrderList.stream().map(billOrder -> billOrder.getTpBillInvoiceId()).collect(Collectors.toList());
            // 总金额
            Long sumPrice = childBillOrderList.stream().map(billOrder -> {
                BillInvoice billInvoice = billInvoiceMapper.selectById(billOrder.getTpBillInvoiceId());
                return billInvoice.getPayPrice();
            }).count();

            e.setBillIdList(billIdCollect);
            e.setBillInvoiceIdList(billInvoiceIdCollect);
            e.setSumPrice(sumPrice);
        });

        Map<String, Object> respMap = Maps.newHashMap();
        respMap.put("list", orderRecords);
        respMap.put("pageNum", billOrderIPage.getCurrent());
        respMap.put("pageSize", billOrderIPage.getSize());
        respMap.put("total", billOrderIPage.getTotal());

        responseBean.addSuccess(respMap);
        return responseBean;
    }

    @Override
    public ResponseBean exportExcel(UserElement userElement) {
        ResponseBean responseBean = new ResponseBean();
        String [] title = new String[] { "流水号","收费组编号","收费组名称","收费单号","费用金额","缴费人","缴费备注","缴费方式","流水生成时间"};

        HSSFWorkbook excel = excel(title, userElement,null);
        responseBean.addSuccess(excel);
        return responseBean;
    }

    /**
     * 表格
     * @param title
     * @param workbook
     * @return
     */
    private HSSFWorkbook excel(String[] title, UserElement userElement, HSSFWorkbook workbook) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        if (null == workbook) {
            workbook = new HSSFWorkbook();
        }
        HSSFSheet sheet = workbook.createSheet("缴费单");
        // 行数标记
        int rowNum = 0;
        // 创建一行,用作标题
        HSSFRow row = sheet.createRow(rowNum);
        // 创建样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 居中
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        // 创建列对象
        HSSFCell cell = null;

        // 写入表头
        for (int i = 0; i<title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }

        Map<String, Object> map = Maps.newHashMap();
        map.put("communityId", userElement.getCommunityId());

        Page<BillStatement> page = new Page<>();
        page.setCurrent(1);
        page.setSize(500);
        IPage<BillStatement> billInvoiceIPage = billStatementMapper.getBillStatementAll(page, map);
        List<BillStatement> records = billInvoiceIPage.getRecords();


        // 写入内容
        for (int i = 1; i<= billInvoiceIPage.getPages(); i++) {
            for (int t = 0; t<records.size(); t++) {
                row = sheet.createRow(++rowNum);
                // 流水号
                cell = row.createCell(0);
                cell.setCellValue(records.get(t).getId());
                cell.setCellStyle(style);
                // 收费组编号
                cell = row.createCell(1);
                cell.setCellValue(records.get(t).getBillId());
                cell.setCellStyle(style);
                // 收费组名称
                cell = row.createCell(2);
                cell.setCellValue(records.get(t).getBillName());
                cell.setCellStyle(style);
                // 收费单号
                cell = row.createCell(3);
                cell.setCellValue(records.get(t).getBillInvoiceId());
                cell.setCellStyle(style);
                // 费用金额
                cell = row.createCell(4);
                double price = Double.valueOf(records.get(t).getPayPrice()) / 100.00;
                cell.setCellValue(price);
                cell.setCellStyle(style);
                // 缴费人
                cell = row.createCell(5);
                cell.setCellValue(records.get(t).getPayName());
                cell.setCellStyle(style);
                // 缴费备注
                cell = row.createCell(6);
                cell.setCellValue(records.get(t).getPayRemark());
                cell.setCellStyle(style);
                // 缴费方式
                cell = row.createCell(7);
                cell.setCellValue("0".equals(records.get(t).getPayType()) ? "微信支付" : "1".equals(records.get(t).getPayType()) ? "线下缴费" : "未知");
                cell.setCellStyle(style);
                if (null != records.get(t).getCreateTime()) {
                    // 生成流水时间
                    cell = row.createCell(8);
                    cell.setCellValue(dateFormat.format(records.get(t).getCreateTime()));
                    cell.setCellStyle(style);
                }
            }
            page.setCurrent(i);
            page.setSize(500);
            billInvoiceIPage = billStatementMapper.getBillStatementAll(page, map);
            records = billInvoiceIPage.getRecords();

        }

        return workbook;
    }

}
