package com.ag.account.service;

import com.ag.account.dao.BizContractsDao;
import com.ag.base.SqlUtil;
import com.ag.entity.account.vo.BizVO;
import com.ag.entity.fee.AccountPoints;
import com.ag.entity.fee.ItemProperties;
import com.ag.entity.fee.TariffMultistep;
import com.ag.entity.fee.TariffRitem;
import com.ag.entity.fee.vo.ContractItemVO;
import com.ag.entity.fee.vo.ContractVO;
import com.ag.entity.fee.vo.TariffVO;
import com.ag.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 将合同对象下的所有对象组装到合同对象
 * Created by Administrator on 2017/6/13 0013.
 */
@Service
public class BizContractsService {
    @Autowired
    private BizContractsDao bizContractsDao;


    /**
     * 设置默认合同
     * @param bizVO
     * @return
     */
    private String setDefaultContract(BizVO bizVO) {
        if (bizVO.getDefaultContractVo() != null){
            return bizVO.getDefaultContractVo().getId();
        }
        //费目id集合
        String ids = new SqlUtil<AccountPoints>().getAddInIds(bizVO.getPointLst(), "itemId");
        bizVO.setItemIds(ids);
        String defaultContractId = bizContractsDao.findDefaultContractId(bizVO);
        //查找标准合同费目费率everything
        bizVO.setDefaultContractVo(getContractVO(defaultContractId, bizVO));
        return defaultContractId;
    }

    /**
     * 客户合同号找合同对象
     * 存在则返回，不存在查询并加入合同列表
     */
    public ContractVO getContractVO(String defaultContractId, BizVO bizVO){
        //货主默认合同号为空
        if (StrUtil.isEmpty(defaultContractId)){
            return null;
        }
        if ("[]".equals(defaultContractId)){
            return null;
        }
        if (bizVO.getBizTime() == null){
            bizVO.setBizTime(new Date());
        }
        //wb数组处理（客户合同格式["6bb8cac321de49979bd0f9c97bc9d449","1ab8a85990a34d1c95773b9b664fcf49"]）
        if (defaultContractId.contains("[")) {
            defaultContractId = defaultContractId.replace("[","").replace("]","").replace("\"","'");
        }else {
            defaultContractId = "'" + defaultContractId + "'";
        }
        ContractVO contractId = bizContractsDao.findContractId(defaultContractId, bizVO);
        if (contractId == null){
            return null;
        }
        defaultContractId = contractId.getId();
        List<ContractVO> appendContractVO = bizVO.getAppendContractVO();
        for (ContractVO append : appendContractVO){
            if (append.getId().equals(defaultContractId)){
                return append;
            }
        }
        //查找标准合同费目费率everything
        ContractVO contractVO = findContractVO(defaultContractId, bizVO);
        appendContractVO.add(contractVO);
        return contractVO;
    }



    /**
     * 查找标准合同费目费率everything实现
     * @param defaultContractId
     * @param bizVO
     * @return
     */
    public ContractVO findContractVO(String defaultContractId, BizVO bizVO) {
        //long sum = 0l;
        //long on = System.currentTimeMillis();
        //合同
        ContractVO contrVO = bizContractsDao.findContractVOById(defaultContractId, bizVO);
        //合同费目
        List<ContractItemVO> items = bizContractsDao.findItemByContract(defaultContractId, bizVO);
        //费率
        List<TariffVO> tariffs = bizContractsDao.findTariffByContract(defaultContractId, bizVO);
        //费率条件
        List<TariffRitem> ritems = bizContractsDao.findRitemByTariff(defaultContractId, bizVO);
        //阶梯费率
        List<TariffMultistep> steps = bizContractsDao.findStepByTariff(defaultContractId, bizVO);
        //费目属性
        List<ItemProperties> properties = bizContractsDao.findPropertiesByItems(bizVO);

        /*List<TariffVO> customTariffs = bizContractsDao.findCustomTariffByContract(defaultContractId, bizVO);
        List<TariffRitem> customRitems = bizContractsDao.findCustomRitemByTariff(defaultContractId, bizVO);
        List<TariffMultistep> customSteps = bizContractsDao.findCustomStepByTariff(defaultContractId, bizVO);*/

        //计免条件
        /*List<ContractItemRuleVO> rules = bizContractsDao.findRuleByContract(defaultContractId, bizVO);
        List<ContractItemRuleCondition> conditions = bizContractsDao.findConditionByContract(defaultContractId, bizVO);*/
        //long end = System.currentTimeMillis();
        //sum = end - on;
        //System.out.println("费率查询时间："+sum);
        //on = System.currentTimeMillis();
        contrVO.setItemLst(items);
        //完善非客户费率
        mergeTariffVO(tariffs, ritems);
        mergeTariffStep(tariffs, steps);
        //完善客户费率
        /*mergeTariffVO(customTariffs, customRitems);
        mergeTariffStep(customTariffs, customSteps);*/
        //计费免费规则
        //mergeRuleConditionVO(rules, conditions);
        //赋值驳船费率
        mergeItemTariffVO(items, tariffs);
        mergeItemProperties(items, properties);
        //赋值驳船（客户）费率
        //mergeItemTariffVO(items, customTariffs, 2);
        //费目绑定计免费规则
        //mergeItemRuleVO(items, rules);
        //end = System.currentTimeMillis();
       // sum = end - on;
        //System.out.println("费率合并时间："+sum);
        //赋值合同费目名称
        //mergeItemName(items, bizVO.getItemList());
        return contrVO;
    }

    private void mergeItemProperties(List<ContractItemVO> items, List<ItemProperties> properties) {
        for (ContractItemVO vo : items){
            List<ItemProperties> pros = new ArrayList<>();
            vo.setItemProperties(pros);
            for (ItemProperties property : properties){
                if (vo.getItemId().equals(property.getItemId())){
                    pros.add(property);
                }
            }
            pros.sort((a, b) -> a.getDispOrder() - b.getDispOrder());
        }
    }


    private void mergeItemTariffVO(List<ContractItemVO> items, List<TariffVO> tariffs) {
        if(CollectionUtils.isEmpty(tariffs)){
            return;
        }
        for(ContractItemVO item : items){
            List<TariffVO> groupTariffs = new ArrayList<>();
            item.setTariffLst(groupTariffs);
            for(TariffVO tariff : tariffs){
                if(tariff.getChargingId().equals(item.getItemId())){
                    groupTariffs.add(tariff);
                }
            }
        }
    }

    private void mergeTariffVO(List<TariffVO> tarLst, List<TariffRitem> ritemLst) {
        for (TariffVO vo : tarLst) {
            List<TariffRitem> ritems = new ArrayList<>();
            vo.setRitemList(ritems);
            for (TariffRitem ritem : ritemLst) {
                if (vo.getId().equals(ritem.getRuleId())) {
                    ritems.add(ritem);
                }
            }
        }
    }

    private void mergeTariffStep(List<TariffVO> tariffs, List<TariffMultistep> stepLst) {
        for (TariffVO vo : tariffs) {
            List<TariffMultistep> steps = new ArrayList<>();
            vo.setStepList(steps);
            for (TariffMultistep step : stepLst) {
                if (vo.getId().equals(step.getTariffId())) {
                    steps.add(step);
                }
            }
        }
    }

}
