package common.service.impl;

import com.google.api.ads.adwords.lib.AdWordsProductFrameworkModule;
import common.model.*;
import common.repository.*;
import common.service.ContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tkio.model.PackageType;
import tkio.repository.PackageTypeRepository;
import tkio.service.AccountService;
import util.DateUtil;
import util.ValidateUtil;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

/**
 * Created by mxq on 2018/1/16.
 */
@Service
public class ContractServiceImpl implements ContractService{

    @Autowired
    ContractRepository contractRepository;
    @Autowired
    ContractBodyRepository contractBodyRepository;
    @Autowired
    Account4WebRepository account4WebRepository;
    @Autowired
    PackageTypeRepository packageTypeRepository;
    @Autowired
    PriceLevelMoneyRepository priceLevelMoneyRepository;
    @Autowired
    UserRepository userRepository;
    @Autowired
    ContractChangeRepository contractChangeRepository;
    @Autowired
    ContractMoneyRepository contractMoneyRepository;
    @Autowired
    AccountService accountService;

    @Override
    public Map<String, Object> checkAccount(String email, String platfrom) {
        Map<String, Object> map = new HashMap<>();
        Account4Web account4Web = account4WebRepository.findByEmail(email);
        if(null == account4Web){
            map.put("result", 0);
        }else{
            BigInteger integer = contractRepository.countNumByEmail(email,platfrom);
            map.put("result", 1);
            map.put("company", account4Web.getCompany());
            map.put("num", integer.intValue());
        }
        return map;
    }

    @Override
    public List<ContractBody> findBody() {
        return contractBodyRepository.findAll();
    }

    @Override
    public String getContractCode(String code) {
        BigInteger integer = contractRepository.countNumByDs(DateUtil.getBeforeDays(0));
        String lastCode = "";
        if(integer.intValue() < 9){
            lastCode = "0" + (integer.intValue() + 1);
        }else{
            lastCode = "" + (integer.intValue() + 1);
        }
        String re = code + "-" + DateUtil.getDays2(0) + lastCode;
        return re;
    }

    @Override
    public List<PackageType> findSetmeal() {
        return packageTypeRepository.findAll();
    }

    @Override
    public Double getRebat(String product, Integer level, Long money) {
        PriceLevelMoney levelMoney = priceLevelMoneyRepository.getOne(product, level);
        return money * 1.0  / levelMoney.getMoney();
    }

    @Override
    public List<User> getSales() {
        return userRepository.findSales();
    }

    @Override
    public Contract create(User loginUser, Contract resource) {
        resource.setPayMoney(0L);
        resource.setInvoice(0L);
        if(DateUtil.getBeforeDays(0).compareTo(resource.getStartDate()) < 0){
            resource.setDs(DateUtil.getBeforeDays(0));
            resource.setStatus("wait");
        }else{
            resource.setDs(DateUtil.getBeforeDays(0));
            resource.setStatus("executing");
        }

        Double rebat = getRebat(resource.getProduct(), resource.getPriceLevel().intValue(), resource.getMoney());
        BigDecimal bg = new BigDecimal(rebat);
        double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        resource.setRebate(f1);

        resource.setCreateAccount(loginUser.getId());
        resource.setCreateTime(new Date());

        //同步修改trackingio的数据
        if(resource.getPlatform().equals("tkio")){
            accountService.update(resource);
        }
        return contractRepository.save(resource);
    }

    @Override
    public Contract update(User loginUser, Contract resource) {
        Map<Long, String> packageMap = getPackageMap();
        Map<Long, String> saleMap = getSaleMap();
        Contract contract = contractRepository.findOne(resource.getId());

        ContractChange cc = new ContractChange();
        cc.setType("update");
        cc.setUser(loginUser.getId());
        cc.setDs(DateUtil.getBeforeDays(0));
        cc.setContent("");
        cc.setEmail(contract.getEmail());
        cc.setCompany(contract.getCustomerBody());
        cc.setContractCode(contract.getContractCode());

        if(!resource.getStartDate().equals(contract.getStartDate())){
            cc.setContent(cc.getContent() + "开始时间变更 : " + contract.getStartDate() + "-->" + resource.getStartDate());
            contract.setStartDate(resource.getStartDate());
            if(DateUtil.getBeforeDays(0).compareTo(resource.getStartDate()) < 0){
                contract.setStatus("wait");
            }else{
                contract.setStatus("executing");
            }
        }
        if(!resource.getEndDate().equals(contract.getEndDate())){
            cc.setContent(cc.getContent() + "   结束时间变更 : " + contract.getEndDate() + "-->" + resource.getEndDate());
            contract.setEndDate(resource.getEndDate());
        }

        boolean newRebat = false;
        if(!resource.getPriceLevel().equals(contract.getPriceLevel())){
            cc.setContent(cc.getContent() +  "  套餐变更：" + packageMap.get(contract.getPriceLevel()) + "-->" + packageMap.get(resource.getPriceLevel()));
            newRebat = true;
            contract.setPriceLevel(resource.getPriceLevel());
        }

        if(!resource.getMoney().equals(contract.getMoney())){
            cc.setContent(cc.getContent() + "   金额变更： " + contract.getMoney() + "-->" + resource.getMoney());
            newRebat = true;
            contract.setMoney(resource.getMoney());
        }

        if(!resource.getSale().equals(contract.getSale())){
            cc.setContent(cc.getContent() + "销售变更：" + saleMap.get(contract.getSale()) + "-->" + saleMap.get(resource.getSale()));
            contract.setSale(resource.getSale());
        }

        if(newRebat){
            Double rebat = getRebat(contract.getProduct(), contract.getPriceLevel().intValue(), contract.getMoney());
            BigDecimal bg = new BigDecimal(rebat);
            double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            contract.setRebate(f1);
        }
        cc.setPlatform(contract.getPlatform());
        contractChangeRepository.save(cc);

        //同步修改trackingio的数据
        if(contract.getPlatform().equals("tkio")){
            accountService.update(contract);
        }
        return contractRepository.save(contract);
    }

