package com.fdkankan.platform.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.common.constant.ConstantFilePath;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.constant.ServerCode;
import com.fdkankan.common.constant.TbStatus;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.util.*;
import com.fdkankan.platform.common.ConstantExcel;
import com.fdkankan.platform.common.ExcelUtil;
import com.fdkankan.common.factory.LogFactory;
import com.fdkankan.platform.goods.service.ICameraDetailService;
import com.fdkankan.platform.goods.service.ICompanyService;
import com.fdkankan.platform.order.constant.OrderEnum;
import com.fdkankan.platform.order.entity.*;
import com.fdkankan.platform.order.service.*;
import com.fdkankan.platform.user.entity.Manager;
import com.fdkankan.platform.user.entity.ReceiverInfo;
import com.fdkankan.platform.user.entity.User;
import com.fdkankan.platform.user.mapper.IManagerMapper;
import com.fdkankan.platform.user.request.*;
import com.fdkankan.platform.user.service.IManagerService;
import com.fdkankan.platform.user.service.IReceiverInfoService;
import com.fdkankan.platform.user.service.IUserService;
import com.fdkankan.platform.user.vo.*;
import com.fdkankan.sms.SendMailAcceUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.fdkankan.platform.common.ExcelUtil.output;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author 
 * @since 2021-12-24
 */
@Service
public class ManagerServiceImpl extends ServiceImpl<IManagerMapper, Manager> implements IManagerService {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IExpansionOrderService expansionOrderService;
    @Autowired
    private IIncrementOrderService incrementOrderService;
    @Autowired
    private IDownloadOrderService downloadOrderService;
    @Autowired
    private IVirtualOrderService virtualOrderService;
    @Autowired
    private ICameraDetailService cameraDetailService;
    @Autowired
    private IInvoiceService invoiceService;
    @Autowired
    private IReceiverInfoService iReceiverInfoService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ITradeLogService tradeLogService;
    @Autowired
    private ICompanyService companyService;

    QueryWrapper<Manager> queryWrapper;

