package com.bonus.material.push.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.StringUtils;
import com.bonus.common.biz.config.DateTimeHelper;
import com.bonus.common.biz.utils.AesEncryptUtils;
import com.bonus.common.biz.utils.HttpHelper;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.push.domain.ConsumeDataPush;
import com.bonus.material.push.domain.CostPushBean;
import com.bonus.material.push.mapper.CostPushMapper;
import com.bonus.material.push.service.CostPushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : 阮世耀
 * @version : 1.0
 * @PackagePath: com.bonus.material.push.service.impl
 * @CreateTime: 2025-06-29  14:16
 * @Description:
 */
@Service
public class CostPushServiceImpl implements CostPushService {

    // 工器具费用推送接口
    public static final String GQJ_PUSH_URL = "http://10.138.55.113:8036/micro-server/zygqj/syncProjectCostsData";

    @Autowired
    private CostPushMapper dao;

    /**
     * 获取费用推送审核数据
     */
    @Override
    public List<CostPushBean> getCostPushCheckList(CostPushBean o) {
        // TODO Auto-generated method stub
        return dao.getCostPushCheckList(o);
    }

    /**
     * 获取费用推送审核数据
     */
    @Override
    public CostPushBean getCostPushCheckListCount(CostPushBean o) {
        // TODO Auto-generated method stub
        List<CostPushBean> beanList = dao.getCostPushCheckList(o);
        calcTotalMoney(beanList);
        if(beanList.isEmpty()){
            return null;
        }
        return beanList.get(beanList.size() - 1);
    }

    /**
     * 获取消耗费用推送审核数据
     */
    @Override
    public List<CostPushBean> getConsumPushCheckList(CostPushBean o) {
        // TODO Auto-generated method stub
        return dao.getConsumePushCheckList(o);
    }

    /**
     * 获取消耗费用推送数据统计
     */
    @Override
    public CostPushBean getConsumPushCheckListCount(CostPushBean o) {
        // TODO Auto-generated method stub
        List<CostPushBean> list = dao.getConsumePushCheckList(o);
        if (list.isEmpty()) {
            return new CostPushBean();
        }
        calcTotalMoney(list);
        return list.get(list.size() - 1);
    }

    /**
     * 获取租赁费用推送审核数据
     */
    @Override
    public List<CostPushBean> getCostPushLeaseList(CostPushBean o) {

        return dao.getCostPushLeaseList(o);
    }



    @Override
    public List<CostPushBean> findDetails(CostPushBean o) {
        List<CostPushBean> list = dao.findDetails(o);
        if (list != null && !list.isEmpty()) {
            double total = 0;
            for (CostPushBean bean : list) {
                String leaseMoney = bean.getLeaseMoney();
                total += moneyStringToDouble(leaseMoney);
            }
            CostPushBean newBean = new CostPushBean();
            newBean.setLeaseMoney(String.format("%.2f", total));
            newBean.setProjectName("合计费用");
            list.add(newBean);
        }
        return list;
    }

    @Override
    public List<CostPushBean> findOtherDetails(CostPushBean o) {
        return dao.findOtherDetails(o);
    }

    /**
     * 推送数据到优尔
     */
    @Override
    public void pushDataToYouer(String cheks) {
        // 对参数进行处理
        List<CostPushBean> params = createParams(cheks);
        //根据ProjectId进行工程分组
        Map<String, List<CostPushBean>> groupedByProjectId = params.stream()
                .collect(Collectors.groupingBy(CostPushBean::getProjectId));
        //取出工程分组后的集合
        List<List<CostPushBean>> projectList = new ArrayList<>(groupedByProjectId.values());
        if (!projectList.isEmpty()) {
            for (List<CostPushBean> bean : projectList) {
                for (CostPushBean costPushBean : bean) {
                    dao.updateCostPushCheckStatus(costPushBean.getId());
                }
                pushToolData(bean);
            }
        }
    }

    /**
     * 消耗性费用推送数据到优尔
     */
    @Override
    public void pushConsumeDataToYouer(String cheks) {
        // 对参数进行处理
        List<CostPushBean> params = createParams(cheks);
        //根据ProjectId进行工程分组
        Map<String, List<CostPushBean>> groupedByProjectId = params.stream()
                .collect(Collectors.groupingBy(CostPushBean::getProjectId));
        //取出工程分组后的集合
        List<List<CostPushBean>> projectList = new ArrayList<>(groupedByProjectId.values());
        if (!projectList.isEmpty()) {
            for (List<CostPushBean> bean : projectList) {
                for (CostPushBean costPushBean : bean) {
                    dao.updateCostPushCheckStatus(costPushBean.getId());
                }
                pushConsumeData(bean);
            }
        }
    }

    /**
     * 更新安全状态
     */
    @Override
    public int updatePushAQStatus(CostPushBean bean) {
        return dao.updatePushAQStatus(bean);
    }