    @Override
    public List<Contract> findAll(String startDate, String endDate, String platfrom) {
        List<Contract> result = new ArrayList<>();
        List<User> sales = userRepository.findAll();
        Map<Long, String> saleMap = new HashMap<>();
        if(ValidateUtil.isValid(sales)){
            for(User s: sales){
                saleMap.put(s.getId(), s.getName());
            }
        }
        List<PackageType> typeList = packageTypeRepository.findAll();
        Map<Long, String> typeMap = new HashMap<>();
        if(ValidateUtil.isValid(typeList)){
            for(PackageType s: typeList){
                typeMap.put(s.getId(), s.getPackageName());
            }
        }
        List<Contract> contractList = contractRepository.findByDs(startDate, endDate, platfrom);
        if(ValidateUtil.isValid(contractList)){
            for(Contract c : contractList){
                c.setSaleName(saleMap.containsKey(c.getSale()) ? saleMap.get(c.getSale()) : "");
                c.setPriceLevelName(typeMap.containsKey(c.getPriceLevel()) ? typeMap.get(c.getPriceLevel()) : "");
                c.setCreateName(saleMap.containsKey(c.getCreateAccount()) ? saleMap.get(c.getCreateAccount()) : "");
                result.add(c);
            }
        }
        return result;
    }

    @Override
    public Contract findOne(String code) {

        List<Contract> result = new ArrayList<>();
        List<User> sales = userRepository.findAll();
        Map<Long, String> saleMap = new HashMap<>();
        if(ValidateUtil.isValid(sales)){
            for(User s: sales){
                saleMap.put(s.getId(), s.getName());
            }
        }
        List<PackageType> typeList = packageTypeRepository.findAll();
        Map<Long, String> typeMap = new HashMap<>();
        if(ValidateUtil.isValid(typeList)){
            for(PackageType s: typeList){
                typeMap.put(s.getId(), s.getPackageName());
            }
        }
        Contract contract = contractRepository.findByCode(code);
        contract.setSaleName(saleMap.containsKey(contract.getSale()) ? saleMap.get(contract.getSale()) : "");
        contract.setPriceLevelName(typeMap.containsKey(contract.getPriceLevel()) ? typeMap.get(contract.getPriceLevel()) : "");
        contract.setCreateName(saleMap.containsKey(contract.getCreateAccount()) ? saleMap.get(contract.getCreateAccount()) : "");

        return contract;
    }

    @Override
    public ContractMoney pay(User loginUser, ContractMoney resource) {
        Contract contract = contractRepository.findByCode(resource.getContractCode());
        if(resource.getType().equals("pay")){
            contract.setPayMoney(contract.getPayMoney() + resource.getMoney());
        } else {
            contract.setInvoice(contract.getInvoice() + resource.getMoney());
        }
        contractRepository.save(contract);

        resource.setPlatform(contract.getPlatform());
        resource.setCreateAccount(loginUser.getId());
        resource.setCreateTime(new Date());
        resource.setUser(loginUser.getId());
        return contractMoneyRepository.save(resource);
    }

    @Override
    public Contract change(User loginUser, ContractChange resource) {
        Map<Long, String> packageMap = getPackageMap();
        Map<Long, String> saleMap = getSaleMap();
        Contract contract = contractRepository.findByCode(resource.getContractCode());
        if(resource.getType().equals("price")){
            resource.setContent("套餐变更 ：" + packageMap.get(contract.getPriceLevel()) + "-->" + packageMap.get(resource.getLevel())
                    + " 金额变更 ：" + contract.getMoney() + "-->" +(resource.getMoney() + contract.getMoney()));

            contract.setMoney(resource.getMoney() + contract.getMoney());
            contract.setPriceLevel(resource.getLevel());
            Double rebat = getRebat(contract.getProduct(), contract.getPriceLevel().intValue(), contract.getMoney());
            BigDecimal bg = new BigDecimal(rebat);
            double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            contract.setRebate(f1);

            //同步修改trackingio的数据
            if(contract.getPlatform().equals("tkio")){
                accountService.update(contract);
            }
        }else{
            //同步修改trackingio的数据
            if(contract.getPlatform().equals("tkio")){
                accountService.forbiden(contract);
            }
            contract.setStatus("cancel");
        }
        resource.setPlatform(contract.getPlatform());
        resource.setCreateAccount(loginUser.getId());
        resource.setCreateTime(new Date());
        resource.setDs(DateUtil.getBeforeDays(0));
        resource.setUser(loginUser.getId());
        contractChangeRepository.save(resource);

        return contractRepository.save(contract);
    }

