package com.iformall.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iformall.common.IdWorker;
import com.iformall.domain.dto.WxCUserBasicInfoDto;
import com.iformall.domain.po.WxChartDataEntity;
import com.iformall.domain.po.WxCouponOrder;
import com.iformall.domain.po.WxMall;
import com.iformall.domain.po.WxMerchantTradeDaily;
import com.iformall.enums.EnumCarCmd;
import com.iformall.enums.EnumChartType;
import com.iformall.mapper.*;
import com.iformall.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gongbiao
 */
@Component
public class ChartDataSchedule {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxCarCmdLogMapper wxCarCmdLogMapper;

    @Autowired
    WxMallMapper wxMallMapper;

    @Autowired
    WxCUserCarMapper wxCUserCarMapper;

    @Autowired
    WxChartDataMapper wxChartDataMapper;

    @Autowired
    WxCouponOrderMapper wxCouponOrderMapper;

    @Autowired
    WxMerchantTradeDailyMapper wxMerchantTradeDailyMapper;


    /**
     * 每天7点执行
     */
    @Scheduled(cron = "0 0 7 * * ?")
    public void createData() {
        createCarData();
        createSaleData();
        createMerchantTradeData();
    }

    /**
     * 出场车辆、缴费车辆、缴费金额、新增会员、新增停车会员、已绑车辆
     */
    public void createCarData() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("cmdType", EnumCarCmd.CAR_ETCP_CALLBACK_PARK_OUT.getCode());
        Date createtime = new Date();
        String startdate = DateUtils.getTimeBefore(1, createtime);
        Date date = DateUtils.stringToDate(startdate);
        params.put("startdate", startdate + " 00:00:00");
        params.put("enddate", startdate + " 23:59:59");

        WxChartDataEntity wxChartDataEntity = new WxChartDataEntity();
        wxChartDataEntity.setQuerytime(date);