    /**
     * 更新消耗品状态
     */
    @Override
    public int updatePushXHStatus(CostPushBean bean) {
        return dao.updatePushXHStatus(bean);
    }

    /**
     * 费用判断转换，从字符串转换到double类型
     */
    private double moneyStringToDouble(String money) {
        if (StringUtils.isEmpty(money)) {
            return 0.00;
        } else {
            return Double.parseDouble(money);
        }
    }

    /**
     * 计算合计费用并添加到数据集合中
     *
     * @param list
     * @return
     */
    private List<CostPushBean> calcTotalMoney(List<CostPushBean> list) {
        double leasatotal = 0;// 租赁总费用
        double losttotal = 0.00;// 丢失总费用
        double scraptotal = 0;// 报废总费用
        double consttotal = 0;// 维修总费用
        double moneytotal = 0;// 合计总费用

        if (list != null && !list.isEmpty()) {
            for (CostPushBean bean : list) {
                String leaseMoney = bean.getLeaseMoney();
                String lostMoney = bean.getLostMoney();
                String scrapMoney = bean.getScrapMoney();
                String consMoney = bean.getConsMoney();
                String money = bean.getMoney();
                leasatotal += moneyStringToDouble(leaseMoney);
                losttotal += moneyStringToDouble(lostMoney);
                scraptotal += moneyStringToDouble(scrapMoney);
                consttotal += moneyStringToDouble(consMoney);
                moneytotal += moneyStringToDouble(money);
            }
            CostPushBean newBean = new CostPushBean();
            newBean.setLeaseMoney(String.format("%.2f", leasatotal));
            newBean.setLostMoney(String.format("%.2f", losttotal));
            newBean.setScrapMoney(String.format("%.2f", scraptotal));
            newBean.setConsMoney(String.format("%.2f", consttotal));
            newBean.setMoney(String.format("%.2f", moneytotal));
            newBean.setProjectName("合计费用");
            list.add(newBean);
        }
        return list;
    }

    /**
     * 将费用合计推送至优尔
     */
    private void pushToolData(List<CostPushBean> params) {
        List<CostPushBean> list = getToolData(params);
        // 推送数据租赁费、维修费用、报废费用
        if (!list.isEmpty()) {
            httpToolData(list);
            for (CostPushBean bean : list) {
                // 更新推送状态
                bean.setTime(DateTimeHelper.getNowTime());
                dao.updateCostPushStatus(bean);
            }
        }
    }

    /**
     * 获取要推送的租赁费用、维修费用、报废费用
     */
    private List<CostPushBean> getToolData(List<CostPushBean> params) {
        List<CostPushBean> result = new ArrayList<>();
        String submitUser = SecurityUtils.getUsername();
        for (CostPushBean bean : params) {
            bean.setSubmitUser(submitUser);
            bean.setType("1");
            List<CostPushBean> leaseList = dao.getToolDataPushList(bean);
            if (leaseList != null && !leaseList.isEmpty()) {
                result.addAll(leaseList);
            }
            bean.setType("3");
            List<CostPushBean> scrapList = dao.getToolDataPushList(bean);
            if (scrapList != null && !scrapList.isEmpty()) {
                result.addAll(scrapList);
            }
            bean.setType("4");
            List<CostPushBean> lossList = dao.getToolDataPushList(bean);
            if (lossList != null && !lossList.isEmpty()) {
                result.addAll(lossList);
            }
        }
        return result;
    }

