package com.iformall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.WxMerchantSubsidy;
import com.iformall.domain.vo.WxMerchantSubsidyVo;
import com.iformall.enums.EnumMerchantSubsidyStatus;
import com.iformall.enums.EnumOrderType;
import com.iformall.mapper.WxMerchantSubsidyMapper;
import com.iformall.service.WxMerchantSubsidyService;
import com.iformall.utils.Constant;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.iformall.common.IdWorker;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class WxMerchantSubsidyServiceImpl implements WxMerchantSubsidyService {
	
	@Autowired
    WxMerchantSubsidyMapper wxMerchantSubsidyMapper;

    @Override
    public Map<String, Object> sumForSubsidy(WxMerchantSubsidy record) {
        return wxMerchantSubsidyMapper.sumVoList(record);
    }


    @Override
    public PageInfo<WxMerchantSubsidyVo> listAsPage(WxMerchantSubsidy record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxMerchantSubsidyMapper.findVoList(record));
    }

    @Override
    public WxMerchantSubsidy getById(Long id) {
        return wxMerchantSubsidyMapper.selectByPrimaryKey(id);
    }

    @Override
    public ResultData saveOrUpdate(WxMerchantSubsidy record) {
        if (record.getId() == null) {
            //record.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            final IdWorker idWorker = IdWorker.get();
        	record.setId(idWorker.nextId());
            wxMerchantSubsidyMapper.insertSelective(record);
        } else {
            int num = wxMerchantSubsidyMapper.updateByPrimaryKeySelective(record);
            return new ResultData(num);
        }
        return new ResultData();
    }

    @Override
    public ResultData update(WxMerchantSubsidy record) {
        String idStr = record.getIdStr();
        if (StringUtils.isEmpty(idStr)) {
            return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "结单数据没有传入");
        }
        wxMerchantSubsidyMapper.updateByCond(record);
        return new ResultData(Result.SUCCESS, "操作成功");
    }

    @Override
    public void deleteById(Long id) {
        wxMerchantSubsidyMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void exportData(WxMerchantSubsidy wxMerchantSubsidy, HttpServletRequest request, HttpServletResponse response) {
        List<WxMerchantSubsidyVo> subsidyVoList = wxMerchantSubsidyMapper.findVoList(wxMerchantSubsidy);

        XSSFWorkbook workbook;
        String filepath = Constant.fileDirectory;
        File savefile = new File(filepath);
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        String filename = UUID.randomUUID() + ".xlsx";
        filepath = filepath + filename;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DecimalFormat df = new DecimalFormat("0.00");

        try {
            File file = new File(filepath);
            workbook = new XSSFWorkbook();
            XSSFSheet sheetTwo = workbook.createSheet("补贴记录");
            Row rowtwo = sheetTwo.createRow(0);
            Cell idCellTwo = rowtwo.createCell(0);
            Cell merchantNameCellTwo = rowtwo.createCell(1);
            Cell createDateCellTwo = rowtwo.createCell(2);
            Cell orderPaymentCellTwo = rowtwo.createCell(3);
            Cell receiverPaymentCellTwo = rowtwo.createCell(4);
            Cell subsidyCellTwo = rowtwo.createCell(5);
            Cell statusCellTwo = rowtwo.createCell(6);

            idCellTwo.setCellValue("交易单号");
            merchantNameCellTwo.setCellValue("消费商户");
            createDateCellTwo.setCellValue("交易时间");
            orderPaymentCellTwo.setCellValue("本次消费(元)");
            receiverPaymentCellTwo.setCellValue("商户应收(元)");
            subsidyCellTwo.setCellValue("补贴(元)");
            statusCellTwo.setCellValue("补贴状态");

            for (int i = 0; i < subsidyVoList.size(); i++) {
                rowtwo = sheetTwo.createRow(i + 1);
                idCellTwo = rowtwo.createCell(0);
                merchantNameCellTwo = rowtwo.createCell(1);
                createDateCellTwo = rowtwo.createCell(2);
                orderPaymentCellTwo = rowtwo.createCell(3);
                receiverPaymentCellTwo = rowtwo.createCell(4);
                subsidyCellTwo = rowtwo.createCell(5);
                statusCellTwo = rowtwo.createCell(6);

                WxMerchantSubsidyVo entity = subsidyVoList.get(i);

                idCellTwo.setCellValue(String.valueOf(entity.getOrderId()));
                merchantNameCellTwo.setCellValue(entity.getMerchantName());
                if (entity.getCreateDate() != null)
                    createDateCellTwo.setCellValue(sdf.format(entity.getCreateDate()));
                String dStr = df.format((float)entity.getOrderPayment()/100);
                orderPaymentCellTwo.setCellValue(dStr);
                dStr = df.format((float)entity.getReceiverPayment()/100);
                receiverPaymentCellTwo.setCellValue(dStr);
                dStr = df.format((float)entity.getSubsidy()/100);
                subsidyCellTwo.setCellValue(dStr);
                String statusStr = "未补贴";
                if (entity.getStatus().equals(EnumMerchantSubsidyStatus.NOT_SUBSIDY.getCode())) {
                    statusStr = "未补贴";
                } else if (entity.getStatus().equals(EnumMerchantSubsidyStatus.AUTO_SUBSIDIED.getCode())) {
                    statusStr = "已自动补贴";
                } else if (entity.getStatus().equals(EnumMerchantSubsidyStatus.MANUAL_SUBSIDIED.getCode())) {
                    statusStr = "已手工补贴";
                }
                statusCellTwo.setCellValue(statusStr);
            }


            FileOutputStream fileOut = new FileOutputStream(file);
            workbook.write(fileOut);
            fileOut.close();
            workbook.close();
            downFile(filepath, filename,"补贴记录.xlsx",response, request);
            FileUtils.forceDelete(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void downFile(String filePath, String filename, String exportFileName,
                         HttpServletResponse response, HttpServletRequest req) throws IOException {
        try {
            response.reset();
            response.setContentType("bin");
            String agent = req.getHeader("user-agent");
            if (agent.contains("Firefox")) {
                response.setHeader("Content-disposition",
                        "attachment; filename="
                                + new String(exportFileName.getBytes("GB2312"),
                                "ISO-8859-1"));
            } else {
                response
                        .setHeader("Content-disposition",
                                "attachment; filename="
                                        + java.net.URLEncoder.encode(exportFileName,
                                        "UTF-8"));
            }
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            InputStream inStream = new FileInputStream(filePath);
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
}
