package io.renren.modules.business.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.business.dao.BusinessAnnualDao;
import io.renren.modules.business.dao.BusinessOutlayDao;
import io.renren.modules.business.dao.BusinessOutlayIncomeDao;
import io.renren.modules.business.entity.BusinessAnnualEntity;
import io.renren.modules.business.entity.BusinessOutlayEntity;
import io.renren.modules.business.service.BusinessOutlayService;
import io.renren.modules.sys.dao.SysUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service("businessOutlayService")
public class BusinessOutlayServiceImpl extends ServiceImpl<BusinessOutlayDao, BusinessOutlayEntity> implements BusinessOutlayService {

    @Autowired
    SysUserDao sysUserDao;
    @Autowired
    BusinessAnnualDao businessAnnualDao;
    @Autowired
    BusinessOutlayDao businessOutlayDao;
    @Autowired
    BusinessOutlayIncomeDao businessOutlayIncomeDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
//        IPage<BusinessOutlayEntity> page = this.page(
//                new Query<BusinessOutlayEntity>().getPage(params),
//                new QueryWrapper<BusinessOutlayEntity>().eq("write_user_id",params.get("writeUserId").toString())
//                        .orderByDesc("out_time")
//        );
        IPage<BusinessOutlayEntity> page = new Query<BusinessOutlayEntity>().getPage(params);
        List<BusinessOutlayEntity> list = baseMapper.listNoPage(params);
        page.setRecords(list);
        return new PageUtils(page);
    }

    /**
     * 列表 状态为 0 并且不含有翻页
     * @param params
     * @return
     */
    @Override
    public List<BusinessOutlayEntity> listNoPage(Map<String, Object> params) {
        return baseMapper.listNoPage(params);
    }

    @Override
    public PageUtils pcListPage(Map<String, Object> params){
        IPage<BusinessOutlayEntity> page = new Query<BusinessOutlayEntity>().getPage(params);
        List<BusinessOutlayEntity> list = baseMapper.pcListNoPage(params);
        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    public List<BusinessOutlayEntity> pcListNoPage(Map<String, Object> params){
        return baseMapper.pcListNoPage(params);
    }

    @Override
    public Map<String, Object> queryList(Map<String, Object> params) {
        //根据条件获取List
        //List<BusinessOutlayEntity> list = baseMapper.listNoPage(params);

//        IPage<BusinessOutlayEntity> page = new Query<BusinessOutlayEntity>().getPage(params);
        List<BusinessOutlayEntity> list = baseMapper.listNoPage(params);
//        page.setRecords(list);
//        PageUtils pageUtils = new PageUtils(page);

        // 统计时无法分页
        params.put("page", -1);
        params.put("limit", -1);
        //获取统计信息
        List<Map<String,Object>> tj = baseMapper.queryTotal(params);
        //执行人
        List<Map<String,Object>> zxr = baseMapper.queryZxr(params);

        //将信息整合
        Map<String, Object> mapList = new HashMap<>();
        //mapList.put("list",list);
        mapList.put("list",list);
        mapList.put("zxr",zxr);
        return mapList;
    }
    @Override
    public List<Map<String,Object>>  getZxrList(){
        Map<String, Object> params = new HashMap<>();
        //执行人
        List<Map<String,Object>> zxr = baseMapper.queryZxr(params);
        return  zxr;
    }

    /**
     * 获取支出最大时间列表
     * @return
     */
    @Override
    public List<BusinessOutlayEntity> biggerTimeList() {
        //获取的最大时间列表
        List<BusinessOutlayEntity> list = baseMapper.biggerTimeList();
        return list;
    }

    private String dateToString(Date d){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(d);
    }

    /**
     * 获取食堂标准信息
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> stbzList(Map<String, Object> params) {
        BigDecimal pjMoney = new BigDecimal("0");
        BigDecimal pjDay = new BigDecimal("0");
        BigDecimal pjStDay = new BigDecimal("0");
        BigDecimal bzJz = new BigDecimal("0");
        List<Map<String,Object>> list = baseMapper.stbzList(params);
        for(int i=0;i<list.size();i++){
            Map<String,Object> map= (Map)list.get(i);
            String moneyStr = map.get("money").toString();
            String dayStr = map.get("day").toString();
            String stdayStr = map.get("stday").toString();
            pjMoney = pjMoney.add(new BigDecimal(moneyStr));
            pjDay = pjDay.add(new BigDecimal(dayStr));
            pjStDay = pjStDay.add(new BigDecimal(stdayStr));
        }

        BigDecimal bzTs = new BigDecimal("0");
        bzTs = pjDay.add(pjStDay);
        if(bzTs.compareTo(new BigDecimal("0")) != 0){
            bzJz = pjMoney.divide(bzTs,2);
        }

        Map<String, Object> mapList = new HashMap<>();
        mapList.put("list",list);
        mapList.put("pjMoney",pjMoney.setScale(2, RoundingMode.HALF_UP));
        mapList.put("pjDay",pjDay.setScale(2, RoundingMode.HALF_UP));
        mapList.put("pjStDay",pjStDay.setScale(2, RoundingMode.HALF_UP));
        mapList.put("bzJz",bzJz.setScale(2, RoundingMode.HALF_UP));
        return mapList;
    }

    /**
     * 获取最新的数据日期
     * @return
     */
    @Override
    public Map<String, Object> getLatestTime() throws ParseException {
        Map<String, Object> map  = new HashMap<>();
        //根据最新的提交时间情况  去判断当前的年度信息
        //获取最新时间信息
        Date latest = baseMapper.getLatestTime();
        //获取当前的时间
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date nowTime = sdf.parse(sdf.format(c.getTime()));
        //当前时间的年
        int year = Integer.parseInt(String.valueOf(c.get(Calendar.YEAR)));
        String newTime = "";
        if(latest.compareTo(nowTime) > 0){//数据最新时间大于当前时间 默认为当前年度的当前时间
//            newTime = year + "-02" + "-01";
            newTime = sdf.format(c.getTime());
        }else if(latest.compareTo(nowTime) < 0 && latest.compareTo(sdf.parse(year + "-02" + "-01")) > 0){//最新时间小于 当前时间 并且 大于  当前年度 2月  为今年本季度
            newTime = year + "-02" + "-01";
        }else if(latest.compareTo(nowTime) < 0 && latest.compareTo(sdf.parse(year + "-02" + "-01")) < 0){//最新时间小于当前时间并且小于当前年度2月  为去年季度时间
            newTime = (year-1) + "-02" + "-01";
        }
        map.put("newTime",newTime);
        return map;
    }

    @Override
    public void ifSave(Date outTime, String writeUserId, int i) throws ParseException {
// 获取当前年份
        Calendar c = Calendar.getInstance();
        //当前时间的年
        /*int year = Integer.parseInt(String.valueOf(c.get(Calendar.YEAR)));
        //判断的时间节点为 每年的3月1号
        String ifTime = year + "-03-01";
        // 装换时间用*/
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat jt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //  格式化 传入的时间   到年
        String yzTime = ft.format(outTime).substring(0,4);
        // 时间比较 -1  前面的时间比后面的小   0 则前面的大 1则为相等
//        if(outTime.compareTo(ft.parse(ifTime)) < 0){ //   说明传入的时间比每年的3月1号小 如果有当前年份则不需要添加
            if(!(businessAnnualDao.countYear(yzTime,writeUserId,String.valueOf(i)) > 0)){ //说明没有数据  则添加
                BusinessAnnualEntity businessAnnualEntity = new BusinessAnnualEntity();
                businessAnnualEntity.setAnnualYear(yzTime);
                businessAnnualEntity.setAnnualName(i);
                businessAnnualEntity.setAnnualState(0);
                businessAnnualEntity.setAnnualHsId(Integer.parseInt(writeUserId));
                businessAnnualEntity.setAnnualEndtime(jt.parse(jt.format(c.getTime())));
                businessAnnualDao.newSave(businessAnnualEntity);
            }
//        } else { // 大或者相等  第二年  如果没有则添加年份
            /*if(!(businessAnnualDao.countYear(yzTime,writeUserId,String.valueOf(i)) > 0)){
                BusinessAnnualEntity businessAnnualEntity = new BusinessAnnualEntity();
                businessAnnualEntity.setAnnualYear(String.valueOf(Integer.parseInt(yzTime) + 1));
                businessAnnualEntity.setAnnualName(i);
                businessAnnualEntity.setAnnualState(0);
                businessAnnualEntity.setAnnualHsId(Integer.parseInt(writeUserId));
                businessAnnualEntity.setAnnualEndtime(jt.parse(jt.format(c.getTime())));
                businessAnnualDao.newSave(businessAnnualEntity);
         }*/
    }

    /**
     * 获取当前年度数据
     * @return
     */
    @Override
    public List<BusinessOutlayEntity> listNowTime(Map<String, Object> params) {
        return baseMapper.listNowTime(params);
    }

    /**
     * .
     * 根据用户id获取信息
     *
     * @param params@return
     */
    @Override
    public Double getTotalByHJGId(Map<String, Object> params) {
        return baseMapper.getTotalByHJGId(params);
    }

    /**
     * 锁住
     *
     * @param userId
     */
    @Override
    public void updateLocked(String userId) {
        baseMapper.updateLocked(userId);
    }


    /**
     * 四人各项类别统计
     * @return
     */
    @Override
    public Map<String,Object> srTypeList( Map<String, Object> params) {
        Map<String,Object> data = new HashMap<>();
        List<Map<String,Object>> list = businessOutlayDao.getLbList(params);
        params.put("writeUserId","13");
        List<Map<String,Object>> xs = businessOutlayDao.getLbTotalByWriteUserId(params);
        params.put("writeUserId","9");
        List<Map<String,Object>> hdq = businessOutlayDao.getLbTotalByWriteUserId(params);
        params.put("writeUserId","11");
        List<Map<String,Object>> lxj = businessOutlayDao.getLbTotalByWriteUserId(params);
        params.put("writeUserId","10");
        List<Map<String,Object>> hdg = businessOutlayDao.getLbTotalByWriteUserId(params);

        for(int i=0;i<xs.size();i++){
            for (int x=0;x<list.size();x++){
                if(xs.get(i).get("id").equals(list.get(x).get("id"))){
                    list.get(x).put("xs",xs.get(i).get("totalNum"));
                }
            }
        }
        for(int i=0;i<hdq.size();i++){
            for (int x=0;x<list.size();x++){
                if(hdq.get(i).get("id").equals(list.get(x).get("id"))){
                    list.get(x).put("hdq",hdq.get(i).get("totalNum"));
                }
            }
        }
        for(int i=0;i<lxj.size();i++){
            for (int x=0;x<list.size();x++){
                if(lxj.get(i).get("id").equals(list.get(x).get("id"))){
                    list.get(x).put("lxj",lxj.get(i).get("totalNum"));
                }
            }
        }
        for(int i=0;i<hdg.size();i++){
            for (int x=0;x<list.size();x++){
                if(hdg.get(i).get("id").equals(list.get(x).get("id"))){
                    list.get(x).put("hdg",hdg.get(i).get("totalNum"));
                }
            }
            //list.get(i).put("hdg",hdg.get(i).get("totalNum"));
        }
        data.put("list",list);

        double xsyszh = list.stream().collect(Collectors.summingDouble(e -> Double.valueOf(e.get("xs").toString())));
        double hdqyszh = list.stream().collect(Collectors.summingDouble(e -> Double.valueOf(e.get("hdq").toString())));
        double lxjyszh = list.stream().collect(Collectors.summingDouble(e -> Double.valueOf(e.get("lxj").toString())));
        double hdgyszh = list.stream().collect(Collectors.summingDouble(e -> Double.valueOf(e.get("hdg").toString())));

        data.put("xsyszh",xsyszh);  //  肖爽以上支出总和
        data.put("hdqyszh",hdqyszh);//  侯吉庆以上支出总和
        data.put("lxjyszh",lxjyszh);//  李现举以上支出总和
        data.put("hdgyszh",hdgyszh);//  侯吉光以上支出总和

        double zh = xsyszh+hdqyszh+lxjyszh+hdgyszh;
        double xsyszb = 100*xsyszh/zh;
        double hdqyszb = 100*hdqyszh/zh;
        double lxjyszb = 100*lxjyszh/zh;
        double hdgyszb = 100*hdgyszh/zh;

        data.put("xsyszb",xsyszb);  //  肖爽以上支出占比
        data.put("hdqyszb",hdqyszb);//  侯吉庆以上支出占比
        data.put("lxjyszb",lxjyszb);//  李现举以上支出占比
        data.put("hdgyszb",hdgyszb);//  侯吉光以上支出占比

        List<Map<String,Object>> tj = businessOutlayIncomeDao.zclbList(params);


        double xssrnb = 0.0;//肖爽内部转账收入总和
        double xssrqt = 0.0;//肖爽其他收入总和

        double hjqsrnb = 0.0;//侯吉庆内部转账收入总和
        double hjqsrqt = 0.0;//侯吉庆其他收入总和

        double lxjsrnb = 0.0;//李现举内部转账收入总和
        double lxjsrqt = 0.0;//李现举其他收入总和

        for(Map<String, Object> item : tj){
            Double totalNum = Double.valueOf(item.get("totalNum").toString());
            if(item.get("id").toString().equals("13")){//肖爽
                if(item.get("out_type").toString().equals("1")){
                    xssrnb =  totalNum;
                }else{
                    xssrqt =  totalNum;
                }
            }
            if(item.get("id").toString().equals("9")){//侯吉庆
                if(item.get("out_type").toString().equals("1")){
                    hjqsrnb =  totalNum;
                }else{
                    hjqsrqt =  totalNum;
                }
            }
            if(item.get("id").toString().equals("11")){//李现举
                if(item.get("out_type").toString().equals("1")){
                    lxjsrnb =  totalNum;
                }else{
                    lxjsrqt =  totalNum;
                }
            }
        }

        double xssrzh = xssrnb+xssrqt;;//肖爽收入总和
        double hjqsrzh = hjqsrnb+hjqsrqt;//侯吉庆收入总和
        double lxjsrzh = lxjsrnb+lxjsrqt;//李现举收入总和

        data.put("xssrzh",xssrzh);//肖爽收入总和
        data.put("xssrnb",xssrnb);//肖爽内部转账收入总和
        data.put("xssrqt",xssrqt);//肖爽其他收入总和

        data.put("hjqsrzh",hjqsrzh);//侯吉庆收入总和
        data.put("hjqsrnb",hjqsrnb);//侯吉庆内部转账收入总和
        data.put("hjqsrqt",hjqsrqt);//侯吉庆其他收入总和

        data.put("lxjsrzh",lxjsrzh);//李现举收入总和
        data.put("lxjsrnb",lxjsrnb);//李现举内部转账收入总和
        data.put("lxjsrqt",lxjsrqt);//李现举其他收入总和

        return data;
    }

    @Override
    public Map<String,Object> getXmcb(Map<String,Object> params){
        Map<String,Object> map = new HashMap<>();
        List<Map<String,Object>> list = businessOutlayDao.selectOutMoneys(params);

        double hjzje = list.stream().collect(Collectors.summingDouble(e -> Double.valueOf(e.get("totalMoney").toString())));
        double hjzcje = list.stream().collect(Collectors.summingDouble(e -> Double.valueOf(e.get("outMoney").toString())));
        double hjzs = list.stream().collect(Collectors.summingDouble(e -> Double.valueOf(e.get("money").toString())));
        list.forEach( x->{
            double zje = new Double(x.get("totalMoney").toString());
            String bfb =   new DecimalFormat("0.00").format(zje / hjzje * 10000 / 100) + "%";
            x.put("bfb",bfb);
        });
        map.put("list",list);
        map.put("hjzje",new BigDecimal(hjzje).setScale(2,BigDecimal.ROUND_HALF_UP));
        map.put("hjzcje",new BigDecimal(hjzcje).setScale(2,BigDecimal.ROUND_HALF_UP));
        map.put("hjzs",new BigDecimal(hjzs).setScale(2,BigDecimal.ROUND_HALF_UP));
        return map;
    }

    @Override
    public Map<String,Object> getGlf(Map<String,Object> params){
        Map<String,Object> map = new HashMap<>();
        List<Map<String,Object>> list = businessOutlayDao.getGlf(params);
        double hjMoney = list.stream().collect(Collectors.summingDouble(e -> Double.valueOf(e.get("outMoney").toString())));
        list.forEach( x->{
            double outMoney = new Double(x.get("outMoney").toString());
            if(hjMoney != 0d){
                String bfb =   new DecimalFormat("0.00").format(outMoney / hjMoney * 10000 / 100) + "%";
                x.put("bfb",bfb);
            }else{
                x.put("bfb","0.00%");
            }
        });
        map.put("list",list);
        map.put("hjMoney",new BigDecimal(hjMoney).setScale(2,BigDecimal.ROUND_HALF_UP));
        return map;
    }

    @Override
    public Map<String,Object> getGzTj(Map<String,Object> params){
        Map<String,Object> map = new HashMap<>();
//        List<Map<String,Object>> list = businessOutlayDao.getGzTj(params);
//
//        list.forEach( x->{
//            BigDecimal sfgz = new BigDecimal(x.get("sfgz").toString());
//            BigDecimal money = new BigDecimal(x.get("money").toString());
//            BigDecimal cz = sfgz.subtract(money);
//            x.put("cz",cz);
//        });
//        double hjsfgz = list.stream().collect(Collectors.summingDouble(e -> Double.valueOf(e.get("sfgz").toString())));
//        double hjmoney = list.stream().collect(Collectors.summingDouble(e -> Double.valueOf(e.get("money").toString())));
//        double hjcz = list.stream().collect(Collectors.summingDouble(e -> Double.valueOf(e.get("cz").toString())));
//
//        list.forEach( x->{
//            double sfgz = new Double(x.get("sfgz").toString());
//            String bfb =   new DecimalFormat("0.00").format(sfgz / hjsfgz * 10000 / 100) + "%";
//            x.put("bfb",bfb);
//        });
//        map.put("list",list);
//        map.put("hjsfgz",new BigDecimal(hjsfgz).setScale(2,BigDecimal.ROUND_HALF_UP));
//        map.put("hjmoney",new BigDecimal(hjmoney).setScale(2,BigDecimal.ROUND_HALF_UP));
//        map.put("hjcz",new BigDecimal(hjcz).setScale(2,BigDecimal.ROUND_HALF_UP));

        List<Map<String,Object>> list = businessOutlayDao.getGzTj2(params);

        double hjsfgz = list.stream().collect(Collectors.summingDouble(e -> Double.valueOf(e.get("sfgz").toString())));

        list.forEach( x-> {
            double sfgz = new Double(x.get("sfgz").toString());
            if(hjsfgz == 0d){
                x.put("bfb", "0.00%");
            }else{
                String bfb = new DecimalFormat("0.00").format(sfgz / hjsfgz * 10000 / 100) + "%";
                x.put("bfb", bfb);
            }
        });
        map.put("list",list);
        map.put("hjsfgz",new BigDecimal(hjsfgz).setScale(2,BigDecimal.ROUND_HALF_UP));
        return map;
    }

    @Override
    public List<Map<String,Object>> yzList(Map<String, Object> params){
        return baseMapper.yzList(params);
    }

    /**
     * 列表-支出查询合计
     */
    @Override
    public Map<String, Object> getZccxhj(Map<String, Object> params){
        return baseMapper.getZccxhj(params);
    }

}
