package com.gree.mall.miniapp.logic.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.miniapp.bean.order.OrderDetailBean;
import com.gree.mall.miniapp.bean.order.OrderTaxCount;
import com.gree.mall.miniapp.bean.workorder.PgIncreVO;
import com.gree.mall.miniapp.constant.Constant;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.logic.workorder.IncreConfigLogic;
import com.gree.mall.miniapp.plus.entity.OrderTax;
import com.gree.mall.miniapp.plus.entity.PgIncreOrder;
import com.gree.mall.miniapp.plus.service.*;
import com.gree.mall.miniapp.utils.EmailUtilsNew;
import com.gree.mall.miniapp.utils.HttpUtils;
import com.gree.mall.miniapp.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderTaxLogic {
    @Autowired
    private OrderTaxService orderTaxService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    GoodsSpecService goodsSpecService;
    @Autowired
    GoodsCategoryService goodsCategoryService;
    @Autowired
    OrderLogic orderLogic;
   // @Value("${tax.token.appid}")
    private String clientId;
   // @Value("${tax.token.appSecret}")
    private String clientSecret;
 //   @Value("${tax.token.url}")
    private String taxTokenUrl;
   // @Value("${tax.invoice.title.url}")
    private String taxTitleUrl;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    CommonLogic commonLogic;

    @Autowired
    IncreConfigLogic increConfigLogic;
    
    @Autowired
    PgIncreOrderService pgIncreOrderService;



    private final static String EMAIL_SUBJECT = "发票";
    private final static String EMAIL_PREFIX = "请点击链接下载您的发票:\n\t";

    @Transactional
    public OrderTax saveTax(OrderTax orderTaxBean) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");

        String orderId = orderTaxBean.getOrderId();


        if (orderTaxBean.getOrderType().equals("ORDER")) {
            OrderDetailBean detail = orderLogic.detail(orderId);
            orderTaxBean.setCompanyWechatId(detail.getCompanyWechatId());
            orderTaxBean.setCompanyWechatName(detail.getCompanyWechatName());
            orderTaxBean.setWebsitId(detail.getWebsitId());
            orderTaxBean.setWebsitName(detail.getWebsitName());
            orderTaxBean.setAmount(detail.getPayAmount());
        }else {

            PgIncreOrder detail = pgIncreOrderService.getById(orderTaxBean.getOrderId());
            orderTaxBean.setCompanyWechatId(detail.getCompanyWechatId());
            orderTaxBean.setCompanyWechatName(detail.getCompanyWechatName());
            orderTaxBean.setWebsitId(detail.getWebsitId());
            orderTaxBean.setWebsitName(detail.getWebsitName());
            orderTaxBean.setAmount(detail.getAmount());
        }
        
        
        
        orderTaxBean.setOrderTaxId(null);
        orderTaxBean.setStatus(false);
        orderTaxBean.setCreateTime(new Date());
        if(orderTaxBean.getTaxNo() != null) {
            orderTaxBean.setTaxNo(orderTaxBean.getTaxNo().replaceAll(" ", ""));
        }
        orderTaxService.save(orderTaxBean);
        //标记订单已开发票
        if (orderTaxBean.getOrderType().equals("ORDER")) {
            orderLogic.tax(orderTaxBean.getOrderId(), orderTaxBean.getOrderTaxId());
        }else {
            increConfigLogic.tax(orderTaxBean.getOrderId(), orderTaxBean.getOrderTaxId());
        }
        return orderTaxBean;
    }

    public void updateTax(OrderTax orderTaxBean) {
        orderTaxService.lambdaUpdate().eq(OrderTax::getOrderTaxId, orderTaxBean.getOrderTaxId())
                .set(StringUtils.isNotBlank(orderTaxBean.getAccount()), OrderTax::getAccount, orderTaxBean.getAccount())
                .set(orderTaxBean.getType() != null, OrderTax::getType, orderTaxBean.getType())
                .set(orderTaxBean.getTaxType() != null, OrderTax::getTaxType, orderTaxBean.getTaxType())
                .set(StringUtils.isNotBlank(orderTaxBean.getName()), OrderTax::getName, orderTaxBean.getName())
                .set(StringUtils.isNotBlank(orderTaxBean.getTaxNo()), OrderTax::getTaxNo, orderTaxBean.getTaxNo())
                .set(StringUtils.isNotBlank(orderTaxBean.getRegisterAddress()), OrderTax::getRegisterAddress, orderTaxBean.getRegisterAddress())
                .set(StringUtils.isNotBlank(orderTaxBean.getRegisterPhone()), OrderTax::getRegisterPhone, orderTaxBean.getRegisterPhone())
                .set(StringUtils.isNotBlank(orderTaxBean.getBank()), OrderTax::getBank, orderTaxBean.getBank())
                .set(StringUtils.isNotBlank(orderTaxBean.getAccount()), OrderTax::getAccount, orderTaxBean.getAccount())
                .set(StringUtils.isNotBlank(orderTaxBean.getReceiverPhone()), OrderTax::getReceiverPhone, orderTaxBean.getReceiverPhone())
                .set(StringUtils.isNotBlank(orderTaxBean.getReceiverEmail()), OrderTax::getReceiverEmail, orderTaxBean.getReceiverEmail())
                .set(StringUtils.isNotBlank(orderTaxBean.getContent()), OrderTax::getContent, orderTaxBean.getContent())
                .update();
    }

    public String delTax(String orderTaxId) {
        orderTaxService.lambdaUpdate()
                .eq(OrderTax::getOrderTaxId, orderTaxId)
                .remove();
        return orderTaxId;
    }

    public String sendTax(String orderTaxId) {
        OrderTax orderTax = orderTaxService.lambdaQuery()
                .eq(OrderTax::getOrderTaxId, orderTaxId)
                .one();
//        if(orderTax.getTaxType()){
//            return "";
//        }
        String taxLink = orderTax == null ? null : orderTax.getTaxLink();
        if (StringUtils.isNotBlank(taxLink)) {
            new EmailUtilsNew().send(orderTax.getReceiverEmail(), EMAIL_SUBJECT, EMAIL_PREFIX + taxLink);
        }
        return taxLink;
    }





    public IPage<OrderTax> page(String userId,Boolean status, Integer pageNum, Integer pageSize) {
        return orderTaxService.lambdaQuery()
                .eq(StringUtils.isNotBlank(userId), OrderTax::getUserId, userId)
                .eq(status != null, OrderTax::getStatus, status)
                .orderByDesc(OrderTax::getCreateTime).page(new Page(pageNum, pageSize));

    }

    public OrderTax detail(String orderTaxId) {
        return orderTaxService.lambdaQuery()
                .eq(StringUtils.isNotBlank(orderTaxId), OrderTax::getOrderTaxId, orderTaxId)
                .one();

    }

    public Object title(String companyName) throws RemoteServiceException {
        HashMap<String, String> params = new HashMap();
        HashMap<String, String> heads = new HashMap();
        heads.put("authorization_token", getTaxToken());
        params.put("companyName", companyName);
        String content = HttpUtils.requestGet(taxTitleUrl, params, heads);
        if (content == null) {
            throw new RemoteServiceException("网络错误");
        }
        Map<String, Object> resMap = JSON.parseObject(content, new TypeReference<HashMap<String, Object>>() {
        });

        int code = (int) resMap.get("code");
        if (code == 1) {
            return resMap.get("data");
        }
        return null;
    }

    public String getTaxToken() throws RemoteServiceException {
        Object token = redisUtil.get(Constant.RedisPrefix.TOKEN_TAX);

        if (token != null) {
            return token.toString();
        }
        //过期就重新获取
        return this.deleteAndAddWxToken();
    }

    public String deleteAndAddWxToken() throws RemoteServiceException {
        HashMap<String, String> params = new HashMap();
        params.put("clientId", this.clientId);
        params.put("clientSecret", this.clientSecret);
        String content = HttpUtils.requestGet(taxTokenUrl, params, null);
        Map<String, Object> resMap = JSON.parseObject(content, new TypeReference<HashMap<String, Object>>() {
        });

        int code = (int) resMap.get("code");
        if (code == 1) {
            String token = (String) resMap.get("data");
            redisUtil.set(Constant.RedisPrefix.TOKEN_TAX, token, 2 * 60 * 60);//2小时过期
            return token;
        }
        return null;
    }

    public OrderTaxCount count(String userId) {

        Integer ywc = orderTaxService.lambdaQuery()
                .eq(StringUtils.isNotBlank(userId), OrderTax::getUserId, userId)
                .eq(OrderTax::getStatus, true)
           .count();

        Integer sqz = orderTaxService.lambdaQuery()
                .eq(StringUtils.isNotBlank(userId), OrderTax::getUserId, userId)
                .eq(OrderTax::getStatus, false)
                .count();

        Integer qb = orderTaxService.lambdaQuery()
                .eq(StringUtils.isNotBlank(userId), OrderTax::getUserId, userId)
                .count();

        OrderTaxCount orderTaxCount = new OrderTaxCount();
        orderTaxCount.setQb(qb);
        orderTaxCount.setSqz(sqz);
        orderTaxCount.setYwc(ywc);

        return orderTaxCount;

    }


