package com.sifang.modules.account.service;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.account.dao.TraderAccountDao;
import com.sifang.modules.account.entity.CrmTraderAccount;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.util.LayuiPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TraderAccountService extends BaseService {

    @Autowired
    private TraderAccountDao traderAccountDao;

    public CrmTraderAccount findByTraderId(String traderId) {
        return traderAccountDao.findByTraderId(traderId);
    }

    public void addSettleAmount(String traderId, BigDecimal settleAmount) {
        int row = traderAccountDao.addSettleAmount(traderId, settleAmount);
        if (row == 0) {
            throw new BusinessException("增加分包款余额失败");
        }
    }

    public void addBasicQuotaAmountBalance(String traderId, BigDecimal settleAmount) {
        int row = traderAccountDao.addBasicQuotaAmountBalance(traderId, settleAmount);
        if (row == 0) {
            throw new BusinessException("增加标准授信额余额失败");
        }
    }

    public void addMaxQuotaAmountBalance(String traderId, BigDecimal settleAmount) {
        int row = traderAccountDao.addMaxQuotaAmountBalance(traderId, settleAmount);
        if (row == 0) {
            throw new BusinessException("增加可授信额上限余额失败");
        }
    }

    public void listTraderAccount(Map<String, String> queryParams, LayuiPage page){
        List<Record> accountList = traderAccountDao.listTraderAccount(queryParams, page);
        Long cnt = traderAccountDao.countTraderAccount(queryParams);
        page.setData(accountList);
        page.setCount(cnt);
    }
    public List<Record> getListForExportExcel(Map<String, String> map){
        return traderAccountDao.getListForExportExcel(map);
    }

    public Record getBondDetail(String traderId){
        Record record= traderAccountDao.getBondDetail(traderId);
        return record;
    }

    public void djsAccountChangeList(LayuiPage<Record> page, Map<String, String> map){
        traderAccountDao.djsAccountChangeList(page, map);
    }

    public void zbjAccountChangeLst(LayuiPage<Record> page, Map<String, String> map){
        traderAccountDao.zbjAccountChangeLst(page, map);
    }

    /**
     * 首次发货额度：实缴保证金金额+min(通过踏勘审核的进件量*1.2倍，保证金*2倍）
     * 发货额度：min(实缴保证金金额+保证金*2倍-累计未安装量，保证金*5倍-累计未并网量）
     * 累计已发货：代理商物料申请单，平台已确认发货数量*零售价；
     * 累计已安装：标记已安装电站容量（MW）*1.5*1000000/10000
     * 累计已并网量：标记已已并网电站容量（MW）*1.5*1000000/10000
     * 累计未安装：累计已发货-累计已安装
     * 累计未并网：累计已发货-累计已并网
     */
    public BigDecimal countLimit(String traderId,String type){
        logger.info(">>>countLimit  traderId:{},type:{}",traderId,type);
        try{
            if("0".equals(type)){
                //取信用额度 的设置
                Record edSet=traderAccountDao.getEdSetRecord(traderId,"1");
                Record record=traderAccountDao.countLimit(traderId);
                //获取友夸初始阶段踏勘量
                CrmTraderAccount account = traderAccountDao.findByTraderId(traderId);
                BigDecimal ykTklTotalCapacity = account.getYkTklTotalCapacity();
                logger.info(">>>>>>>>>>>>>>>countLimit  one record:{}",record);
                BigDecimal totalCapacity=record.getBigDecimal("totalCapacity");
                if(totalCapacity==null){
                    totalCapacity=ykTklTotalCapacity;
                }else {
                    totalCapacity = totalCapacity.add(ykTklTotalCapacity);
                }
                if(edSet==null){
                    throw new IllegalArgumentException("请先账号设置首次发货授信方案！");
                }
                BigDecimal edOne=totalCapacity.multiply(edSet.getBigDecimal("capacity_ratio")).multiply(edSet.getBigDecimal("capacity_multiple"));
                BigDecimal edTwo=record.getBigDecimal("bond_amount_limit").multiply(edSet.getBigDecimal("amount"));
                logger.info(">>>>>>>>>>>countLimit   edOne:{},edTwo:{}",edOne,edTwo);
                BigDecimal resultEd=edOne.compareTo(edTwo)>0?edTwo:edOne; //取二者的最小值
                resultEd= (resultEd.add(record.getBigDecimal("bzj_amount"))).divide(BigDecimal.ONE, 2);
                resultEd = (resultEd.add(record.getBigDecimal(  "ykBzjAmount"))).divide(BigDecimal.ONE, 2);
                return resultEd;
            }else{
                //取信用额度 的设计
                Record edSet2=traderAccountDao.getEdSetRecord(traderId,"2");
                Record recordTwo= traderAccountDao.countLimitTwo(traderId);
                logger.info(">>>>>>>>>>>>>>>countLimit  recordTwo:{}",recordTwo);
                BigDecimal oneEd=BigDecimal.ZERO;
                BigDecimal twoEd=BigDecimal.ZERO;
                if(recordTwo!=null){
                    oneEd=recordTwo.getBigDecimal("bzj_amount").add(recordTwo.getBigDecimal("ykBzjAmount")).add(recordTwo.getBigDecimal("bond_amount_limit").multiply(edSet2.getBigDecimal("amount"))).subtract(recordTwo.getBigDecimal("deliverTotalAmount").subtract(recordTwo.getBigDecimal("yazTotalCapacity1")).add(recordTwo.getBigDecimal("yk_deliverTotalCapacity").subtract(recordTwo.getBigDecimal("ykYazTotalCapacity"))));
                    twoEd=recordTwo.getBigDecimal("bond_amount_limit").multiply(edSet2.getBigDecimal("capacity_multiple")).subtract(recordTwo.getBigDecimal("deliverTotalAmount").subtract(recordTwo.getBigDecimal("ybwTotalCapacity1")).add(recordTwo.getBigDecimal("yk_deliverTotalCapacity").subtract(recordTwo.getBigDecimal("ykYbwTotalCapacity"))));
                }
                logger.info(">>>>>>>>>>>>countLimit oneEd:{},twoEd:{}",oneEd,twoEd);
                BigDecimal resultEd= oneEd.compareTo(twoEd)>0?twoEd:oneEd;
                resultEd.divide(BigDecimal.ONE, 2);
                return resultEd;
            }
        }catch (NullPointerException n){
            return BigDecimal.ZERO;
        }

    }

    public Map<String,Object> countLimit2(String traderId,String type){
        logger.info(">>>countLimit  traderId:{},type:{}",traderId,type);
        Map<String,Object> map = new HashMap<>();
        try{
            if("0".equals(type)){
                //取信用额度 的设置
                Record edSet=traderAccountDao.getEdSetRecord(traderId,"1");
                Record record=traderAccountDao.countLimit(traderId);
                //获取友夸初始阶段踏勘量
                CrmTraderAccount account = traderAccountDao.findByTraderId(traderId);
                BigDecimal ykTklTotalCapacity = account.getYkTklTotalCapacity();
                logger.info(">>>>>>>>>>>>>>>countLimit  one record:{}",record);
                BigDecimal totalCapacity=record.getBigDecimal("totalCapacity");
                if(totalCapacity==null){
                    totalCapacity=ykTklTotalCapacity;
                }else {
                    totalCapacity = totalCapacity.add(ykTklTotalCapacity);
                }
                if(edSet==null){
                    throw new IllegalArgumentException("请先账号设置首次发货授信方案！");
                }
                map.put("totalCapacity",totalCapacity);//通过踏勘审核的进件量
                BigDecimal edOne=totalCapacity.multiply(edSet.getBigDecimal("capacity_ratio")).multiply(edSet.getBigDecimal("capacity_multiple"));
                //保证金额度
                BigDecimal bondAmountLimit = record.getBigDecimal("bond_amount_limit");
                map.put("bondAmountLimit",bondAmountLimit);//保证金额度
                BigDecimal edTwo= bondAmountLimit.multiply(edSet.getBigDecimal("amount"));
                logger.info(">>>>>>>>>>>countLimit   edOne:{},edTwo:{}",edOne,edTwo);
                BigDecimal resultEd=edOne.compareTo(edTwo)>0?edTwo:edOne; //取二者的最小值
                //实缴保证金金额
                BigDecimal bzjAmount = record.getBigDecimal("bzj_amount");
                //友夸实缴保证金金额
                BigDecimal ykBzjAmount = record.getBigDecimal("ykBzjAmount");
                map.put("bzjAmount",bzjAmount);//实缴保证金金额
                map.put("ykBzjAmount",ykBzjAmount);//友夸实缴保证金金额
                map.put("totalBzjAmount",bzjAmount.add(ykBzjAmount));
                resultEd= (resultEd.add(bzjAmount)).divide(BigDecimal.ONE, 2);
                resultEd = (resultEd.add(ykBzjAmount)).divide(BigDecimal.ONE, 2);
                map.put("ed",resultEd);//总信用额度
                return map;
            }else{
                //取信用额度 的设计
                Record edSet2=traderAccountDao.getEdSetRecord(traderId,"2");
                Record recordTwo= traderAccountDao.countLimitTwo(traderId);
                logger.info(">>>>>>>>>>>>>>>countLimit  recordTwo:{}",recordTwo);
                BigDecimal oneEd=BigDecimal.ZERO;
                BigDecimal twoEd=BigDecimal.ZERO;
                if(recordTwo!=null){
                    BigDecimal bzjAmount = recordTwo.getBigDecimal("bzj_amount");
                    map.put("bzjAmount",bzjAmount);//实缴保证金金额
                    BigDecimal ykBzjAmount = recordTwo.getBigDecimal("ykBzjAmount");//友夸实缴保证金金额
                    map.put("ykBzjAmount",ykBzjAmount);//友夸实缴保证金金额
                    map.put("totalBzjAmount",bzjAmount.add(ykBzjAmount));
                    BigDecimal bondAmountLimit = recordTwo.getBigDecimal("bond_amount_limit");//保证金额度
                    map.put("bondAmountLimit",bondAmountLimit);//保证金额度
                    BigDecimal wazTotalCapacity = recordTwo.getBigDecimal("deliverTotalAmount").subtract(recordTwo.getBigDecimal("yazTotalCapacity1")).add(recordTwo.getBigDecimal("yk_deliverTotalCapacity").subtract(recordTwo.getBigDecimal("ykYazTotalCapacity")));
                    map.put("wazTotalCapacity",wazTotalCapacity);//累计未安装量
                    oneEd= bzjAmount.add(ykBzjAmount).add(bondAmountLimit.multiply(edSet2.getBigDecimal("amount"))).subtract(wazTotalCapacity);
                    BigDecimal wbwTotalCapacity = recordTwo.getBigDecimal("deliverTotalAmount").subtract(recordTwo.getBigDecimal("ybwTotalCapacity1")).add(recordTwo.getBigDecimal("yk_deliverTotalCapacity").subtract(recordTwo.getBigDecimal("ykYbwTotalCapacity")));
                    map.put("wbwTotalCapacity",wbwTotalCapacity);//累计未并网
                    twoEd= bondAmountLimit.multiply(edSet2.getBigDecimal("capacity_multiple")).subtract(wbwTotalCapacity);
                }
                logger.info(">>>>>>>>>>>>countLimit oneEd:{},twoEd:{}",oneEd,twoEd);
                BigDecimal resultEd= oneEd.compareTo(twoEd)>0?twoEd:oneEd;
                resultEd.divide(BigDecimal.ONE, 2);
                map.put("ed",resultEd);//总信用额度
                return map;
            }
        }catch (NullPointerException n){
            map.put("ed",BigDecimal.ZERO);
            return map;
        }

    }

}
