package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Dksq;
import com.ruoyi.system.domain.DksqLcjl;
import com.ruoyi.system.mapper.DksqLcjlMapper;
import com.ruoyi.system.mapper.DksqMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.IDkCommonServerce;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

import static com.ruoyi.common.constant.Constants.*;

/**
 * @Author: tjf
 * @Date: 2023/6/15 15:32
 * @Describe:
 */
@Service
public class DkCommonServerceImpl implements IDkCommonServerce {

    @Autowired
    private DksqMapper dksqMapper;
    @Autowired
    private DksqLcjlMapper dksqLcjlMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    /**
     * 劳动局审核
     *
     * @param dksq
     * @return
     */
    @Override
    public AjaxResult shenHe(Dksq dksq) {
        if (!ONE.equals(dksq.getType())) {
            return AjaxResult.error("请勿重复审核");
        }
        //通过不通过都设置为2
        dksq.setType(TWO);
        dksqMapper.updateDksq(dksq);

        //插入流程记录表
        DksqLcjl dksqLcjl = new DksqLcjl();
        dksqLcjl.setDksqId(dksq.getId());
        dksqLcjl.setType(TWO);
        dksqLcjl.setResult(dksq.getResult());
        dksqLcjl.setCreateBy(SecurityUtils.getUsername());
        dksqLcjlMapper.insertDksqLcjl(dksqLcjl);
        return AjaxResult.success();
    }


    /**
     * 劳动局指派银行
     *
     * @param dksq
     * @return
     */
    @Override
    public AjaxResult zhiPai(Dksq dksq) {
        if (!TWO.equals(dksq.getType()) && !TWO.equals(dksq.getResult())) {
            return AjaxResult.error("审核未通过,请勿指派下一阶段");
        }
        //设置为等待银行评估
        dksq.setType(THR);
        dksq.setResult(ONE);
        dksqMapper.updateDksq(dksq);

        //插入流程记录表
        DksqLcjl dksqLcjl = new DksqLcjl();
        dksqLcjl.setDksqId(dksq.getId());
        dksqLcjl.setType(THR);
        dksqLcjl.setResult(ONE);
        dksqLcjl.setCreateBy(SecurityUtils.getUsername());
        dksqLcjlMapper.insertDksqLcjl(dksqLcjl);
        return AjaxResult.success();
    }

    /**
     * 银行评估
     *
     * @param dksq
     * @return
     */
    @Override
    public AjaxResult pingGu(Dksq dksq) {
        if (!THR.equals(dksq.getType()) && !ONE.equals(dksq.getResult())) {
            return AjaxResult.error("当前状态异常");
        }
        //根据评估结果来设置状态
        String result = dksq.getResult();
        DksqLcjl dksqLcjl = new DksqLcjl();
        //流程记录
        dksqLcjl.setType(THR);
        dksqLcjl.setResult(result);
        //不通过
        if (THR.equals(result)){
         //回到人社局审核通过
            dksq.setType(TWO);
            dksq.setResult(TWO);
            dksq.setFdBank(null);
            dksq.setFdBankId(-1L);
        }else if(TWO.equals(result)){
            //通过进去到等待放贷
            dksq.setType(FOR);
            dksq.setResult(ONE);
        }
        dksqMapper.updateDksq(dksq);
        //插入流程记录表
        dksqLcjl.setDksqId(dksq.getId());
        dksqLcjl.setCreateBy(SecurityUtils.getUsername());
        dksqLcjlMapper.insertDksqLcjl(dksqLcjl);
        return AjaxResult.success();
    }

    /**
     * 银行放贷
     * @param dksq
     * @return
     */
    @Override
    public AjaxResult fangDai(Dksq dksq) {
        if (!FOR.equals(dksq.getType()) && !ONE.equals(dksq.getResult())) {
            return AjaxResult.error("当前状态异常");
        }
        //默认放贷成功
        //流程记录
        dksq.setResult(TWO);
        dksq.setFdTime(DateUtils.parseDate(DateUtils.getDate()));
        dksqMapper.updateDksq(dksq);
        //插入流程记录表
        DksqLcjl dksqLcjl = new DksqLcjl();
        dksqLcjl.setType(FOR);
        dksqLcjl.setResult(TWO);
        dksqLcjl.setDksqId(dksq.getId());
        dksqLcjl.setCreateBy(SecurityUtils.getUsername());
        dksqLcjlMapper.insertDksqLcjl(dksqLcjl);
        return AjaxResult.success();
    }