    @Override
    public List<ContractMoney> findPay(String startDate, String endDate, String code) {
        List<User> sales = userRepository.findAll();
        Map<Long, String> saleMap = new HashMap<>();
        if(ValidateUtil.isValid(sales)){
            for(User s: sales){
                saleMap.put(s.getId(), s.getName());
            }
        }

        List<ContractMoney> result  = new ArrayList<>();
        List<ContractMoney> list = contractMoneyRepository.findByDs(startDate, endDate,code);
        if(ValidateUtil.isValid(list)){
            for(ContractMoney cm : list){
                cm.setCreateName(saleMap.containsKey(cm.getUser()) ? saleMap.get(cm.getUser()) : "");
                result.add(cm);
            }
        }
        return result;
    }

    @Override
    public List<ContractChange> findChange(String startDate, String endDate, String code) {

        List<User> sales = userRepository.findAll();
        Map<Long, String> saleMap = new HashMap<>();
        if(ValidateUtil.isValid(sales)){
            for(User s: sales){
                saleMap.put(s.getId(), s.getName());
            }
        }

        List<ContractChange> result  = new ArrayList<>();
        List<ContractChange> list = contractChangeRepository.findByDs(startDate, endDate,code);
        if(ValidateUtil.isValid(list)){
            for(ContractChange cm : list){
                cm.setCreateName(saleMap.containsKey(cm.getUser()) ? saleMap.get(cm.getUser()) : "");
                result.add(cm);
            }
        }
        return result;
    }

    @Override
    public Contract updatePay(User loginUser, ContractMoney resource) {
        ContractMoney contractMoney = contractMoneyRepository.findOne(resource.getId());
        Contract contract = contractRepository.findByCode(resource.getContractCode());
        if(contractMoney.getType().equals("pay")){
            contract.setPayMoney(contract.getPayMoney() + resource.getMoney() - contractMoney.getMoney());
        } else {
            contract.setInvoice(contract.getInvoice() + resource.getMoney() - contractMoney.getMoney());
        }
        Contract save = contractRepository.save(contract);

        contractMoney.setModifyAccount(loginUser.getId());
        contractMoney.setModifyTime(new Date());
        contractMoney.setMoney(resource.getMoney());
        contractMoney.setDs(resource.getDs());
        contractMoneyRepository.save(contractMoney);

        List<User> sales = userRepository.findAll();
        Map<Long, String> saleMap = new HashMap<>();
        if(ValidateUtil.isValid(sales)){
            for(User s: sales){
                saleMap.put(s.getId(), s.getName());
            }
        }
        List<PackageType> typeList = packageTypeRepository.findAll();
        Map<Long, String> typeMap = new HashMap<>();
        if(ValidateUtil.isValid(typeList)){
            for(PackageType s: typeList){
                typeMap.put(s.getId(), s.getPackageName());
            }
        }

        save.setSaleName(saleMap.containsKey(save.getSale()) ? saleMap.get(save.getSale()) : "");
        save.setPriceLevelName(typeMap.containsKey(save.getPriceLevel()) ? typeMap.get(save.getPriceLevel()) : "");
        save.setCreateName(saleMap.containsKey(save.getSale()) ? saleMap.get(save.getSale()) : "");
        return save;
    }

    @Override
    public List<ContractMoney> findPayAll(String startDate, String endDate, String platfrom) {
        List<User> sales = userRepository.findAll();
        Map<Long, String> saleMap = new HashMap<>();
        if(ValidateUtil.isValid(sales)){
            for(User s: sales){
                saleMap.put(s.getId(), s.getName());
            }
        }

        List<ContractMoney> result  = new ArrayList<>();
        List<ContractMoney> list = contractMoneyRepository.findByDsAll(startDate, endDate, platfrom);
        if(ValidateUtil.isValid(list)){
            for(ContractMoney cm : list){
                cm.setCreateName(saleMap.containsKey(cm.getUser()) ? saleMap.get(cm.getUser()) : "");
                result.add(cm);
            }
        }
        return result;
    }

    public Map<Long, String> getPackageMap(){
        List<PackageType> typeList = packageTypeRepository.findAll();
        Map<Long, String> typeMap = new HashMap<>();
        if(ValidateUtil.isValid(typeList)){
            for(PackageType s: typeList){
                typeMap.put(s.getId(), s.getPackageName());
            }
        }
        return typeMap;
    }

    public Map<Long, String> getSaleMap(){
        List<User> sales = userRepository.findAll();
        Map<Long, String> saleMap = new HashMap<>();
        if(ValidateUtil.isValid(sales)){
            for(User s: sales){
                saleMap.put(s.getId(), s.getName());
            }
        }
        return saleMap;
    }
}
