package vip.xiaonuo.money.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
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.money.entity.MoneyOverdue;
import vip.xiaonuo.money.entity.vo.MoneyBorrowUserVo;
import vip.xiaonuo.money.mapper.MoneyOverdueMapper;
import vip.xiaonuo.money.param.MoneyOverduePageParam;
import vip.xiaonuo.money.param.MoneyOverdueParam;
import vip.xiaonuo.money.service.IMoneyOverdueService;
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.util.*;

/**
 * <p>
 * 财务应收逾期表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-21
 */
@Service
public class MoneyOverdueServiceImpl extends ServiceImpl<MoneyOverdueMapper, MoneyOverdue> implements IMoneyOverdueService {

    @Autowired
    private MoneyOverdueMapper overdueMapper;

    @Override
    public JSONObject getOverdueCount(MoneyOverdueParam overdueParam) {
        String orgId = overdueParam.getOrgId();
        String userName = overdueParam.getUserName();
        QueryWrapper<MoneyOverdue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        queryWrapper.eq(StringUtils.isNotBlank(userName), "user_name", userName);
        queryWrapper.eq("is_overdue", 1);
        List<MoneyOverdue> list = overdueMapper.selectList(queryWrapper);
        Double money = 0.00;
        if (list.size() != 0) {
            for (MoneyOverdue moneyOverdue : list) {
                Date overdueTime = moneyOverdue.getOverdueTime();
                Date endTime = moneyOverdue.getEndTime();
                long l = (overdueTime.getTime() - endTime.getTime()) / (24 * 60 * 60 * 1000);
                if (l > 30) {
                    money = money + Double.valueOf(moneyOverdue.getOverduePrice());
                }
            }
        }
        DecimalFormat def = new DecimalFormat("0.00");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("money", def.format(money));
        return jsonObject;
    }

    @Override
    public JSONObject overdueRank(MoneyOverdueParam overdueParam) {
        String orgId = overdueParam.getOrgId();
        String userName = overdueParam.getUserName();
        QueryWrapper<MoneyOverdue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        queryWrapper.eq(StringUtils.isNotBlank(userName), "user_name", userName);
        queryWrapper.groupBy("is_overdue");
        List<MoneyOverdue> overdues = overdueMapper.selectList(queryWrapper);
        double count = 0.00;
        double isOverdue = 0.00;
        double disOverdue = 0.00;
        JSONObject jsonObject = new JSONObject();
        DecimalFormat def = new DecimalFormat("0.00");
        if (overdues.size() != 0) {
            for (MoneyOverdue overdue : overdues) {
                if (overdue.getIsOverdue() == 0) {
                    disOverdue = disOverdue + Double.valueOf(overdue.getCollectPrice());
                } else {
                    isOverdue = isOverdue + Double.valueOf(overdue.getOverduePrice());
                }
                count = isOverdue + disOverdue;
            }
            if (count == 0) {
                jsonObject.put("isOverdue", "0");
                jsonObject.put("disOverdue", "100");
            } else {
                jsonObject.put("isOverdue", def.format(isOverdue / count));
                jsonObject.put("disOverdue", def.format(disOverdue / count));
            }
        } else {
            jsonObject.put("isOverdue", "0");
            jsonObject.put("disOverdue", "100");
        }
        return jsonObject;
    }

    @Override
    public JSONArray userRank(MoneyOverdueParam overdueParam) {
        String orgId = overdueParam.getOrgId();
        QueryWrapper<MoneyOverdue> queryWrapper = new QueryWrapper<>();
        String time = overdueParam.getTime();
        if ("".equals(time) || null == time) {
            queryWrapper.ge("date_time", DateUtil.beginOfMonth(new Date()));
        } else {
            queryWrapper.between("date_time", time + "-01 00:00:00", time + "-31 23:59:59");
        }
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        queryWrapper.eq(StringUtils.isNotBlank(overdueParam.getUserName()), "user_name", overdueParam.getUserName());
        JSONArray jsonArray = new JSONArray();
        List<MoneyBorrowUserVo> userRank = overdueMapper.getUserRank(queryWrapper);
        BigDecimal math = new BigDecimal("10000");
        if (userRank.size() != 0) {
            for (MoneyBorrowUserVo moneyBorrowUserVo : userRank) {
                JSONObject jsonObject = new JSONObject();
                BigDecimal bg = new BigDecimal(moneyBorrowUserVo.getCollectPrice());
                bg = bg.divide(math, 2, RoundingMode.HALF_UP);
                BigDecimal bg1 = new BigDecimal( moneyBorrowUserVo.getOverduePrice());
                bg1 = bg1.divide(math, 2, RoundingMode.HALF_UP);
                jsonObject.put("collectPrice",bg.toString());
                jsonObject.put("overduePrice", bg1.toString());
                jsonObject.put("userName", moneyBorrowUserVo.getUserName());
                jsonArray.add(jsonObject);
            }
        }
        JSONArray jsonArray1 = jsonArraySort(jsonArray, "collectPrice", true);
        return jsonArray1;
    }

    @Override
    public Page<MoneyOverdue> overdueDetail(MoneyOverduePageParam overduePageParam) {
        String orgId = overduePageParam.getOrgId();
        Integer pageNum = overduePageParam.getPageNum();
        Integer pageSize = overduePageParam.getPageSize();
        QueryWrapper<MoneyOverdue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId).orderByDesc("date_time");
        Page page = new Page<MoneyOverdue>(pageNum, pageSize);
        Page selectPage = overdueMapper.selectPage(page, queryWrapper);
        List<MoneyOverdue> records = selectPage.getRecords();
        BigDecimal math = new BigDecimal("10000");
        for (MoneyOverdue record : records) {
            BigDecimal bg = new BigDecimal(record.getCollectPrice());
            bg = bg.divide(math, 2, RoundingMode.HALF_UP);
            record.setCollectPrice(bg.toString());
        }
        return overdueMapper.selectPage(page, queryWrapper);
    }

    /*数组排序*/
    public static JSONArray jsonArraySort(JSONArray jsonArr, String sortKey, boolean is_desc) {
        //存放排序结果json数组
        JSONArray sortedJsonArray = new JSONArray();
        //用于排序的list
        List<JSONObject> jsonValues = new ArrayList<JSONObject>();
        //将参数json数组每一项取出，放入list

            for (int i = 0; i < jsonArr.size(); i++) {
                jsonValues.add(jsonArr.getJSONObject(i));
            }
            //快速排序，重写compare方法，完成按指定字段比较，完成排序
            Collections.sort(jsonValues, new Comparator<JSONObject>() {
                //排序字段
                private final String KEY_NAME = sortKey;

                //重写compare方法
                @Override
                public int compare(JSONObject a, JSONObject b) {
                    //如果用String接会导致一位数和两位数混合比对的时候不能准确比出来，要用int类型接
                    //String valA = new String();
                    //String valB = new String();
                    Float valA = 0.00f;
                    Float valB = 0.00f;
                    try {
                        valA = Float.parseFloat(a.getString(KEY_NAME));
                        valB = Float.parseFloat(b.getString(KEY_NAME));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //是升序还是降序
                    if (is_desc) {
                        return -valA.compareTo(valB);
                    } else {
                        return -valB.compareTo(valA);
                    }

                }
            });
            //将排序后结果放入结果jsonArray
            for (int i = 0; i < jsonArr.size(); i++) {
                sortedJsonArray.add(jsonValues.get(i));
            }
        return sortedJsonArray;
    }
}