        List<WxMall> wxMalls = wxMallMapper.findList(null);
        for (WxMall wxMall : wxMalls) {
            String tenantId = wxMall.getTenantId();
            params.put("tenantId", tenantId);
            wxChartDataEntity.setTenantId(tenantId);
            wxChartDataEntity.setType(EnumChartType.CAR_OUT.getCode());
            int count = wxChartDataMapper.selectCount(new QueryWrapper(wxChartDataEntity));
            if (count == 0) {
                logger.info("出场车数>>>>>>>>>>>>>>>>>>>>>>>>>>");
                carOutData(params, createtime, date, tenantId);
            }
            wxChartDataEntity.setType(EnumChartType.CAR_PAID.getCode());
            count = wxChartDataMapper.selectCount(new QueryWrapper(wxChartDataEntity));
            if (count == 0) {
                params.put("cmdType", EnumCarCmd.CAR_ETCP_CALLBACK_PAY_MANUAL.getCode());
                logger.info("缴费车辆>>>>>>>>>>>>>>>>>>>>>>>>>>");
                carPaidData(params, createtime, date, tenantId);
            }
            wxChartDataEntity.setType(EnumChartType.CAR_PAY_FEE.getCode());
            count = wxChartDataMapper.selectCount(new QueryWrapper(wxChartDataEntity));
            if (count == 0) {
                logger.info("缴费金额>>>>>>>>>>>>>>>>>>>>>>>>>>");
                carPayFeeData(params, createtime, date, tenantId);
            }
            wxChartDataEntity.setType(EnumChartType.CAR_MEMBER.getCode());
            count = wxChartDataMapper.selectCount(new QueryWrapper(wxChartDataEntity));
            if (count == 0) {
                logger.info("新增会员>>>>>>>>>>>>>>>>>>>>>>>>>>");
                carMemberData(params, createtime, date, tenantId);
            }
            wxChartDataEntity.setType(EnumChartType.CAR_NEW_MEMBER.getCode());
            count = wxChartDataMapper.selectCount(new QueryWrapper(wxChartDataEntity));
            if (count == 0) {
                logger.info("新增停车会员>>>>>>>>>>>>>>>>>>>>>>>>>>");
                carNewMemberData(createtime, date, tenantId);
            }
            wxChartDataEntity.setType(EnumChartType.CAR_BIND.getCode());
            count = wxChartDataMapper.selectCount(new QueryWrapper(wxChartDataEntity));
            if (count == 0) {
                logger.info("已绑车辆>>>>>>>>>>>>>>>>>>>>>>>>>>");
                carBindData(params, createtime, date, tenantId);
            }
        }
    }

    /**
     * 销售总交易额
     */
    public void createSaleData() {
        HashMap<String, Object> params = new HashMap<>();
        Date createtime = new Date();
        String yesterday = DateUtils.getTimeBefore(1, createtime);
        String today = DateUtils.getSystemTime("yyyy-MM-dd");
        Date startdate = DateUtils.stringToDate(yesterday);
        Date enddate = DateUtils.stringToDate(today);

        WxChartDataEntity wxChartDataEntity = new WxChartDataEntity();
        wxChartDataEntity.setQuerytime(startdate);

        List<WxMall> wxMalls = wxMallMapper.findList(null);
        for (WxMall wxMall : wxMalls) {
            String tenantId = wxMall.getTenantId();
            params.put("tenantId", tenantId);
            wxChartDataEntity.setTenantId(tenantId);
            wxChartDataEntity.setType(EnumChartType.SALE_COUPON_PRICE.getCode());
            int count = wxChartDataMapper.selectCount(new QueryWrapper(wxChartDataEntity));
            if (count == 0) {
                logger.info("销售总交易额>>>>>>>>>>>>>>>>>>>>>>>>>>");
                WxCouponOrder wxCouponOrder = new WxCouponOrder();
                wxCouponOrder.setTenantId(tenantId);
                wxCouponOrder.setStartTime(startdate);
                wxCouponOrder.setEndTime(enddate);
                Integer price = wxCouponOrderMapper.queryPriceTotal(wxCouponOrder);
                addChartData(tenantId, price.toString(), EnumChartType.SALE_COUPON_PRICE.getCode(), startdate, createtime);
            }
        }
    }

    /**
     * 解单金额
     */
    public void createMerchantTradeData() {
        HashMap<String, Object> params = new HashMap<>();
        Date createtime = new Date();
        String yesterday = DateUtils.getTimeBefore(1, createtime);
        Date querytime = DateUtils.stringToDate(yesterday);

        WxChartDataEntity wxChartDataEntity = new WxChartDataEntity();
        wxChartDataEntity.setQuerytime(querytime);

        List<WxMall> wxMalls = wxMallMapper.findList(null);
        for (WxMall wxMall : wxMalls) {
            String tenantId = wxMall.getTenantId();
            params.put("tenantId", tenantId);

            wxChartDataEntity.setTenantId(tenantId);
            wxChartDataEntity.setType(EnumChartType.MERCHANT_TRADE.getCode());
            int count = wxChartDataMapper.selectCount(new QueryWrapper(wxChartDataEntity));
            if (count == 0) {
                logger.info("解单金额>>>>>>>>>>>>>>>>>>>>>>>>>>");
                WxMerchantTradeDaily wxMerchantTradeDaily = new WxMerchantTradeDaily();
                wxMerchantTradeDaily.setTenantId(tenantId);
                wxMerchantTradeDaily.setReportDate(yesterday);
                List<WxMerchantTradeDaily> recordList = wxMerchantTradeDailyMapper.findTotalListOfMonth(wxMerchantTradeDaily);
                Integer price = 0;
                if (!recordList.isEmpty()) {
                    price = Integer.parseInt(recordList.get(0).getTradeAmt());
                }
                addChartData(tenantId, price.toString(), EnumChartType.MERCHANT_TRADE.getCode(), querytime, createtime);
            }
        }
    }


    public void carBindData(HashMap<String, Object> params, Date createtime, Date date, String tenantId) {
        Long todaybindcar = wxCUserCarMapper.queryCarCount(params);
        addChartData(tenantId, todaybindcar.toString(), EnumChartType.CAR_BIND.getCode(), date, createtime);
    }

    public void carNewMemberData(Date createtime, Date date, String tenantId) {
        WxCUserBasicInfoDto wxCUserBasicInfoDto = new WxCUserBasicInfoDto();
        wxCUserBasicInfoDto.setTenantId(tenantId);
        wxCUserBasicInfoDto.setStartTime(date);
        wxCUserBasicInfoDto.setEndTime(date);
        Integer carUserCount = wxCUserCarMapper.countUser(wxCUserBasicInfoDto);
        addChartData(tenantId, carUserCount.toString(), EnumChartType.CAR_NEW_MEMBER.getCode(), date, createtime);
    }

    public void carMemberData(HashMap<String, Object> params, Date createtime, Date date, String tenantId) {
        List<Map<String, Object>> carCountHistory = wxCUserCarMapper.queryCarCountHistory(params);
        Long userCount = carCountHistory.isEmpty() ? 0L : (Long) carCountHistory.get(0).get("count");
        addChartData(tenantId, userCount.toString(), EnumChartType.CAR_MEMBER.getCode(), date, createtime);
    }

    public void carPayFeeData(HashMap<String, Object> params, Date createtime, Date date, String tenantId) {
        List<Map<String, Object>> weekCarPayHistoryList = wxCarCmdLogMapper.queryWeekCarPay(params);
        BigDecimal fee = weekCarPayHistoryList.isEmpty() ? new BigDecimal(0) : (BigDecimal) weekCarPayHistoryList.get(0).get("fee");
        addChartData(tenantId, fee.toString(), EnumChartType.CAR_PAY_FEE.getCode(), date, createtime);
    }

    public void carPaidData(HashMap<String, Object> params, Date createtime, Date date, String tenantId) {
        Long carPayFeeCount = wxCarCmdLogMapper.queryWeekCarPayCount(params);
        addChartData(tenantId, carPayFeeCount.toString(), EnumChartType.CAR_PAID.getCode(), date, createtime);
    }

    public void carOutData(HashMap<String, Object> params, Date createtime, Date date, String tenantId) {
        List<Map<String, Object>> historylist = wxCarCmdLogMapper.queryHistory(params);
        Long carOutCount = historylist.isEmpty() ? 0L : (Long) historylist.get(0).get("carcount");
        addChartData(tenantId, carOutCount.toString(), EnumChartType.CAR_OUT.getCode(), date, createtime);
    }

    private void addChartData(String tenantId, String result, Integer type, Date querytime, Date createtime) {
        logger.info("即将插入数据>>>>>>>>>>>>>>>>>>>>>>>");
        final IdWorker idWorker = IdWorker.get();
        long id = idWorker.nextId();
        WxChartDataEntity wxChartDataEntity = new WxChartDataEntity();
        wxChartDataEntity.setId(id);
        wxChartDataEntity.setTenantId(tenantId);
        wxChartDataEntity.setResult(result);
        wxChartDataEntity.setType(type);
        wxChartDataEntity.setQuerytime(querytime);
        wxChartDataEntity.setCreatetime(createtime);
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>" + wxChartDataEntity.toString());
        wxChartDataMapper.insert(wxChartDataEntity);
    }

}