package com.sifang.modules.customer.Service;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.AccountSetConstants;
import com.sifang.modules.customer.dao.AccountSetDao;
import com.sifang.modules.customer.dao.AccountSetDetailsDao;
import com.sifang.modules.customer.entity.CrmAccountSet;
import com.sifang.modules.customer.entity.CrmAccountSetDetails;
import com.sifang.modules.customer.vo.AccountSetVo;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class AccountSetService extends BaseService {

    @Autowired
    private AccountSetDao accountSetDao;

    @Autowired
    private AccountSetDetailsDao setDetailsDao;


    @Transactional(rollbackFor = Exception.class)
    public void saveAccountSet(AccountSetVo setVo){
        logger.info(">>>>>>>>>>>saveAccountSet  type:{},items",setVo.getType(),setVo.getItems().size());
        CrmAccountSet accountSet=accountSetDao.getByType(setVo.getType());
        List<CrmAccountSetDetails> items= setVo.getItems();
        int i=1;
        StringBuffer sb=new StringBuffer();

        List<String> traderList=new ArrayList<>();
        for(CrmAccountSetDetails details:items){
            logger.info(">>>>>>>>>>>saveAccountSet detail:{}",details);
           details.setSetId(accountSet.getId());
           if("1".equals(details.getRangeTap())){
                details.setTraderId(null);
           }else{
               if(StringUtil.isBlank(details.getTraderId())){
                   throw new RuntimeException("第 "+i +"个方案，请设置指定的代理商!");
               }
               for(String tid:details.getTraderId().split(",")){
                   if(traderList.contains(tid)){
                       throw new RuntimeException("第 "+i +"个方案，指定的代理商和前面方案重复!");
                   }
                   traderList.add(tid);
               }
           }
           if(AccountSetConstants.TYPE_YJS_PROPORTION.equals(setVo.getType())){
               sb.append("方案"+i+": 结算款账户方案="+details.getAmount().setScale(2)+"%"+("1".equals(details.getRangeTap())?";所有代理商":";指定代理商")+"。");
               details.setName("方案"+i);
           }else if(AccountSetConstants.TYPE_STAND_PRICE.equals(setVo.getType())){
               sb.append(/*"方案"+i+":"+*/details.getName()+"：首次发货授信额=实缴保证金金额 + min((申请赊销下单电站的设计容量*"+details.getCapacityRatio()+")*"+details.getCapacityMultiple()+"， 保证金"+details.getAmount().setScale(2)+") "+("1".equals(details.getRangeTap())?"；所有代理商":"；指定代理商")+"。");
           }else if(AccountSetConstants.TYPE_AMOUNT_TOP.equals(setVo.getType())){
               sb.append(/*"方案"+i+":"+*/details.getName()+"：标准发货授信额= min(实缴保证金金额+保证金*"+details.getAmount()+" - 累计未安装量，保证金*"+details.getCapacityMultiple().setScale(2)+"-累计未并网量) "+("1".equals(details.getRangeTap())?"；所有代理商":"；指定代理商")+"。");
           }

           i++;
        }

        accountSet.setContent(sb.toString());
        accountSetDao.save(accountSet);
        //删除之前设置的
        setDetailsDao.deleteDetail(accountSet.getId());
        setDetailsDao.save(items);
    }

    public void saveOtherAccountSet(String type,String amount,String way){
        logger.info(">>>>>>>>>>>>>saveOtherAccountSet  type:{},amount:{}",type,amount);
        CrmAccountSet accountSet=accountSetDao.getByType(type);
        accountSet.setProportion(new BigDecimal(amount));
        accountSet.setWay(way);
        accountSetDao.save(accountSet);
    }

    /**
     * 获取预结算比例
     */
    public BigDecimal findYjsProportion(String traderId) {
        Record set = accountSetDao.getTraderVsAccount(traderId,AccountSetConstants.TYPE_YJS_PROPORTION);
        if (set == null) {
            return null;
        }
        BigDecimal bg=set.getBigDecimal("amount");
        return bg;
    }

    /**
     * 获取授信额计算规则
     */
  public  Record findTraderSxeProportion(String traderId,String type) {
        Record set = accountSetDao.getTraderVsAccount(traderId,type);
       return set;
    }



    /**
     * 获取质保金单价设置
     */
   public Record findZBJSinglePrice() {
        Record set = accountSetDao.findByType(AccountSetConstants.TYPE_ZBJ_SINGLE_PRICE);
        if (set == null) {
            return null;
        }
        return set;
    }

    public List<Record> getSetDetail(String type){
        return accountSetDao.getSetDetail(type);
    }

    public Map<String,Record> getAccountList(){
        List<Record> list=accountSetDao.getAccountList();
        Map<String,Record> map=new HashMap<>();
        if(list.size()>0){
            for(Record r:list){
                map.put(r.getStr("type"),r);
            }
        }
        return map;
    }
}
