package vip.xiaonuo.sale.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import vip.xiaonuo.production.entity.ProductionWorkstopPlan;
import vip.xiaonuo.sale.entity.*;
import vip.xiaonuo.sale.entity.vo.SaleTargetDetailVo;
import vip.xiaonuo.sale.entity.vo.SaleTargetVo;
import vip.xiaonuo.sale.mapper.*;
import vip.xiaonuo.sale.param.SaleCustomerParam;
import vip.xiaonuo.sale.param.SaleDetailPageParam;
import vip.xiaonuo.sale.param.SaleParam;
import vip.xiaonuo.sale.service.ISaleTargetService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 销售指标 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-13
 */
@Service
public class SaleTargetServiceImpl extends ServiceImpl<SaleTargetMapper, SaleTarget> implements ISaleTargetService {

    @Autowired
    private SaleTargetMapper targetMapper;
    @Autowired
    private SaleInvoiceMapper invoiceMapper;
    @Autowired
    private SaleDeliverMapper deliverMapper;
    @Autowired
    private SaleOrderMapper orderMapper;
    @Autowired
    private SaleReceiveMapper receiveMapper;

    @Override
    public JSONArray getTarget(SaleParam saleParam) {
        String orgId = saleParam.getOrgId();
        String time = saleParam.getTime();
        String year = time.substring(0, 4);//2025-02

        //销售发货金额
        QueryWrapper<SaleDeliver> deliverQueryWrapper = new QueryWrapper<>();
        deliverQueryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        deliverQueryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
        deliverQueryWrapper.select(" IFNULL(sum(sale_deliver_money),'0') saleDeliverMoney");
        SaleDeliver monthDeliver = deliverMapper.selectOne(deliverQueryWrapper);
        deliverQueryWrapper.clear();
        deliverQueryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        deliverQueryWrapper.between("create_time", year + "-01-01 00:00:00", year + "-12-31 23:59:59");
        deliverQueryWrapper.select(" IFNULL(sum(sale_deliver_money),'0') saleDeliverMoney");
        SaleDeliver yearDeliver = deliverMapper.selectOne(deliverQueryWrapper);
        //销售发票金额
        QueryWrapper<SaleInvoice> invoiceQueryWrapper = new QueryWrapper<>();
        invoiceQueryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        invoiceQueryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
        invoiceQueryWrapper.select(" IFNULL(sum(sale_invoice_money),'0') saleInvoiceMoney");
        SaleInvoice monthInvoice = invoiceMapper.selectOne(invoiceQueryWrapper);
        invoiceQueryWrapper.clear();
        invoiceQueryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        invoiceQueryWrapper.between("create_time", year + "-01-01 00:00:00", year + "-12-31 23:59:59");
        invoiceQueryWrapper.select(" IFNULL(sum(sale_invoice_money),'0') saleInvoiceMoney");
        SaleInvoice yearInvoice = invoiceMapper.selectOne(invoiceQueryWrapper);
        //销售订单金额和合同金额
        QueryWrapper<SaleOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        orderQueryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
        orderQueryWrapper.select(" IFNULL(sum(sale_money),'0') saleMoney");
        SaleOrder monthOrder = orderMapper.selectOne(orderQueryWrapper);
        orderQueryWrapper.clear();
        orderQueryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        orderQueryWrapper.between("create_time", year + "-01-01 00:00:00", year + "-12-31 23:59:59");
        orderQueryWrapper.select(" IFNULL(sum(sale_money),'0') saleMoney");
        SaleOrder yearOrder = orderMapper.selectOne(orderQueryWrapper);


        QueryWrapper<SaleTarget> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        queryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
        queryWrapper.select(" IFNULL(sum(visit_number),'0') visitNumber");
        SaleTarget monthTarget = targetMapper.selectOne(queryWrapper);
        queryWrapper.clear();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        queryWrapper.between("create_time", year + "-01-01 00:00:00", year + "-12-31 23:59:59");
        queryWrapper.select(" IFNULL(sum(visit_number),'0') visitNumber");
        SaleTarget yearTarget = targetMapper.selectOne(queryWrapper);


        BigDecimal math = new BigDecimal("10000");
        BigDecimal bg = new BigDecimal(monthOrder.getSaleMoney());
        BigDecimal bg1 = new BigDecimal(yearOrder.getSaleMoney());
        BigDecimal bg2 = new BigDecimal(monthDeliver.getSaleDeliverMoney());
        BigDecimal bg3 = new BigDecimal(yearDeliver.getSaleDeliverMoney());
        BigDecimal bg4 = new BigDecimal(monthInvoice.getSaleInvoiceMoney());
        BigDecimal bg5 = new BigDecimal(yearInvoice.getSaleInvoiceMoney());

        monthTarget.setCompleteRate("0");
        yearTarget.setCompleteRate("0");
        monthTarget.setContractMoney(bg.divide(math, 2, RoundingMode.HALF_UP).toString());
        yearTarget.setContractMoney(bg1.divide(math, 2, RoundingMode.HALF_UP).toString());
        monthTarget.setSaleOrderMoney(bg.divide(math, 2, RoundingMode.HALF_UP).toString());
        yearTarget.setSaleOrderMoney(bg1.divide(math, 2, RoundingMode.HALF_UP).toString());
        monthTarget.setSaleDeliverMoney(bg2.divide(math, 2, RoundingMode.HALF_UP).toString());
        yearTarget.setSaleDeliverMoney(bg3.divide(math, 2, RoundingMode.HALF_UP).toString());
        monthTarget.setSaleInvoiceMoney(bg4.divide(math, 2, RoundingMode.HALF_UP).toString());
        yearTarget.setSaleInvoiceMoney(bg5.divide(math, 2, RoundingMode.HALF_UP).toString());
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "month");
        jsonObject.put("object", monthTarget);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("type", "year");
        jsonObject1.put("object", yearTarget);
        jsonArray.add(jsonObject);
        jsonArray.add(jsonObject1);
        return jsonArray;
    }

    @Override
    public SaleTargetVo getTargetScreen(SaleParam saleParam) {
        String orgId = saleParam.getOrgId();
        String time = saleParam.getTime();
        String year = time.substring(0, 4);
        int lastYear = Integer.parseInt(year) - 1;
        String month = time.substring(5, 7);
        SaleTargetVo vo = new SaleTargetVo();


        //客户拜访次数
        QueryWrapper<SaleTarget> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        queryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
        queryWrapper.select(" IFNULL(sum(visit_number),'0') visitNumber");
        SaleTarget monthTarget = targetMapper.selectOne(queryWrapper);
        queryWrapper.clear();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        queryWrapper.between("create_time", lastYear+"-"+month + "-01 00:00:00", lastYear+"-"+month +  "-31 23:59:59");
        queryWrapper.select(" IFNULL(sum(visit_number),'0') visitNumber");
        SaleTarget lastMonthTarget = targetMapper.selectOne(queryWrapper);

        //销售合同金额
        QueryWrapper<SaleOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        orderQueryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
        orderQueryWrapper.select(" IFNULL(sum(sale_money),'0') saleMoney");
        SaleOrder monthOrder = orderMapper.selectOne(orderQueryWrapper);
        orderQueryWrapper.clear();
        orderQueryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        orderQueryWrapper.between("create_time", lastYear+"-"+month + "-01 00:00:00", lastYear+"-"+month + "-31 23:59:59");
        orderQueryWrapper.select(" IFNULL(sum(sale_money),'0') saleMoney");
        SaleOrder yearOrder = orderMapper.selectOne(orderQueryWrapper);

        //销售发货金额
        QueryWrapper<SaleDeliver> deliverQueryWrapper = new QueryWrapper<>();
        deliverQueryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        deliverQueryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
        deliverQueryWrapper.select(" IFNULL(sum(sale_deliver_money),'0') saleDeliverMoney");
        SaleDeliver monthDeliver = deliverMapper.selectOne(deliverQueryWrapper);
        deliverQueryWrapper.clear();
        deliverQueryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        deliverQueryWrapper.between("create_time", lastYear+"-"+month + "-01 00:00:00", lastYear+"-"+month + "-31 23:59:59");
        deliverQueryWrapper.select(" IFNULL(sum(sale_deliver_money),'0') saleDeliverMoney");
        SaleDeliver yearDeliver = deliverMapper.selectOne(deliverQueryWrapper);

        //预期应收款金额
        QueryWrapper<SaleReceive> saleReceiveQueryWrapper = new QueryWrapper<>();
        saleReceiveQueryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        saleReceiveQueryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
        saleReceiveQueryWrapper.select(" IFNULL(sum(receive_money),'0') receiveMoney");
        SaleReceive monthReceive = receiveMapper.selectOne(saleReceiveQueryWrapper);
        saleReceiveQueryWrapper.clear();
        saleReceiveQueryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        saleReceiveQueryWrapper.between("create_time", lastYear+"-"+month + "-01 00:00:00", lastYear+"-"+month + "-31 23:59:59");
        saleReceiveQueryWrapper.select(" IFNULL(sum(receive_money),'0') receiveMoney");
        SaleReceive yearReceive = receiveMapper.selectOne(saleReceiveQueryWrapper);

        DecimalFormat def = new DecimalFormat("0.00");
        BigDecimal math = new BigDecimal("10000");

        if (lastMonthTarget.getVisitNumber().equals("0")) {
            vo.setVisitNumRate("0");
        } else {
            double v = (Double.valueOf(monthTarget.getVisitNumber()) - Double.valueOf(lastMonthTarget.getVisitNumber()))/Double.valueOf(lastMonthTarget.getVisitNumber());
            if (v >= 1.0) {
                vo.setVisitNumRate("100");
            } else {
                vo.setVisitNumRate(def.format(v * 100));
            }
        }
        vo.setVisitNum(monthTarget.getVisitNumber());
        vo.setComplete("0");
        vo.setCompleteRate("0");
        if (yearOrder.getSaleMoney().equals("0")) {
            vo.setSaleMoneyRate("0");
        } else {
            double v = (Double.valueOf(monthOrder.getSaleMoney()) - Double.valueOf(yearOrder.getSaleMoney()))/Double.valueOf(yearOrder.getSaleMoney());
            if (v >= 1.0) {
                vo.setSaleMoneyRate("100");
            } else {
                vo.setSaleMoneyRate(def.format(v * 100));
            }
        }
        BigDecimal bg = new BigDecimal(monthOrder.getSaleMoney());
        vo.setSaleMoney(bg.divide(math, 2, RoundingMode.HALF_UP).toString());

        if (yearDeliver.getSaleDeliverMoney().equals("0")) {
            vo.setSaleDeliverMoneyRate("0");
        } else {
            double v = (Double.valueOf(monthDeliver.getSaleDeliverMoney()) - Double.valueOf(yearDeliver.getSaleDeliverMoney()))/Double.valueOf(yearDeliver.getSaleDeliverMoney());
            if (v >= 1.0) {
                vo.setSaleDeliverMoneyRate("100");
            } else {
                vo.setSaleDeliverMoneyRate(def.format(v * 100));
            }
        }
        BigDecimal bg2 = new BigDecimal(monthDeliver.getSaleDeliverMoney());
        vo.setSaleDeliverMoney(bg2.divide(math, 2, RoundingMode.HALF_UP).toString());

        if (yearReceive.getReceiveMoney().equals("0")) {
            vo.setReceiveMoneyRate("0");
        } else {
            double v = (Double.valueOf(monthReceive.getReceiveMoney()) - Double.valueOf(yearReceive.getReceiveMoney()))/Double.valueOf(yearReceive.getReceiveMoney());
            if (v >= 1.0) {
                vo.setReceiveMoneyRate("100");
            } else {
                vo.setReceiveMoneyRate(def.format(v * 100));
            }
        }
        BigDecimal bg3 = new BigDecimal(monthReceive.getReceiveMoney());
        vo.setReceiveMoney(bg3.divide(math, 2, RoundingMode.HALF_UP).toString());

        return vo;
    }

    @Override
    public List<SaleTargetDetailVo> getCompleteDetail(SaleParam saleParam) {
        Integer type = saleParam.getType();
        String time = saleParam.getTime();
        String orgId = saleParam.getOrgId();
        QueryWrapper<SaleTarget> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
//        queryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
        if (0 == type) {
            queryWrapper.select("convert(IFNULL(avg(complete_rate),'0'),decimal(10,2)) completeRate,create_time createTime");
            queryWrapper.groupBy("DATE_FORMAT(create_time,'%y-%m')");
        } else {
            queryWrapper.select("convert(IFNULL(avg(complete_rate),'0'),decimal(10,2)) completeRate,create_time createTime");
            queryWrapper.groupBy("DATE_FORMAT(create_time,'%y')");
        }
        queryWrapper.orderByAsc("create_time");

        List<SaleTarget> targets = targetMapper.selectList(queryWrapper);
        List<SaleTargetDetailVo> list = new ArrayList<>();
        if (targets.size() != 0) {
            for (SaleTarget target : targets) {
                SaleTargetDetailVo vo = new SaleTargetDetailVo();
                if (0 == type) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    vo.setCreateTime(sdf.format(target.getCreateTime()));
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    vo.setCreateTime(sdf.format(target.getCreateTime()));
                }

                vo.setValue(target.getCompleteRate());

                list.add(vo);
            }
        }
        return list;
    }

    @Override
    public List<SaleTargetDetailVo> getVisitNumDetail(SaleParam saleParam) {
        Integer type = saleParam.getType();
        String time = saleParam.getTime();
        String orgId = saleParam.getOrgId();
        QueryWrapper<SaleTarget> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
//        queryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
        queryWrapper.orderByAsc("create_time");
        if (0 == type) {
            queryWrapper.select("convert(IFNULL(sum(visit_number),'0'),decimal(10,2)) visitNumber,create_time createTime");
            queryWrapper.groupBy("DATE_FORMAT(create_time,'%y-%m')");
        } else {
            queryWrapper.select("convert(IFNULL(sum(visit_number),'0'),decimal(10,2)) visitNumber,create_time createTime");
            queryWrapper.groupBy("DATE_FORMAT(create_time,'%y')");
        }

        List<SaleTarget> targets = targetMapper.selectList(queryWrapper);
        List<SaleTargetDetailVo> list = new ArrayList<>();
        if (targets.size() != 0) {
            for (SaleTarget target : targets) {
                SaleTargetDetailVo vo = new SaleTargetDetailVo();
                if (0 == type) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    vo.setCreateTime(sdf.format(target.getCreateTime()));
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    vo.setCreateTime(sdf.format(target.getCreateTime()));
                }
                vo.setValue(target.getVisitNumber());
                list.add(vo);
            }
        }
        return list;
    }

    @Override
    public List<SaleTargetDetailVo> getSaleMoneyDetail(SaleParam saleParam) {
        Integer type = saleParam.getType();
        String time = saleParam.getTime();
        String orgId = saleParam.getOrgId();
        QueryWrapper<SaleOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
//        queryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
        queryWrapper.orderByAsc("create_time");
        if (0 == type) {
            queryWrapper.select("IFNULL(sum(sale_money),'0') saleMoney,create_time createTime");
            queryWrapper.groupBy("DATE_FORMAT(create_time,'%y-%m')");
        } else {
            queryWrapper.select("IFNULL(sum(sale_money),'0') saleMoney,create_time createTime");
            queryWrapper.groupBy("DATE_FORMAT(create_time,'%y')");
        }

        List<SaleOrder> targets = orderMapper.selectList(queryWrapper);
        List<SaleTargetDetailVo> list = new ArrayList<>();
        BigDecimal math = new BigDecimal("10000");
        if (targets.size() != 0) {
            for (SaleOrder target : targets) {
                SaleTargetDetailVo vo = new SaleTargetDetailVo();
                if (0 == type) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    vo.setCreateTime(sdf.format(target.getCreateTime()));
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    vo.setCreateTime(sdf.format(target.getCreateTime()));
                }
                BigDecimal bg = new BigDecimal(target.getSaleMoney());
                vo.setValue(bg.divide(math,2,RoundingMode.HALF_UP).toString());
                list.add(vo);
            }
        }
        return list;
    }

    @Override
    public Page<SaleTarget> listTop(SaleDetailPageParam customerParam) {
        Integer pageNum = customerParam.getPageNum();
        Integer pageSize = customerParam.getPageSize();
        String orgId = customerParam.getOrgId();
        Page<SaleTarget> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SaleTarget> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        queryWrapper.select(" IFNULL(sum(visit_number),'0') visitNumber,customer_name customerName");
        queryWrapper.orderByDesc("visit_number");
        queryWrapper.groupBy("customer_name");
        Page<SaleTarget> targets = targetMapper.selectPage(page, queryWrapper);
        List<SaleTarget> records = targets.getRecords();
        if (ObjectUtil.isNotEmpty(records)){
            for (int i = 0; i < pageSize; i++) {
                SaleTarget workstopPlan = records.get(i);
                workstopPlan.setId((pageNum-1) *pageSize + i+ 1 );
            }
        }

        return targets;
    }

}