/*
    public void yonge(MultipartFile file) throws RemoteServiceException, IOException {

        List<Object> datas = ExcelUtils.importExcel(file);
        List<String> tableHeaders = (List<String>)datas.get(0);

        Map<String,List<List<Object>>> map = new HashMap<>();
        for(int i=1 ;i<datas.size(); i++){
            List<Object> row = (List<Object>) datas.get(i);
            //邮箱
            String email = (String) row.get(0);

            List<List<Object>> objects = map.get(email);
            if(objects == null){
                objects = new ArrayList<>();
            }
            row.remove(0);
            objects.add(row);

            if(!map.containsKey(email)){
                map.put(email,objects);
            }
        }
        for(String email:map.keySet()){
            //String filePath = "B:/"+email+"-"+file.getName()+".xlsx";
            String filePath = "/app/tmp/"+email+"-"+file.getName()+".xlsx";
            this.createExcel(tableHeaders,map.get(email),filePath);
            new EmailUtilsNew().send(email, file.getName(), "请查收",filePath);
        }

    }*/


    /**
     * 创建Excel
     */
/*
    public void createExcel(List<String> tableHeaders,List<List<Object>> rows, String fileFullPath) {
        OutputStream out = null;
        try {
            out = new FileOutputStream(new File(fileFullPath));
            write(out, tableHeaders,rows);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
*/