    @Override
    public List<Manager> getByFrameworkId(Long parentId) {
        queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Manager::getTbStatus, TbStatus.VALID.code());
        queryWrapper.lambda().eq(Manager::getAgentFrameworkId,parentId);
        return  this.list(queryWrapper);
    }

    @Override
    public Manager getByUserName(String userName) {
        queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Manager::getTbStatus,TbStatus.VALID.code());
        queryWrapper.lambda().eq(Manager::getUsername,userName);
        return getEntityByQuery(queryWrapper);
    }


    private Manager getEntityByQuery(QueryWrapper<Manager> queryWrapper){
        List<Manager> list = this.list(queryWrapper);
        if(list == null || list.size() <= 0 ){
            return null;
        }
        return list.get(0);
    }

    @Override
    public  HashMap<String,Object> getHome() {
        Integer orderTodayCount = orderService.queryOrderCountByToday();
        BigDecimal todayTurnover = orderService.queryTurnoverByToday();
        BigDecimal monthTurnover = orderService.queryTurnoverByMonth();
        BigDecimal lastMonthTurnover = orderService.queryTurnoverByLastMonth();
        Integer sumcamera = orderService.queryAllPayOrdersCount();
        BigDecimal allcameramoneys = orderService.queryAllTurnoverByOrder();
        Integer waitCount = orderService.queryOrderCountByShippingStatus("unshipped");
        Integer todayRechargeCount = virtualOrderService.queryOrderCountByToday();
        BigDecimal todayRechargeTurnover = virtualOrderService.queryTurnoverByToday(1);
        BigDecimal monthRechargeTurnover = virtualOrderService.queryTurnoverByMonth();
        BigDecimal lastMonthRechargeTurnover = virtualOrderService.queryTurnoverByLastMonth();
        Integer allRechargeCount = virtualOrderService.queryAllCount();
        BigDecimal allRechargeTurnover = virtualOrderService.selectAllTurnover(1);
        List<ResponseVirtualOrder> trendRechargeOrder = virtualOrderService.queryTrendRechargeOrder(1);

        BigDecimal todayConsumeTurnover = virtualOrderService.queryTurnoverByToday(-1);
        BigDecimal allConsumeTurnover = virtualOrderService.selectAllTurnover(-1);
        List<ResponseVirtualOrder> trendConsumeOrder = virtualOrderService.queryTrendRechargeOrder(-1);

        BigDecimal monthMoney = monthRechargeTurnover.add(monthTurnover);
        BigDecimal lastMonthMoney = lastMonthRechargeTurnover.add(lastMonthTurnover);
        List<ResponseOrder> trendOrders = orderService.queryTrendOrder();

        BigDecimal allMoney = allcameramoneys.add(allRechargeTurnover);
        HashMap<String,Object> result = new HashMap<>();

        result.put("sumcamera", sumcamera);
        result.put("allcameramoneys", allcameramoneys);
        result.put("todayOrder", orderTodayCount);
        result.put("todayTurnover", todayTurnover);
        result.put("allMoney", allMoney);
        result.put("allRechargeCount", allRechargeCount);
        result.put("allRechargeTurnover", allRechargeTurnover);
        result.put("todayRecharge", todayRechargeCount);
        result.put("todayRechargeTurnover", todayRechargeTurnover);
        result.put("todayConsumeTurnover", todayConsumeTurnover);
        result.put("allConsumeTurnover", allConsumeTurnover);
        result.put("waitCount", waitCount);
        result.put("monthMoney", monthMoney);
        result.put("monthCamera", monthTurnover);
        result.put("monthRecharge", monthRechargeTurnover);
        result.put("lastMonthMoney", lastMonthMoney);
        result.put("lastMonthCamera", lastMonthTurnover);
        result.put("lastMonthRecharge", lastMonthRechargeTurnover);
        result.put("trendRecharge", trendRechargeOrder);
        result.put("consumeRecharge", trendConsumeOrder);
        result.put("trend", trendOrders);
        return result;
    }

    @Override
    public Page<JSONObject> findAllInvoiceByCondition(RequestCamera param) throws Exception {
        Page<ResponseCamera> cameras = cameraDetailService.queryListByParams(param);
        List<ResponseCamera> list = cameras.getRecords();
        List<JSONObject> jsonArray = new ArrayList<>();
        if (list!= null && list.size() > 0){
            for (ResponseCamera responseCamera : list){
                param.setChildName(responseCamera.getChildName());

                int initPoints = 0;
                int initInvoice = 0;
                int add = 0;
                int less = 0;
                int other = 0;
                int addInvoice = 0;
                int lessInvoice = 0;

                if (StringUtils.isNotEmpty(param.getStartDate())){
                    RequestCamera param1 = new RequestCamera();
                    param1.setChildName(responseCamera.getChildName());
                    param1.setEndDate(param.getStartDate());

                    List<VirtualOrder> startList = virtualOrderService.getAllByParam(param1);
                    for (VirtualOrder start : startList) {
                        int status = start.getStatus();
                        if (status == 0 || status == 1) {
                            initPoints += start.getPoints();
                            if (status == 1) {
                                initInvoice += start.getPoints();
                            }
                        } else if (status == -1 || status == -2) {
                            initPoints -= start.getPoints();
                            if (status == -2) {
                                initInvoice -= start.getPoints();
                            }
                        }
                    }
                }

                List<VirtualOrder> virtualOrderEntities = virtualOrderService.getAllByParam(param);
                for (VirtualOrder virtualOrderEntity : virtualOrderEntities) {
                    int status = virtualOrderEntity.getStatus();
                    if (status == 1 || status == 0) {
                        add += virtualOrderEntity.getPoints();
                        if (status == 1) {
                            addInvoice += virtualOrderEntity.getPoints();
                        }
                    } else if (status == -1) {
                        less += virtualOrderEntity.getPoints();
                    } else if (status == -2) {
                        other -= virtualOrderEntity.getPoints();
                    }
                }

                if (StringUtils.isNotEmpty(param.getStartDate())){
                    RequestTrade trade1 = new RequestTrade();
                    trade1.setSearchKey(param.getSearchKey());
                    trade1.setEndDate(param.getStartDate());
                    List<Invoice> invoices = invoiceService.getListByParam(trade1);
                    for (Invoice invoice : invoices){
                        initInvoice -= invoice.getMoney().intValue();
                    }
                }

                RequestTrade trade = new RequestTrade();
                trade.setSearchKey(param.getSearchKey());
                trade.setStartDate(param.getStartDate());
                trade.setEndDate(param.getEndDate());
                List<Invoice> invoices = invoiceService.getListByParam(trade);
                for (Invoice invoice : invoices){
                    lessInvoice +=invoice.getMoney().intValue();
                }

                JSONObject jo = new JSONObject();
                jo.put("userName", responseCamera.getUserName());
                jo.put("childName", responseCamera.getChildName());
                jo.put("initPoints", initPoints);
                jo.put("addPoints", add);
                jo.put("lessPoints", -1*less);
                jo.put("otherPoints", other);
                jo.put("endPoints", initPoints+add-less+other);
                jo.put("initInvoice", initInvoice);
                jo.put("addInvoice", addInvoice);
                jo.put("lessInvoice", lessInvoice);
                jo.put("endInvoice", initInvoice+addInvoice-lessInvoice+other);
                jo.put("otherCredits", other);
                jsonArray.add(jo);
            }
        }

        Page<JSONObject> pageVo = new Page<JSONObject>(param.getPageNum(), param.getPageSize());
        pageVo.setTotal(cameras.getTotal());
        pageVo.setRecords(jsonArray);
        return pageVo;
    }

    @Override
    public Page<ResponseInvoice> findInvoiceByCondition(RequestTrade param) {
        return invoiceService.getPageByParam(param);
    }

    @Override
    public String updateInvoiceStatus(Long invoiceId, Integer type) {
        Invoice invoiceEntity = invoiceService.getById(invoiceId);
        invoiceEntity.setFinish(type);
        if(!invoiceService.updateById(invoiceEntity)){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        return ServerCode.SUCCESS.message();
    }

    @Override
    public Page<ResponseInvoice> findInvoiceList(RequestTrade param) throws Exception {
        if(StringUtils.isNotEmpty(param.getOrderSn())){
            Order orderEntity = orderService.getByOrderSn(param.getOrderSn());
            if(orderEntity != null){
                param.setOrderId(orderEntity.getId());
                param.setConsumeType(0);
            }else {
                ExpansionOrder expansionOrder = expansionOrderService.getByOrderSn(param.getOrderSn());
                if(expansionOrder != null){
                    param.setOrderId(expansionOrder.getId());
                    param.setConsumeType(1);
                }else{
                    IncrementOrder incrementOrderEntity = incrementOrderService.getByOrderSn(param.getOrderSn());
                    if(incrementOrderEntity!=null){
                        param.setIncrementId(incrementOrderEntity.getId());
                        param.setConsumeType(2);
                    }else{
                        DownloadOrder downloadOrderEntity = downloadOrderService.getByOrderSn(param.getOrderSn());
                        if(downloadOrderEntity!=null){
                            param.setDownloadId(downloadOrderEntity.getId());
                            param.setConsumeType(3);
                        }else{
                            param.setOrderId(9999999999999L);
                        }
                    }
                }
            }
        }
        Page<ResponseInvoice> pageInfo = invoiceService.findInvoiceList(param);
        ResponseOrder orderDetail = new ResponseOrder();
        ResponseVirtualOrder virtualOrderDetail = new ResponseVirtualOrder();
        ResponseIncrementOrder incrementDetail = new ResponseIncrementOrder();
        ResponseDownloadOrder downloadDetail = new ResponseDownloadOrder();
        List<ResponseOrderItem> orderItems = null;
        ResponseOrderItem orderItem = null;
        StringBuilder goodsName = null;
        ReceiverInfo receiverInfoEntity = new ReceiverInfo();
        for(ResponseInvoice invoice : pageInfo.getRecords()){
            //购买相机的订单
            if(invoice.getConsumeType() == 0){
                orderDetail  = orderService.getOrderDetail(invoice.getOrderId());
                invoice.setOrderDetail(orderDetail);
            }

            //消费订单
            if(invoice.getConsumeType() == 1){
                virtualOrderDetail = virtualOrderService.getVoById(invoice.getVirtualOrderId());
                if(orderDetail!=null){
                    invoice.setResponseVirtualOrder(virtualOrderDetail);
                }
            }

            //会员权益
            if(invoice.getConsumeType() == 2){
                incrementDetail = incrementOrderService.getVoById(invoice.getIncrementOrderId());
                if(incrementDetail!=null){
                    invoice.setResponseIncrementOrder(incrementDetail);
                }
            }

            //会员权益
            if(invoice.getConsumeType() == 3){
                downloadDetail  = downloadOrderService.getVoById(invoice.getDownloadOrderId());
                if(downloadDetail!=null){
                    invoice.setResponseDownloadOrder(downloadDetail);
                }
            }

            receiverInfoEntity = iReceiverInfoService.getDefaultByUserId(invoice.getUserId());
            if(receiverInfoEntity!=null){
                invoice.setShipName(receiverInfoEntity.getShipName() == null?"" : receiverInfoEntity.getShipName());
                invoice.setShipMobile(receiverInfoEntity.getShipMobile() == null?"" : receiverInfoEntity.getShipMobile());
                invoice.setShipAreaPath( receiverInfoEntity.getShipAreaPath()== null?"" : receiverInfoEntity.getShipAreaPath());
                invoice.setShipAddress(receiverInfoEntity.getShipAddress()== null?"" : receiverInfoEntity.getShipAddress());
            }
        }
        return pageInfo;
    }

    @Override
    public String sendExpress(RequestInvoice param) {
        if(param.getInvoiceId() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        return invoiceService.sendExpress(param);
    }

    @Override
    public String uploadEInvoice(MultipartFile file, String invoiceId) throws Exception{
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        File targetFile = new File(ConstantFilePath.INVOICE_PATH + fileName);
        file.transferTo(targetFile);
        return ConstantFilePath.INVOICE_PATH.replace(ConstantFilePath.BASE_PATH, "") + fileName;
    }

    @Override
    public String sendEInvoice(Long invoiceId, String remarks, String filePath)throws Exception {
        if(invoiceId == null || StringUtils.isEmpty(filePath)){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        Invoice invoice = invoiceService.sendEInvoice(invoiceId, remarks, filePath);

        String ordersn = "";
        Long userId = null;
        if(invoice != null){
            if(StringUtils.isEmpty(invoice.getEmailAddress())){
                throw new BusinessException(ErrorCode.NOT_RECORD);
            }
            if(invoice.getOrderId() != null){
                ResponseOrder order  = orderService.getOrderDetail(invoice.getOrderId());
                if(order == null) {
                    ExpansionOrder expansionOrderEntity = expansionOrderService.getById(invoice.getOrderId());
                    if(expansionOrderEntity != null){
                        ordersn = expansionOrderEntity.getOrderSn();
                        userId = expansionOrderEntity.getUserId();
                    }
                }else {
                    ordersn = order.getOrderSn();
                    userId = order.getUserId();
                }
            }else if (invoice.getIncrementOrderId()!=null){
                IncrementOrder incrementOrderEntity = incrementOrderService.getById(invoice.getIncrementOrderId());
                if(incrementOrderEntity!=null ){
                    ordersn = incrementOrderEntity.getOrderSn();
                    userId = incrementOrderEntity.getUserId();
                }
            }else if(invoice.getDownloadOrderId()!=null){
                DownloadOrder downloadOrderEntity = downloadOrderService.getById(invoice.getDownloadOrderId());
                if(downloadOrderEntity!=null){
                    ordersn = downloadOrderEntity.getOrderSn();
                    userId = downloadOrderEntity.getUserId();
                }
            }
        }

        String subject = SendMailAcceUtils.subjectinvoice.replace("${ordernum}", ordersn);
        String msg = SendMailAcceUtils.msg;
        msg = msg.replace("${ordernum}", ordersn);
        User userEntity = userService.getById(userId);
        if(userEntity!=null){
            msg = msg.replace("${username}", userEntity.getUserName() == null?"":userEntity.getUserName());
        }else{
            msg = msg.replace("${username}", "");
        }

        //TODO aa
        //发送电子邮件
        boolean falg = SendMailAcceUtils.sendMail(invoice.getEmailAddress(), subject, msg, ConstantFilePath.BASE_PATH + invoice.getEInvoice());
        LogFactory.P_LOG.info("邮件发送状态：{}", falg);
        return ServerCode.SUCCESS.message();
    }

    @Override
    public void exportInvoiceList(RequestTrade param, HttpServletRequest request, HttpServletResponse response)throws Exception {
        param.setPageSize(9999);

        List<ResponseInvoice> list = invoiceService.getVoListByParam(param);
        ResponseOrder orderDetail = new ResponseOrder();
        ExpansionOrder expansionOrderEntity = new ExpansionOrder();
        List<ResponseOrderItem> orderItems = null;
        StringBuilder goodsName = null;
        ResponseIncrementOrder incrementDetail = new ResponseIncrementOrder();
        ResponseDownloadOrder downloadDetail = new ResponseDownloadOrder();
        ReceiverInfo receiverInfoEntity = new ReceiverInfo();

        //导出的数据
        int serNum = 1;
        Map<String, Object> item = null;
        List<Map> dataList = new ArrayList<Map>();
        for(ResponseInvoice invoice : list){

            if(invoice.getOrderId()==null && invoice.getVirtualOrderId()==null &&
                    invoice.getIncrementOrderId() == null && invoice.getDownloadOrderId() == null){
                continue;
            }

            //购买相机的订单
            item = new HashMap();
            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[0], String.valueOf(serNum));
            if(invoice.getType() == 2){
                item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[7], "增值税普通发票");
            }
            if(invoice.getType() == 3){
                item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[7], "增值税专用发票");
            }
            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[4], invoice.getExpressNumber()== null?"" : invoice.getExpressNumber());
            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[5], invoice.getMoney()== null?"" : String.valueOf(invoice.getMoney()));

            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[8], invoice.getTitle() == null?"" : invoice.getTitle());
            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[9], invoice.getCode() == null?"" : invoice.getCode());
            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[10], invoice.getOrganizedAddress() == null?"" : invoice.getOrganizedAddress());
            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[11], invoice.getRegisterPhone() == null?"" : invoice.getRegisterPhone());
            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[12], invoice.getBankName() == null?"" : invoice.getBankName());
            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[13], invoice.getBankAccount() == null?"" : invoice.getBankAccount());

            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[17], invoice.getEmailAddress() == null?"" : invoice.getEmailAddress());

            if(invoice.getConsumeType() == 0){
                orderDetail = orderService.getOrderDetail(invoice.getOrderId());

                item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[1], orderDetail.getOrderSn() == null?"" : orderDetail.getOrderSn());
