package com.sifang.modules.sunshine.SystemSetting.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.platform.fittingManager.dao.PlatformFittingDao;
import com.sifang.modules.platform.fittingManager.entity.PlatformFitting;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.CrmSiteAssetFrozenRecordDao;
import com.sifang.modules.sunshine.SystemSetting.dao.FittingAmountDao;
import com.sifang.modules.sunshine.SystemSetting.dao.SiteInformationDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSite;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSiteAssetFrozenRecord;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.financialManagement.dao.SiteAssetDao;
import com.sifang.modules.sunshine.financialManagement.entity.CrmPlatformCollections;
import com.sifang.modules.sunshine.financialManagement.entity.CrmSiteAsset;
import com.sifang.modules.sunshine.fittingManager.dao.FittingApplyDao;
import com.sifang.modules.sunshine.fittingManager.entity.CrmPlantformFittingApply;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class FittingAmountService extends BaseService {
    @Autowired
    FittingAmountDao fittingAmountDao;
    @Autowired
    SiteAssetDao siteAssetDao;
    @Autowired
    SiteInformationDao siteInformationDao;

    @Autowired
    private FittingApplyDao fittingApplyDao;
    @Autowired
    private PlatformFittingDao fittingDao;

    @Autowired
    CrmSiteAssetFrozenRecordDao siteAssetRecordDao;

    public void getRechargeList(LayuiPage page, Map<String, String> map){
        List<Record> list = fittingAmountDao.getRechargeList(page,map);
        Long count = fittingAmountDao.getRechargeCount(map);
        page.setCount(count);
        page.setData(list);
    }

    /**
     * 保存充值
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Object save(Map<String,String> map){
        Result result = new Result();
        try{
            String siteId = map.get("siteId") !=null ? map.get("siteId"): "";
            String payAmount = map.get("payAmount") !=null ? map.get("payAmount") : "";
            String remarks = map.get("remarks") !=null ? map.get("remarks") : "";
            String type = map.get("type") !=null ? map.get("type") : "";
        /*    CrmSite site = siteInformationDao.get(siteId);
            site.setTotalWallet(site.getTotalWallet().add(new BigDecimal(payAmount)));
            site.setUpdateTime(new Date());
            siteInformationDao.save(site);*/
            CrmPlatformCollections cpfc = new CrmPlatformCollections();
            cpfc.setSiteId(siteId);
            cpfc.setSiteName(getSiteName(siteId));
            cpfc.setPaymentAmount(new BigDecimal(payAmount));
            cpfc.setMarks(remarks);
            cpfc.setPaymentType("3");
            cpfc.setCreateBy(UserUtils.getUser().getId());
            cpfc.setCreateTime(new Date());
            cpfc.setPayTime(new Date());
            cpfc.setStatus("0");
            cpfc.setImgs(map.get("img"));
            cpfc.setNumber("D" + PlantformUtils.getSiteNumber());
            fittingAmountDao.save(cpfc);
            CrmSiteAsset asset= siteAssetDao.getSiteId(siteId);
            if(asset==null){
                asset=new CrmSiteAsset();
                asset.setCreateTime(new Date());
                asset.setSiteId(siteId);
                asset.setTotalAmount(new BigDecimal(payAmount));
                asset.setAvailableAmount(new BigDecimal(payAmount));
                siteAssetDao.save(asset);
            }else{
                asset.setUpdateTime(new Date());
                if("1".equals(type)){
                    asset.setTotalAmount(new BigDecimal(payAmount));
                }else{
                    asset.setTotalAmount(asset.getAvailableAmount().add(new BigDecimal(payAmount)));
                }
                asset.setAvailableAmount(asset.getAvailableAmount().add(new BigDecimal(payAmount)));
                siteAssetDao.save(asset);
            }
                logger.info("保存crm_platform_collections表数据成功："+cpfc+",saveTime:"+ DateUtils.getDateTime());
                result.setCode("200");
        }catch (Exception e){
            result.setCode("205");
            logger.error("返回异常信息:"+e+",saveTime:"+ DateUtils.getDateTime() +" Exception :{}",e);
        }
        return result;
    }

    public String getSiteName(String siteId) {
        Record record = Db.findFirst("select name from crm_site where id = '"+siteId+"'");
        return record.getStr("name");
    }



    public void getCostList(LayuiPage page, Map<String, String> map){
        List<Record> list = fittingAmountDao.getCostList(page,map);
        Long count = fittingAmountDao.getCostCount(map);
        page.setCount(count);
        page.setData(list);
    }




    /**
     * CRM 扣除备件额度--生成哦扣款记录
     */
    public Result siteFittingDeduction(String applyId,String customerId){
        String siteId = siteInformationDao.getSiteIdByCustomerId(customerId);
        if(StringUtil.isBlank(siteId)){
            return Result.fail("202","当前客户没有绑定服务商");
        }
        CrmPlantformFittingApply apply = fittingApplyDao.get(applyId);
        if(apply == null){
            return Result.fail("202","查无备件申请信息");
        }
        PlatformFitting fi = fittingDao.get(apply.getFittingId());
        if(fi == null){
            return Result.fail("202","当前备件信息不存在");
        }
        //判断备件额度是否足够 --- 没绑定服务商才会去判断
        CrmSiteAsset asset = siteAssetDao.getSiteId(siteId);
        if(asset == null){
            return Result.fail("503","没有备件额度!");
        }
        logger.info("备件可使用额度 使用前 AvailableAmount : "+asset.getAvailableAmount() +".UsedAmount :"+asset.getUsedAmount()+" ,备件申请id: " +apply.getId());
        //备件金额
        BigDecimal fittingAmount = apply.getFittingAuditNum().multiply(fi.getSitePrice());
        if(fittingAmount.compareTo(asset.getAvailableAmount()) == 1){
            //备件总金额大于备件可使用额度
            return Result.fail("504","备件额度不足，请联系服务商充值!!");
        }
        asset.setAvailableAmount(asset.getAvailableAmount().subtract(fittingAmount));
        asset.setUsedAmount(asset.getUsedAmount().add(fittingAmount));
        siteAssetDao.save(asset);

        CrmSiteAssetFrozenRecord ass = new CrmSiteAssetFrozenRecord();
        ass.setAmount(fittingAmount);
        ass.setSiteId(siteId);
        ass.setSitePrice(fi.getSitePrice());
        ass.setApplyFittingId(apply.getId());
        ass.setFittingId(apply.getFittingId());
        siteAssetRecordDao.save(ass);

        return Result.ok();
    }

    /**
     * CRM单独 扣 备件额度 ---  如客户间转款转出账户为备件账户
     * @param customerId  扣款的客户id  --- 查找对应的服务商信息
     * @param amount  扣款备件额度
    */
    public Result siteDeduction(String customerId,String amount){
        String siteId = siteInformationDao.getSiteIdByCustomerId(customerId);
        if(StringUtil.isBlank(siteId)){
            return Result.fail("203","当前客户没有绑定服务商");
        }

        //判断备件额度是否足够 --- 没绑定服务商才会去判断
        CrmSiteAsset asset = siteAssetDao.getSiteId(siteId);
        if(asset == null){
            return Result.fail("503","没有备件额度!");
        }
        logger.info("备件可使用额度 使用前 AvailableAmount : "+asset.getAvailableAmount() +".UsedAmount :"+asset.getUsedAmount());

        logger.info("CRM 扣除备件账户金额 customerId ： {} ，扣除金额 为 ：{}",customerId,amount);
        //备件金额
        BigDecimal fittingAmount = new BigDecimal(amount);
        if(fittingAmount.compareTo(asset.getAvailableAmount()) == 1){
            //备件总金额大于备件可使用额度
            return Result.fail("504","备件额度不足，请联系服务商充值!!");
        }
        asset.setAvailableAmount(asset.getAvailableAmount().subtract(fittingAmount));
        asset.setUsedAmount(asset.getUsedAmount().add(fittingAmount));
        siteAssetDao.save(asset);
        logger.info("备件可使用额度 扣除后 AvailableAmount : "+asset.getAvailableAmount() +".UsedAmount :"+asset.getUsedAmount());

        BigDecimal price = new BigDecimal("0.00");
        CrmSiteAssetFrozenRecord ass = new CrmSiteAssetFrozenRecord();
        ass.setAmount(fittingAmount);
        ass.setSiteId(siteId);
        ass.setSitePrice(price);
        ass.setApplyFittingId("");
        ass.setFittingId("");
        siteAssetRecordDao.save(ass);

        return Result.ok();
    }


}
