package com.xhpc.user.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import com.xhpc.common.core.constant.StatusConstants;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.core.web.service.BaseService;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.system.api.domain.SysUser;
import com.xhpc.system.api.model.LoginUser;
import com.xhpc.user.domain.XhpcCommunityPersonnel;
import com.xhpc.user.domain.XhpcCustomersPersonnel;
import com.xhpc.user.mapper.XhpcCommonMapper;
import com.xhpc.user.service.IXhpcCommonService;
import com.xhpc.user.service.IXhpcCommunityService;
import com.xhpc.user.service.IXhpcCustomersService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yuyang
 * @date 2021/12/29 11:11
 */
@Service
public class XhpcCommonServiceImpl extends BaseService implements IXhpcCommonService {

    @Autowired
    private XhpcCommonMapper xhpcCommonMapper;
    @Autowired
    private IXhpcCommunityService xhpcCommunityService;
    @Autowired
    private IXhpcCustomersService xhpcCustomersService;
    @Autowired
    TokenService tokenService;

    @Override
    public Map<String, Object> getLandUser(String phone,Long userId, Integer type,String serialNumber,String tenantId) {
        if(UserTypeUtil.USER_TYPE.equals(type)){
            return xhpcCommonMapper.getAppUser(phone,userId,tenantId);
        }else if(UserTypeUtil.COMMUNIT_TYPE.equals(type)){
            return xhpcCommonMapper.getCommunityUser(phone,userId,serialNumber,tenantId);
        }else if(UserTypeUtil.CUSTOMERS_TYPE.equals(type)){
            return xhpcCommonMapper.getCustomersUser(phone,userId,serialNumber,tenantId);
        }else if(UserTypeUtil.INTERNET_TYPE.equals(type)){
            return xhpcCommonMapper.getAppInternetUser(phone,userId,serialNumber,tenantId);
        }else if(UserTypeUtil.MOTORCADE_USER_TYPE.equals(type)){
            //个人
            return xhpcCommonMapper.getMotorcadeUser(phone,userId,serialNumber,tenantId);
        }else if(UserTypeUtil.MOTORCADE_TYPE.equals(type)){
            //车队总负责人
            return xhpcCommonMapper.getMotorcade(phone,userId,serialNumber,tenantId);
        }
        return new HashMap<>();
    }

    @Override
    public AjaxResult insertUserBalance(BigDecimal money, Long userId, Integer userType, String tenantId, Integer type,Integer status,String remark,Long moneyOrderId) {
        if(UserTypeUtil.USER_TYPE.equals(userType)){
            //C端用户暂不考虑

        }else if(UserTypeUtil.COMMUNIT_TYPE.equals(userType)){
            Map<String, Object> communityUser = xhpcCommonMapper.getCommunityUser(null, userId, null, tenantId);
            if(communityUser!=null){
                if(UserTypeUtil.INSERT_BALANCE.equals(status)){
                    XhpcCommunityPersonnel xhpcCommunityPersonnel=new XhpcCommunityPersonnel();
                    xhpcCommunityPersonnel.setCommunityPersonnelId(Long.valueOf(communityUser.get("appUserId").toString()));
                    xhpcCommunityPersonnel.setRechargeMoney(money);
                    xhpcCommunityPersonnel.setRemark(remark);
                    xhpcCommunityPersonnel.setRechargeType(type);
                    xhpcCommunityPersonnel.setTenantId(tenantId);
                    xhpcCommunityPersonnel.setMoneyOrderId(moneyOrderId);
                    return xhpcCommunityService.addRecharge(xhpcCommunityPersonnel);
                }
            }
        }else if(UserTypeUtil.CUSTOMERS_TYPE.equals(userType)){
            Map<String, Object> customersUser = xhpcCommonMapper.getCustomersUser(null, userId, null, tenantId);
            if(customersUser!=null){
                if(UserTypeUtil.INSERT_BALANCE.equals(status)){
                    XhpcCustomersPersonnel xhpcCustomersPersonnel =new XhpcCustomersPersonnel();
                    xhpcCustomersPersonnel.setCustomersPersonnelId(Long.valueOf(customersUser.get("appUserId").toString()));
                    xhpcCustomersPersonnel.setRechargeMoney(money);
                    xhpcCustomersPersonnel.setRemark(remark);
                    xhpcCustomersPersonnel.setRechargeType(type);
                    xhpcCustomersPersonnel.setTenantId(tenantId);
                    xhpcCustomersPersonnel.setMoneyOrderId(moneyOrderId);
                    return xhpcCustomersService.addRecharge(xhpcCustomersPersonnel);
                }
            }
        }
        return AjaxResult.error();
    }