/*

    */
/**
     * 生成Excel文件的方法write
     *
     * @param outputStream
     *//*

    public void write(OutputStream outputStream, List<String> tableHeaders,List<List<Object>> rows) {
        // 初始一个workbook
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 创建单个sheet
        XSSFSheet sheet = workbook.createSheet("sheet1");
        // 创建第一行，设置列名
        XSSFRow row0 = sheet.createRow(0);
        row0.setHeight((short) 400);             // 设置行高
        XSSFCell cell = null;                    // Excel的列
        XSSFFont font = workbook.createFont();// 设置字体
        font.setColor(HSSFFont.COLOR_NORMAL);           // 设置单元格字体的颜色
        XSSFCellStyle style = workbook.createCellStyle();// 样式
        // 设置边框颜色
        style.setTopBorderColor(HSSFColor.BLACK.index);
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        style.setRightBorderColor(HSSFColor.BLACK.index);
        // 设置文本格式
        XSSFDataFormat format = workbook.createDataFormat();
        style.setDataFormat(format.getFormat("@"));

        short cellNumber = (short) tableHeaders.size();  // 表的列数
        for (int k = 0; k < cellNumber; k++) {
            if(k == 0){
                continue;
            }
            int i = 0;
            i += k-1;
            short b = 5000;
            cell = row0.createCell(i);          // 创建第0行第k列
            cell.setCellValue(tableHeaders.get(k));  // 设置第0行第k列的值
            sheet.setColumnWidth(i, b);         // 设置列的宽度
            style.setFont(font);                // 设置字体风格
            cell.setCellStyle(style);
        }


        XSSFCellStyle styleContext = workbook.createCellStyle();
        styleContext.setWrapText(true);
        // 设置边框颜色
        styleContext.setTopBorderColor(HSSFColor.BLACK.index);
        styleContext.setBottomBorderColor(HSSFColor.BLACK.index);
        styleContext.setLeftBorderColor(HSSFColor.BLACK.index);
        styleContext.setRightBorderColor(HSSFColor.BLACK.index);
        // 设置文本格式
        styleContext.setDataFormat(format.getFormat("@"));

        if (rows.size() > 0) {
            // 创建剩余行
            for (int rowIndex = 0; rowIndex < rows.size(); rowIndex++) {
                XSSFRow row = sheet.createRow(rowIndex+1);
                List<Object> values = rows.get(rowIndex);
                // 创建多列
                for (int cellIndex = 0; cellIndex < values.size(); cellIndex++) {
                    cell = row.createCell(cellIndex);
                    cell.setCellStyle(styleContext);               // 设置风格
                    cell.setCellValue(values.get(cellIndex).toString());
                }
            }
        }
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

*/



}