    /**
     * 调用接口推送 租赁费、维修费用、报废费用到优尔
     */
    private List<CostPushBean> httpToolData(List<CostPushBean> list) {
        String content = JSONObject.toJSONString(list);
        String encrypt;
        try {
            // 数据推送，http请求
            encrypt = AesEncryptUtils.encrypt(content, HttpHelper.KEY);
            System.err.println("租赁费、维修费用、报废费推送数据解密======：" + AesEncryptUtils.decrypt(encrypt, HttpHelper.KEY));
            Map<String, String> map = new HashMap<String, String>();
            map.put("body", encrypt);
            String body = JSONObject.toJSONString(map);
			String url = "http://10.138.55.105:8097/micro-server/zzaqgjf/syncSafetyTool";
            //String url = "http://192.168.1.134:8036/micro-server/zzaqgjf/syncSafetyTool";
            String data = HttpHelper.sendHttpPost(url, body);
            JSONObject object = JSONObject.parseObject(data);
            System.err.println(data);


            String code = object.getString("code");
            if ("200".equals(code)) {
                String dataResultString = object.getString("data");
                // 数据解密
                String dataArrayString = AesEncryptUtils.decrypt(dataResultString, HttpHelper.KEY);
                System.err.println("四类费用推送返回："+dataArrayString);
                JSONArray dataArray = JSONArray.parseArray(dataArrayString);
                if (dataArray != null && !dataArray.isEmpty()) {
                    // 有数据
                    for (int i = 0; i < dataArray.size(); i++) {
                        JSONObject dataObject = dataArray.getJSONObject(i);
                        String resultId = dataObject.getString("id");
                        String resultPushRemark = dataObject.getString("pushRemark");
                        String pushStatus = "2";
                        for (int j = 0; j < list.size(); j++) {
                            CostPushBean costPushBean = list.get(j);
                            String id = costPushBean.getId();
                            if (resultId.equals(id)) {
                                costPushBean.setPushRemark(resultPushRemark);
                                costPushBean.setPushStatus(pushStatus);
                                list.set(j, costPushBean);
                            }
                        }
                    }
                }
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return list;
        }
    }


    /**
     * 构造 查询费用参数
     */
    private List<CostPushBean> createParams(String cheks) {
        if (StringUtils.isNotEmpty(cheks)) {
            JSONArray object = JSONObject.parseArray(cheks);
            List<CostPushBean> params = new ArrayList<>();
            if (object != null && !object.isEmpty()) {
                for (int i = 0; i < object.size(); i++) {
                    CostPushBean bean = new CostPushBean();
                    JSONObject idObj = object.getJSONObject(i);
                    String id = idObj.getString("id");
                    String proId = idObj.getString("projectId");
                    String taskId = idObj.getString("taskId");
                    String unitId = idObj.getString("unitId");
                    bean.setId(id);
                    bean.setProjectId(proId);
                    bean.setTaskId(taskId);
                    bean.setUnitId(unitId);
                    params.add(bean);
                }
            }
            return params;
        } else {
            return Collections.emptyList();
        }
    }


    /**
     * 将消耗性费用推送至优尔 主表: 关联表: 描述: TODO
     */
    private void pushConsumeData(List<CostPushBean> params) {
        List<ConsumeDataPush> consumeList = getConsumeDataList(params);

        // 推送消耗品费用到优尔
        if (!consumeList.isEmpty()) {
            httpConsumeData(consumeList);
            for (ConsumeDataPush bean : consumeList) {
                CostPushBean costPushBean = new CostPushBean();
                costPushBean.setTime(DateTimeHelper.getNowTime());
                costPushBean.setPushRemark(bean.getPushRemark());
                costPushBean.setPushStatus(bean.getPushStatus());
                costPushBean.setId(bean.getId());
                // 更新推送状态
                dao.updateCostPushStatus(costPushBean);
            }
        }
    }

    /**
     * 获取消耗品推送费用集合 主表: 关联表: 描述: TODO
     *
     * @return List<ConsumeDataPush>
     */
    private List<ConsumeDataPush> getConsumeDataList(List<CostPushBean> params) {
        List<ConsumeDataPush> result = new ArrayList<>();
        String submitUser = SecurityUtils.getUsername();
        for (CostPushBean bean : params) {
            bean.setSubmitUser(submitUser);
            List<ConsumeDataPush> tempList = dao.getConsumeDataPushsList(bean);
            result.addAll(tempList);
        }
        return result;
    }

    /**
     * 调用接口推送 消耗品费用到优尔
     *
     * @return boolean
     */
    private List<ConsumeDataPush> httpConsumeData(List<ConsumeDataPush> list) {
        String content = JSONObject.toJSONString(list);
        String encrypt;
        try {
            // 数据推送，http请求
            encrypt = AesEncryptUtils.encrypt(content, HttpHelper.KEY);
            System.err.println("消耗品费用加密数据======：" + encrypt);
            Map<String, String> map = new HashMap<String, String>();
            map.put("body", encrypt);

            String body = JSONObject.toJSONString(map);
			String url = "http://10.138.55.105:8097/micro-server/consumetool/syncConsumeTool";
            //String url = "http://192.168.1.134:8036/micro-server/consumetool/syncConsumeTool";
            String data = HttpHelper.sendHttpPost(url, body);
            JSONObject object = JSONObject.parseObject(data);
            System.err.println(data);

            String code = object.getString("code");
            if ("200".equals(code)) {
                String dataResultString = object.getString("data");
                // 数据解密
                String dataArrayString = AesEncryptUtils.decrypt(dataResultString, HttpHelper.KEY);
                System.err.println("消耗品费用推送返回："+dataArrayString);
                JSONArray dataArray = JSONArray.parseArray(dataArrayString);
                if (dataArray != null && !dataArray.isEmpty()) {
                    // 有数据
                    for (int i = 0; i < dataArray.size(); i++) {
                        JSONObject dataObject = dataArray.getJSONObject(i);
                        String resultId = dataObject.getString("id");
                        String resultPushRemark = dataObject.getString("pushRemark");
                        for (int k = 0; k < list.size(); k++) {
                            ConsumeDataPush consumeDataPush = list.get(k);
                            String id = consumeDataPush.getId();
                            if (resultId.equals(id)) {
                                consumeDataPush.setPushRemark(resultPushRemark);
                                consumeDataPush.setPushStatus("2");
                                list.set(k, consumeDataPush);
                            }
                        }
                    }
                }
                return list;
            } else {
                return list;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return list;
        }
    }

}