    /**
     * 获取该机构的折扣比例
     *
     * @param userId   充值用户
     * @param userType 用户类型
     * @param tenantId 租户id
     * @return
     */
    @Override
    public AjaxResult getMechanismDiscount(Long userId, Integer userType, String tenantId, Long chargingStationId) {
        if(UserTypeUtil.COMMUNIT_TYPE.equals(userType)){
            return  AjaxResult.success(xhpcCommunityService.getCommunityPersonnelUserId(userId, tenantId,chargingStationId));
        }else if(UserTypeUtil.CUSTOMERS_TYPE.equals(userType)){
            return  AjaxResult.success(xhpcCustomersService.getCustomersPersonnelUserId(userId, tenantId,chargingStationId));
        }else if(UserTypeUtil.MOTORCADE_TYPE.equals(userType)){
            return  AjaxResult.success(xhpcCustomersService.getCustomersPersonnelUserId(userId, tenantId,chargingStationId));
        }else{
            return AjaxResult.error();
        }
    }

    /**
     * 根据用户手机号获取用户信息
     *
     * @param operatorId
     * @param chargingStationId
     * @param chargingPileId
     * @param type
     * @param name
     * @param phone
     * @param account
     */
    @Override
    public List<Map<String, Object>> getPersonnelStatistics(String tenantId,Long terminalId,Long operatorId, Long chargingStationId, Long chargingPileId, Integer type, String name, String phone, String account,String startTime,String endTime,String mark) {

        //获取登陆用户
        LoginUser loginUser = tokenService.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        Long sysUserId = sysUser.getUserId();
        //获取登陆用户
        List<Map<String, Object>> list =new ArrayList<>();

        if(!UserTypeUtil.SYS_USER_TYPE_ADMIN.equals(sysUser.getUserId())){
            startPage();
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType()) && StatusConstants.OPERATION_POWER_TYPE.equals(sysUser.getDataPowerType())){
                Long logOperatorId = sysUser.getOperatorId();
                //运营商看自己的场站
                if(type==null){
                    list = xhpcCommonMapper.getPersonnelStatistics(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 1,logOperatorId,tenantId,startTime,endTime,mark);
                }else if(type==1){
                    list = xhpcCommonMapper.getCommunityPersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 1,logOperatorId,tenantId,startTime,endTime,mark);
                }else if(type==2){
                    list = xhpcCommonMapper.getCustomersPersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 1,logOperatorId,tenantId,startTime,endTime,mark);
                }else{
                    list = xhpcCommonMapper.getMotorcadePersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 1,logOperatorId,tenantId,startTime,endTime,mark);
                }
            }else if(UserTypeUtil.SYS_MOTORCADE_TYPE_FOUR.equals(sysUser.getUserType()) && StatusConstants.MOTORCADE_TYPE.equals(sysUser.getDataPowerType())){
                Long logOperatorId = sysUser.getInternetUserId();
                //车队场站
                if(type==null){
                    list = xhpcCommonMapper.getMotorcadePersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 1,logOperatorId,tenantId,startTime,endTime,mark);
                }else if(type==1){
                    list = new ArrayList<>();
                }else if(type==2){
                    list = new ArrayList<>();
                }else{
                    list = xhpcCommonMapper.getMotorcadePersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 1,logOperatorId,tenantId,startTime,endTime,mark);
                }
            }else{
                //查询赋值的场站
                if(type==null){
                    list = xhpcCommonMapper.getPersonnelStatistics(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 2,sysUserId,tenantId,startTime,endTime,mark);
                }else if(type==1){
                    list = xhpcCommonMapper.getCommunityPersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 2,sysUserId,tenantId,startTime,endTime,mark);
                }else if(type==2){
                    list = xhpcCommonMapper.getCustomersPersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 2,sysUserId,tenantId,startTime,endTime,mark);
                }else{
                    list = xhpcCommonMapper.getMotorcadePersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 2,sysUserId,tenantId,startTime,endTime,mark);
                }
            }
        }else{
            startPage();
            if(type==null){
                list =xhpcCommonMapper.getPersonnelStatistics(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 0,sysUserId,tenantId,startTime,endTime,mark);
            }else if(type==1){
                list =xhpcCommonMapper.getCommunityPersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 0,sysUserId,tenantId,startTime,endTime,mark);
            }else if(type==2){
                list =xhpcCommonMapper.getCustomersPersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 0,sysUserId,tenantId,startTime,endTime,mark);
            }else{
                list =xhpcCommonMapper.getMotorcadePersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 0,sysUserId,tenantId,startTime,endTime,mark);
            }
        }
        return list;
    }

    @Override
    public void getPersonnelStatisticsExport(HttpServletResponse response, String tenantId,Long terminalId,Long operatorId, Long chargingStationId, Long chargingPileId, Integer type, String name, String phone, String account,String startTime,String endTime,String mark) throws IOException {
        LoginUser loginUser = tokenService.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        Long sysUserId = sysUser.getUserId();
        //获取登陆用户
        List<Map<String, Object>> list =new ArrayList<>();

        if(!UserTypeUtil.SYS_USER_TYPE_ADMIN.equals(sysUser.getUserId())){
            startPage();
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType()) && StatusConstants.OPERATION_POWER_TYPE.equals(sysUser.getDataPowerType())){
                Long logOperatorId = sysUser.getOperatorId();
                //运营商看自己的场站
                if(type==null){
                    list = xhpcCommonMapper.getPersonnelStatistics(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 1,logOperatorId,tenantId,startTime,endTime,mark);
                }else if(type==1){
                    list = xhpcCommonMapper.getCommunityPersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 1,logOperatorId,tenantId,startTime,endTime,mark);
                }else if(type==2){
                    list = xhpcCommonMapper.getCustomersPersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 1,logOperatorId,tenantId,startTime,endTime,mark);
                }else{
                    list = xhpcCommonMapper.getMotorcadePersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 1,logOperatorId,tenantId,startTime,endTime,mark);
                }
            }else if(UserTypeUtil.SYS_MOTORCADE_TYPE_FOUR.equals(sysUser.getUserType()) && StatusConstants.MOTORCADE_TYPE.equals(sysUser.getDataPowerType())){
                Long logOperatorId = sysUser.getInternetUserId();
                //车队场站
                if(type==null){
                    list = xhpcCommonMapper.getMotorcadePersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 1,logOperatorId,tenantId,startTime,endTime,mark);
                }else if(type==1){
                    list = new ArrayList<>();
                }else if(type==2){
                    list = new ArrayList<>();
                }else{
                    list = xhpcCommonMapper.getMotorcadePersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 1,logOperatorId,tenantId,startTime,endTime,mark);
                }
            }else{
                //查询赋值的场站
                if(type==null){
                    list = xhpcCommonMapper.getPersonnelStatistics(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 2,sysUserId,tenantId,startTime,endTime,mark);
                }else if(type==1){
                    list = xhpcCommonMapper.getCommunityPersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 2,sysUserId,tenantId,startTime,endTime,mark);
                }else if(type==2){
                    list = xhpcCommonMapper.getCustomersPersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 2,sysUserId,tenantId,startTime,endTime,mark);
                }else{
                    list = xhpcCommonMapper.getMotorcadePersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 2,sysUserId,tenantId,startTime,endTime,mark);
                }
            }
        }else{
            startPage();
            if(type==null){
                list =xhpcCommonMapper.getPersonnelStatistics(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 0,sysUserId,tenantId,startTime,endTime,mark);
            }else if(type==1){
                list =xhpcCommonMapper.getCommunityPersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 0,sysUserId,tenantId,startTime,endTime,mark);
            }else if(type==2){
                list =xhpcCommonMapper.getCustomersPersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 0,sysUserId,tenantId,startTime,endTime,mark);
            }else{
                list =xhpcCommonMapper.getMotorcadePersonnel(terminalId,operatorId, chargingStationId, chargingPileId, type, name,phone,account, 0,sysUserId,tenantId,startTime,endTime,mark);
            }
        }
        // 通过工具类创建writer，默认创建xls格式
        BigExcelWriter writer = ExcelUtil.getBigWriter("机构人员统计.xlsx");
        writer.addHeaderAlias("mechanismName", "机构类型");
        writer.addHeaderAlias("account", "机构账号");
        writer.addHeaderAlias("name", "用户名称");
        writer.addHeaderAlias("phone", "手机号");
        writer.addHeaderAlias("vinNumber", "ViN码");
        writer.addHeaderAlias("number", "充电次数");
        writer.addHeaderAlias("totalPower", "充电度数");
        writer.addHeaderAlias("totalPrice", "充电金额");
        writer.addHeaderAlias("promotionDiscount", "优惠金额");
        writer.setOnlyAlias(true);
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(list, true);
        //out为OutputStream，需要写出到的目标流
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        ServletOutputStream out = response.getOutputStream();

        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }
}