    /**
     * 首页统计
     * @return
     */
    @Override
    public AjaxResult index() {
        Dksq dksq = new Dksq();
        //定义返回值
        Map<String,Object> indexMap = new HashMap<>();
        Map<String,Object> up = new HashMap<>();
        up.put("sqCount",0);
        up.put("sqMoney",0);
        up.put("dbr",0);
        up.put("fc",0);
        up.put("dbrPer","00.0%");
        up.put("fcPer","00.0%");
        Map<String,Double> right = new HashMap<>();
        //获取所有银行名称
        SysDept sysDept = new SysDept();
        sysDept.setParentId(110L);
        List<SysDept> sysDepts = sysDeptMapper.selectDeptList(sysDept);
        if (sysDepts != null && sysDepts.size() > 0){
            for (SysDept dept : sysDepts) {
                right.put(dept.getDeptName(),0D);
            }
        }
        //判断用户角色 如果是银行角色
        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        if (roles != null && roles.size() > 0){
            for (SysRole role : roles) {
                if ("bank".equals(role.getRoleKey())){
                    //查询指派给自己的
                    dksq.setFdBankId(SecurityUtils.getLoginUser().getDeptId());
                    break;
                }
            }
        }
        //所有的贷款信息
        dksq.setCreateTime(DateUtils.parseDate(DateUtils.getDate()));
        List<Dksq> dksqs = dksqMapper.selectDksqList(dksq);
        if (dksqs != null && dksqs.size() > 0){
            //申请人数
            up.put("sqCount",dksqs.size());
            double sqMoney = dksqs.stream().mapToDouble(Dksq::getSqMoney).sum();
            up.put("sqMoney",sqMoney);
            //担保人担保
           double dbr = dksqs.stream().filter(s -> ONE.equals(s.getDbType())).count();
           //房产担保
            double fc = dksqs.stream().filter(s -> TWO.equals(s.getDbType())).count();
            up.put("dbr",dbr);
            up.put("fc",fc);
            Map<String, Double> collect = dksqs.stream().filter(s -> StringUtils.isNotBlank(s.getFdBank())).collect(Collectors.groupingBy(Dksq::getFdBank, Collectors.summingDouble(Dksq::getFdMoney)));
            for (String deptName : collect.keySet()) {
                right.put(deptName,collect.get(deptName));
            }
            NumberFormat nf  =  NumberFormat.getPercentInstance();
            nf.setMinimumFractionDigits( 1 );
            up.put("dbrPer",nf.format(dbr / (double) dksqs.size()));
            up.put("fcPer",nf.format(fc / (double)dksqs.size()));
        }
        indexMap.put("up",up);
        indexMap.put("right",right);
        return AjaxResult.success(indexMap);
    }

    /**
     * 首页eCharts
     * 每个月无担保 贷款金额和有担保贷款金额
     * @param dksq
     * @return
     */
    @Override
    public AjaxResult eCharts(Dksq dksq) {
        Object beginTime = dksq.getParams().get("beginTime");
        //把查询时间设置为20230101
        dksq.getParams().put("beginTime",beginTime+"0101");
        dksq.setType(FOR);
        dksq.setResult(TWO);
        Map<String,Object> indexMap = new HashMap<>();
        List<Object> months = new ArrayList<>();
        List<Object> y1 = new ArrayList<>();
        List<Object> y2 = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            months.add(i+"");
        }
        indexMap.put("x",months);
        List<Dksq> dksqs = dksqMapper.selectDksqList(dksq);
        if (dksqs != null && dksqs.size() > 0){
            //放贷统计
            Map<String, Double> collectY1 = dksqs.stream().filter(s -> ONE.equals(s.getDbGrade())).collect(Collectors.groupingBy(o -> DateUtils.format(o.getFdTime(), "M"), Collectors.summingDouble(Dksq::getFdMoney)));
            for (Object month : months) {
                Double aDouble = collectY1.get(month);
                if (aDouble == null){
                    y1.add(0);
                }else {
                    y1.add(aDouble);
                }
            }
            //放贷统计
            Map<String, Double> collectY2 = dksqs.stream().filter(s -> !ONE.equals(s.getDbGrade())).collect(Collectors.groupingBy(o -> DateUtils.format(o.getFdTime(), "M"), Collectors.summingDouble(Dksq::getFdMoney)));
            for (Object month : months) {
                Double aDouble = collectY2.get(month);
                if (aDouble == null){
                    y2.add(0);
                }else {
                    y2.add(aDouble);
                }
            }
        }
        indexMap.put("y1",y1);
        indexMap.put("y2",y2);
        return AjaxResult.success(indexMap);
    }
}
