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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.tax.OrderTaxExcelBean;
import com.gree.mall.manager.bean.tax.RspOrderTax;
import com.gree.mall.manager.commonmapper.TaxMapper;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.goods.GoodsLogic;
import com.gree.mall.manager.plus.entity.GoodsCategory;
import com.gree.mall.manager.plus.entity.OrderInfo;
import com.gree.mall.manager.plus.entity.OrderTax;
import com.gree.mall.manager.plus.service.OrderInfoService;
import com.gree.mall.manager.plus.service.OrderTaxService;
import com.gree.mall.manager.utils.DateUtils;
import com.gree.mall.manager.utils.excel.ExcelUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderTaxLogic {

    @Autowired
    private OrderTaxService orderTaxService;
    @Autowired
    TaxMapper taxMapper;
    @Autowired
    OrderLogic orderLogic;
    @Autowired
    GoodsLogic goodsLogic;
    @Autowired
    CommonLogic commonLogic;
    @Autowired
    OrderInfoService orderInfoService;

    /**
     * 线下处理发票
     */
    public void offline(String orderTaxId) throws  RemoteServiceException {
        OrderTax orderTax = orderTaxService.getById(orderTaxId);
        if(!orderTax.getTaxType()){
            throw new RemoteServiceException("非专票不可处理");
        }
        orderTax.setStatus(true);
        orderTax.updateById();
    }


    public void updateTax(String orderTaxId,String taxlink){
        orderTaxService.lambdaUpdate().eq(StringUtils.isNotBlank(orderTaxId),OrderTax::getOrderTaxId,orderTaxId)
                .set(StringUtils.isNotBlank(taxlink),OrderTax::getTaxLink,taxlink)
                .set(OrderTax::getStatus,true)
                .update();
    }


    public void updateInfo(String orderTaxId, String name,String taxNo,String receiverName,String receiverPhone,String receiveEmail,String receiverAddress) throws RemoteServiceException {

        //判断是否允许修改,已开票的不许修改
        OrderTax orderTax = orderTaxService.getById(orderTaxId);
        if(!orderTax.getStatus()){
            throw new RemoteServiceException("已开票的不许修改");
        }
        //修改
        orderTaxService.lambdaUpdate()
                .eq(OrderTax::getStatus,false)
                .eq(OrderTax::getOrderTaxId,orderTaxId)
                .set(StringUtils.isNotEmpty(name),OrderTax::getName,name)
                .set(StringUtils.isNotEmpty(taxNo),OrderTax::getTaxNo,taxNo)
                .set(StringUtils.isNotEmpty(receiverName),OrderTax::getReceiverName,receiverName)
                .set(StringUtils.isNotEmpty(receiverPhone),OrderTax::getReceiverPhone,receiverPhone)
                .set(StringUtils.isNotEmpty(receiveEmail),OrderTax::getReceiverEmail,receiveEmail)
                .set(StringUtils.isNotEmpty(receiverAddress),OrderTax::getReceiverAddress,receiverAddress)
                .update();




    }


    public IPage<RspOrderTax> page(Boolean status,String orderId, Integer pageNum, Integer pageSize,HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        IPage page = orderTaxService.lambdaQuery()
                .like(StringUtils.isNotEmpty(orderId),OrderTax::getOrderId,orderId)
                .in(CollectionUtils.isNotEmpty(adminUser.getAdminCompanyIds()),OrderTax::getCompanyWechatId,adminUser.getAdminCompanyIds())
                ////.//in(CollectionUtils.isNotEmpty(adminUser.getAdminWebsitIds()),OrderTax::getWebsitId,adminUser.getAdminWebsitIds())
                .eq(status != null, OrderTax::getStatus, status)
                .orderByDesc(OrderTax::getCreateTime).page(new Page(pageNum, pageSize));

        List<RspOrderTax> list = new ArrayList<>();
        for(Object o : page.getRecords()){
            OrderTax tax = (OrderTax)o;
            RspOrderTax rspOrderTax = new RspOrderTax();
            BeanUtils.copyProperties(tax,rspOrderTax);
            final OrderInfo orderInfo = orderInfoService.getById(tax.getOrderId());
            if (Objects.nonNull(orderInfo)) {
                rspOrderTax.setBuyerName(orderInfo.getBuyerName());
                rspOrderTax.setBuyerMobile(orderInfo.getBuyerMobile());
                rspOrderTax.setBuyerIdCard(orderInfo.getBuyerIdCard());
                rspOrderTax.setCouponMerchantContribute(orderInfo.getCouponMerchantContribute());
            }
            List<GoodsCategory> goodsCategories = taxMapper.queryGoodsCategoryByOrderId(tax.getOrderId());
            if(goodsCategories.size() == 0){
                continue;
            }
            List<String> categoryNames = goodsCategories.stream().map(GoodsCategory::getName).distinct().collect(Collectors.toList());
            rspOrderTax.setCategoryNames(StringUtils.join(categoryNames,","));
            list.add(rspOrderTax);
        }
        page.setRecords(list);
        return page;
    }

    /**
     * 导出发票信息
     */
    public void exportOrderTax(Boolean status, String orderId, HttpServletRequest request, HttpServletResponse response) throws Exception {

        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getAdminCompanyIds();
        List<String> adminWebsitIds = adminUser.getAdminWebsitIds();

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat();
        List<List<Object>> rowList=new ArrayList<>();

        ExcelData excelData=new ExcelData();
        excelData.setRows(rowList);
        excelData.setName("发票");
        excelData.setTitles(
                Arrays.asList(
                        "发票编号","订单编号","用户编号","公司/个人","专票/普票","公司名称或个人名","纳税人识别号",
                        "公司注册地址","公司注册电话","开户银行","银行账号","接收电话","接收邮箱","收票人名称",
                        "收票人地址","发票内容","已开票/未开票","电子发票下载链接","创建时间","商品分类","订单支付时间"
                )
        );
        adminWebsitIds = null;
        List<OrderTaxExcelBean> orderTaxExcelBeanList = taxMapper.queryOrderTaxExcelMsg(companyWechatIds, adminWebsitIds, status, orderId);
        for (OrderTaxExcelBean orderTaxExcelBean:orderTaxExcelBeanList
             ) {
            List<Object> row=new ArrayList<>();
            rowList.add(row);

            row.add(orderTaxExcelBean.getOrderTaxId());
            row.add(orderTaxExcelBean.getOrderId());
            row.add(orderTaxExcelBean.getUserId());
            row.add(orderTaxExcelBean.getType()==null?"":(orderTaxExcelBean.getType()?"公司":"个人"));
            row.add(orderTaxExcelBean.getTaxType()==null?"":(orderTaxExcelBean.getTaxType()?"专票":"普票"));
            row.add(orderTaxExcelBean.getName());
            row.add(orderTaxExcelBean.getTaxNo());
            row.add(orderTaxExcelBean.getRegisterAddress());
            row.add(orderTaxExcelBean.getRegisterPhone());
            row.add(orderTaxExcelBean.getBank());
            row.add(orderTaxExcelBean.getAccount());
            row.add(orderTaxExcelBean.getReceiverPhone());
            row.add(orderTaxExcelBean.getReceiverEmail());
            row.add(orderTaxExcelBean.getReceiverName());
            row.add(orderTaxExcelBean.getReceiverAddress());
            row.add(orderTaxExcelBean.getContent());
            row.add(orderTaxExcelBean.getStatus()==null?"":(orderTaxExcelBean.getStatus()?"已开":"待开"));
            row.add(orderTaxExcelBean.getTaxLink());
            row.add(orderTaxExcelBean.getCreateTime()==null?"":DateUtils.formatDate(orderTaxExcelBean.getCreateTime()));
            row.add(orderTaxExcelBean.getCategoryNames());
            row.add(orderTaxExcelBean.getPayTime() == null ? "" : DateUtils.formatDate(orderTaxExcelBean.getPayTime()));
        }


        ExcelUtils.exportExcel(request,response,String.format("发票导出%s.xlsx", simpleDateFormat.format(new Date())),excelData);

    }
}