//                item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[2], orderDetail.getUserName() == null?"" : orderDetail.getUserName());

                if(orderDetail.getUserId()!=null){
                    User userEntity = userService.getById(orderDetail.getUserId());
                    if(userEntity!=null){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[2], userEntity.getUserName() == null?"" : userEntity.getUserName());

                        if(invoice.getType() == 3){
                            //获取默认地址
                            receiverInfoEntity = iReceiverInfoService.getDefaultByUserId(orderDetail.getUserId());
                            if(receiverInfoEntity!=null){
                                item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[14], receiverInfoEntity.getShipName() == null?"" : receiverInfoEntity.getShipName());
                                item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[15], receiverInfoEntity.getShipMobile() == null?"" : receiverInfoEntity.getShipMobile());
                                item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[16], receiverInfoEntity.getShipAreaPath()== null?"" : receiverInfoEntity.getShipAreaPath()
                                        + " " + receiverInfoEntity.getShipAddress()== null?"" : receiverInfoEntity.getShipAddress());
                            }
                        }
                    }
                }

                if( orderDetail.getOrderTime() == null){
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[3], "");
                }else{
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[3], DateUtil.date2String(orderDetail.getOrderTime(),null));
                }

                if (orderDetail.getPaymentTypeName() ==null || orderDetail.getPaymentTypeName() == -1) {
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[6], "未支付");
                    continue;
                } else {
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[6], ConstantExcel.PAYFORM[orderDetail.getPaymentTypeName()]);
                }

                if(orderDetail.getOrderStatus()!=null){
                    if(orderDetail.getOrderStatus().equals("unprocessed")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[18], "未处理");
                    }else if(orderDetail.getOrderStatus().equals("processed")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[18], "已确认");
                    }else if(orderDetail.getOrderStatus().equals("completed")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[18], "已完成");
                    }else if(orderDetail.getOrderStatus().equals("invalid")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[18], "已取消");
                    }
                }else{
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[18], "");
                }

                if(orderDetail.getShippingStatus()!=null){
                    if(orderDetail.getShippingStatus().equals("unshipped")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[19], "未发货");
                    }else if(orderDetail.getShippingStatus().equals("partShipped")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[19], "部分发货");
                    }else if(orderDetail.getShippingStatus().equals("shipped")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[19], "已发货");
                    }else if(orderDetail.getShippingStatus().equals("partReshiped")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[19], "部分退货");
                    }else if(orderDetail.getShippingStatus().equals("reshiped")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[19], "已退货");
                    }else if(orderDetail.getShippingStatus().equals("received")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[19], "已收货");
                    }
                }else{
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[19], "");
                }

                if(orderDetail.getPaymentStatus()!=null){
                    if(orderDetail.getPaymentStatus().equals("unpaid")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "未付款");
                        continue;
                    }else if(orderDetail.getPaymentStatus().equals("paid")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "已付款");
                    }else if(orderDetail.getPaymentStatus().equals("cancel")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "已取消");
                    }else if(orderDetail.getPaymentStatus().equals("partPayment")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "部分支付");
                    }else if(orderDetail.getPaymentStatus().equals("partRefund")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "部分退款");
                    }else if(orderDetail.getPaymentStatus().equals("refunded")){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "全额退款");
                    }
                }else{
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "");
                }
            }else if(invoice.getConsumeType() == 1){
                expansionOrderEntity = expansionOrderService.getById(invoice.getOrderId());

                if(expansionOrderEntity!=null){
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[1], expansionOrderEntity.getOrderSn() == null?"" : expansionOrderEntity.getOrderSn());
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[5], expansionOrderEntity.getAmount()== null?"" : String.valueOf(expansionOrderEntity.getAmount()));
                    if(expansionOrderEntity.getUserId()!=null){
                        User userEntity = userService.getById(expansionOrderEntity.getUserId());
                        if(userEntity!=null){
                            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[2], userEntity.getUserName() == null?"" : userEntity.getUserName());
                            if(invoice.getType() == 3){
                                //获取默认地址
                                receiverInfoEntity = iReceiverInfoService.getDefaultByUserId(expansionOrderEntity.getUserId());
                                if(receiverInfoEntity!=null){
                                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[14], receiverInfoEntity.getShipName() == null?"" : receiverInfoEntity.getShipName());
                                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[15], receiverInfoEntity.getShipMobile() == null?"" : receiverInfoEntity.getShipMobile());
                                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[16], receiverInfoEntity.getShipAreaPath()== null?"" : receiverInfoEntity.getShipAreaPath()
                                            + " " + receiverInfoEntity.getShipAddress()== null?"" : receiverInfoEntity.getShipAddress());
                                }
                            }
                        }
                    }

                    if( expansionOrderEntity.getTradeTime() == null){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[3], "");
                    }else{
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[3], DateUtil.date2String(expansionOrderEntity.getTradeTime(),null));
                    }

                    if (expansionOrderEntity.getPayType() == -1) {
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[6], "未支付");
                        continue;
                    } else {
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[6], ConstantExcel.PAYFORM[expansionOrderEntity.getPayType()]);
                    }

                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[18], "");
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[19], "");

                    try{
                        if(expansionOrderEntity.getPayStatus() == 0 || expansionOrderEntity.getPayStatus() ==-1 ){
                            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "未付款");
                            continue;
                        }else if(expansionOrderEntity.getPayStatus() == -2 ){
                            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "已退款");
                        }else if(expansionOrderEntity.getPayStatus() == 1){
                            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "已付款");
                        }
                    }catch (Exception e){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "");
                    }
                }

            }else if(invoice.getConsumeType() == 2){
                incrementDetail = incrementOrderService.getVoById(invoice.getIncrementOrderId());

                if(incrementDetail!=null){
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[1], incrementDetail.getOrderSn() == null?"" : incrementDetail.getOrderSn());
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[5], incrementDetail.getAmount()== null?"" : String.valueOf(incrementDetail.getAmount()));
                    if(incrementDetail.getUserId()!=null){
                        User userEntity = userService.getById(incrementDetail.getUserId());
                        if(userEntity!=null){
                            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[2], userEntity.getUserName() == null?"" : userEntity.getUserName());

                            if(invoice.getType() == 3){
                                //获取默认地址
                                receiverInfoEntity = iReceiverInfoService.getDefaultByUserId(incrementDetail.getUserId());
                                if(receiverInfoEntity!=null){
                                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[14], receiverInfoEntity.getShipName() == null?"" : receiverInfoEntity.getShipName());
                                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[15], receiverInfoEntity.getShipMobile() == null?"" : receiverInfoEntity.getShipMobile());
                                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[16], receiverInfoEntity.getShipAreaPath()== null?"" : receiverInfoEntity.getShipAreaPath()
                                            + " " + receiverInfoEntity.getShipAddress()== null?"" : receiverInfoEntity.getShipAddress());
                                }
                            }
                        }
                    }

                    if( incrementDetail.getTradeTime() == null){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[3], "");
                    }else{
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[3], DateUtil.date2String(incrementDetail.getTradeTime(),null));
                    }

                    if (incrementDetail.getPayType() == null || incrementDetail.getPayType() == -1) {
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[6], "未支付");
                        continue;
                    } else {
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[6], ConstantExcel.PAYFORM[incrementDetail.getPayType()]);
                    }

                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[18], "");
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[19], "");

                    if(incrementDetail.getPayStatus()!=null){
                        if(incrementDetail.getPayStatus().equals(0) || incrementDetail.getPayStatus().equals(-1)){
                            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "未付款");
                            continue;
                        }else if(incrementDetail.getPayStatus().equals(-2)){
                            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "已退款");
                        }else if(incrementDetail.getPayStatus().equals(1)){
                            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "已付款");
                        }
                    }else{
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "");
                    }
                }

            }else if(invoice.getConsumeType() == 3){
                downloadDetail = downloadOrderService.getVoById(invoice.getDownloadOrderId());

                if(downloadDetail!=null){
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[1], downloadDetail.getOrderSn() == null?"" : downloadDetail.getOrderSn());
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[5], downloadDetail.getAmount()== null?"" : String.valueOf(downloadDetail.getAmount()));
                    if(downloadDetail.getUserId()!=null){
                        User userEntity = userService.getById(downloadDetail.getUserId());
                        if(userEntity!=null){
                            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[2], userEntity.getUserName() == null?"" : userEntity.getUserName());

                            if(invoice.getType() == 3){
                                //获取默认地址
                                receiverInfoEntity = iReceiverInfoService.getDefaultByUserId(downloadDetail.getUserId());
                                if(receiverInfoEntity!=null){
                                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[14], receiverInfoEntity.getShipName() == null?"" : receiverInfoEntity.getShipName());
                                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[15], receiverInfoEntity.getShipMobile() == null?"" : receiverInfoEntity.getShipMobile());
                                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[16], receiverInfoEntity.getShipAreaPath()== null?"" : receiverInfoEntity.getShipAreaPath()
                                            + " " + receiverInfoEntity.getShipAddress()== null?"" : receiverInfoEntity.getShipAddress());
                                }
                            }
                        }
                    }

                    if( downloadDetail.getTradeTime() == null){
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[3], "");
                    }else{
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[3], DateUtil.date2String(downloadDetail.getTradeTime(),null));
                    }

                    if (downloadDetail.getPayType() == null || downloadDetail.getPayType() == -1) {
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[6], "未支付");
                        continue;
                    } else {
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[6], ConstantExcel.PAYFORM[downloadDetail.getPayType()]);
                    }

                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[18], "");
                    item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[19], "");

                    if(downloadDetail.getPayStatus()!=null){
                        if(downloadDetail.getPayStatus().equals(0) || downloadDetail.getPayStatus().equals(-1)){
                            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "未付款");
                            continue;
                        }else if(downloadDetail.getPayStatus().equals(-2)){
                            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "已退款");
                        }else if(downloadDetail.getPayStatus().equals(1)){
                            item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "已付款");
                        }
                    }else{
                        item.put(ConstantExcel.INVOICEEXCELCOLENNAME2[20], "");
                    }
                }

            }

            serNum++;
            dataList.add(item);
        }

        String fileName = "发票数据-" + String.valueOf(System.currentTimeMillis()) + ".xls";
        File file = new File(FileUtils.getResource() + fileName + ".xls");

        ExcelUtil.writeExcel(dataList, ConstantExcel.INVOICEEXCELCOLENNAME2.length, FileUtils.getResource() + fileName + ".xls", 6);

        outXls(request,response,fileName,file);
    }
    @Override
    public void export(RequestOrder param, HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<ResponseOrder> orders = orderService.getPageVoByParam(param).getRecords();
        List<Map> dataList = new ArrayList<Map>();
        int serNum = 1;
        for (int i = 0; i < orders.size(); ++i) {
            ResponseOrder order = orders.get(i);
            Map<String, String> item = new HashMap();
            String num = order.getOrderSn();
            if (order.getPaymentStatus().equals(OrderEnum.PaymentStatus.unpaid.name())) { //未支付
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[0], String.valueOf(serNum));
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[1], "");
            } else {
                TradeLog trade = tradeLogService.getByOrderSn(order.getOrderSn());
                if (trade != null) {
                    if (trade.getPayStatus() != 1) {
                        //未支付
                        item.put(ConstantExcel.ORDEREXCELCOLENNAME[0], String.valueOf(serNum));
                        item.put(ConstantExcel.ORDEREXCELCOLENNAME[1], "");
                    } else {
                        //支付成功
                        item.put(ConstantExcel.ORDEREXCELCOLENNAME[0], String.valueOf(serNum));
                        if(!ObjectUtils.isEmpty(trade.getTradeTime())){
                            item.put(ConstantExcel.ORDEREXCELCOLENNAME[1], new SimpleDateFormat("yyyyMMddhhmmss").format(trade.getTradeTime()));
                        }
                    }
                } else {
                    continue;
                }
            }

            item.put(ConstantExcel.ORDEREXCELCOLENNAME[2], order.getOrderSn());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[3], order.getUserName());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[4], String.valueOf(order.getTotalAmount()));
            if (order.getPaymentTypeName() == -1) {
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[5], "未支付");
            } else {
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[5], ConstantExcel.PAYFORM[order.getPaymentTypeName()]);
            }
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[6], order.getShipAddress());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[7], order.getShipMobile());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[8], order.getShipName());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[9], ConstantExcel.getOrderStatus(order.getOrderStatus()));
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[10], ConstantExcel.getPaymentStatus(order.getPaymentStatus()));
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[11], ConstantExcel.getShippingStatus(order.getShippingStatus()));
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[12], order.getTradeNum());

            Invoice invoice = invoiceService.getByOrderId(order.getId());
            if (invoice == null) {
                continue;
            }
            int type = invoice.getType();
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[13], ConstantExcel.INVOICE[type - 1]);
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[14], invoice.getTitle());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[15], invoice.getCode());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[16], invoice.getOrganizedAddress());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[17], invoice.getRegisterPhone());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[18], invoice.getBankName());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[19], invoice.getBankAccount());
            ++serNum;
            dataList.add(item);
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = dateFormat.format(new Date());
        String fileName = dateStr + ".xls";
        File file = new File(FileUtils.getResource() + dateStr + ".xls");

        ExcelUtil.writeExcel(dataList, 20, FileUtils.getResource() + dateStr + ".xls", 1);

        outXls(request,response,fileName,file);
    }

    private void outXls(HttpServletRequest request,HttpServletResponse response,String fileName,File file) throws Exception{
        String agent = request.getHeader("User-Agent");
        if (agent != null && (agent.contains("MSIE")||agent.contains("Trident"))) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            //非IE浏览器的处理：
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        response.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
        response.setContentType(request.getServletContext().getMimeType(fileName));
        response.setContentLength((int) file.length());
        output(response, file);
    }

    @Override
    public List<Manager> managerList() {
        List<Long> ids = companyService.getManagerId();
        LambdaQueryWrapper<Manager> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Manager::getIsCompany,1).eq(Manager::getTbStatus,TbStatus.VALID.code());
        if(ids!=null || ids.size()>0){
            queryWrapper.notIn(Manager::getId,ids);
        }
        return  this.list(queryWrapper);
    }

    @Override
    public String companyUpdatePassword(RequestManager param, String token) {
        String userName = JwtUtil.getUsername(token);

        Manager managerEntity = this.getByUserName(userName.replace(SsoUtil.PREFIX_CACHE_MANAGER, ""));
        if (managerEntity == null){
            throw new BusinessException(ErrorCode.USER_NOT_LOGIN);
        }

        if(managerEntity.getIsCompany() != 1){
            throw new BusinessException(ErrorCode.NOT_PERMISSION);
        }

        //对前端传的密码解密
        String password = Base64Converter.decode(Base64Converter.subText(param.getPassword()));
        param.setPassword(password);

        String encryptPwd = PasswordUtils.encrypt(param.getUserName(), param.getPassword(), PasswordUtils.getStaticSalt());
        if (!encryptPwd.equals(managerEntity.getPassword())){
            throw new BusinessException(ErrorCode.PASSWORD_ERROR);
        }

        if(!param.getNewPassword().equals(param.getConfirmPwd())){
            throw new BusinessException(ErrorCode.PASSWORD_TWO_VIOLATION);
        }

        String newPassword = Base64Converter.decode(Base64Converter.subText(param.getNewPassword()));
        param.setNewPassword(newPassword);
        managerEntity.setPassword(PasswordUtils.encrypt(param.getUserName(), param.getNewPassword(), PasswordUtils.getStaticSalt()));
        this.updateById(managerEntity);
        return ServerCode.SUCCESS.message();
    }

    @Override
    public String saveManager(RequestManager param) {
        if(StringUtils.isEmpty(param.getUserName()) || StringUtils.isEmpty(param.getNickname()) ||
                param.getAgentFrameworkId() == null || param.getManagerRoleId() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }

        Manager managerEntity = this.getByUserName(param.getUserName());
        if(managerEntity != null){
            throw new BusinessException(ErrorCode.PHONE_EXIST);
        }

        managerEntity = new Manager();
        BeanUtils.copyProperties(param, managerEntity);
        managerEntity.setPassword(PasswordUtils.encrypt(param.getUserName(), "4dkankan", PasswordUtils.getStaticSalt()));
        this.save(managerEntity);
        return ServerCode.SUCCESS.message();
    }

    @Override
    public String updateManager(RequestManager param) {
        if(StringUtils.isEmpty(param.getUserName()) || StringUtils.isEmpty(param.getNickname()) ||
                param.getAgentFrameworkId() == null || param.getManagerRoleId() == null || param.getId() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }

        Manager managerEntity = this.getByUserName(param.getUserName());
        if(managerEntity != null && managerEntity.getId() != param.getId()){
            throw new BusinessException(ErrorCode.PHONE_EXIST);
        }

        managerEntity = new Manager();
        BeanUtils.copyProperties(param, managerEntity);
        this.updateById(managerEntity);
        return ServerCode.SUCCESS.message();
    }

    @Override
    public String updatePassword(RequestManager param) {
        if(StringUtils.isEmpty(param.getPassword()) || StringUtils.isEmpty(param.getNewPassword()) ||
                StringUtils.isEmpty(param.getConfirmPwd()) || param.getId() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }

        Manager managerEntity = this.getById(param.getId());
        if(managerEntity == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }

        String encryptPwd = PasswordUtils.encrypt(param.getUserName(), param.getPassword(), PasswordUtils.getStaticSalt());
        if (!encryptPwd.equals(managerEntity.getPassword())){
            throw new BusinessException(ErrorCode.PASSWORD_ERROR);
        }

        if(!param.getNewPassword().equals(param.getConfirmPwd())){
            throw new BusinessException(ErrorCode.PASSWORD_TWO_VIOLATION);
        }

        managerEntity.setPassword(PasswordUtils.encrypt(param.getUserName(), param.getNewPassword(), PasswordUtils.getStaticSalt()));
        this.updateById(managerEntity);
        return ServerCode.SUCCESS.message();
    }

    @Override
    public String deleteManager(RequestManager param) {
        if(param.getId() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        Manager managerEntity = this.getById(param.getId());
        if(managerEntity == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }
        managerEntity.setTbStatus(TbStatus.DELETE.code());
        this.updateById(managerEntity);
        return ServerCode.SUCCESS.message();
    }

    @Override
    public String restPassword(RequestManager param) {
        if(param.getId() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        Manager managerEntity = this.getById(param.getId());
        if(managerEntity == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }
        managerEntity.setPassword(PasswordUtils.encrypt(param.getUserName(), "4dkankan", PasswordUtils.getStaticSalt()));
        this.updateById(managerEntity);
        return ServerCode.SUCCESS.message();
    }

    @Override
    public Page<Manager> listNew(RequestManager param) {
        LambdaQueryWrapper<Manager> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(param.getUserName())){
            queryWrapper.like(Manager::getUsername,param.getUserName());
        }
        if(StringUtils.isNotEmpty(param.getNickname())){
            queryWrapper.like(Manager::getNickname,param.getNickname());
        }
        if(param.getAgentFrameworkId() != null){
            queryWrapper.eq(Manager::getAgentFrameworkId,param.getAgentFrameworkId());
        }
        if(param.getManagerRoleId() != null){
            queryWrapper.eq(Manager::getManagerRoleId,param.getManagerRoleId());
        }
        Page<Manager> page = new Page<>(param.getPageNum(),param.getPageSize());
        Page<Manager> pageResult = this.page(page, queryWrapper);
        for (Manager record : pageResult.getRecords()) {
            record.setPassword(null);
        }
        return pageResult;
    }
}
