package cn.palmte.work.service;

import cn.palmte.work.bean.ProjectConfigBean;
import cn.palmte.work.bean.ResponseMsg;
import cn.palmte.work.model.SysConfig;
import cn.palmte.work.model.SysConfigRepository;
import cn.palmte.work.pojo.SysConfigRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class SysConfigService {

    @Autowired
    private SysConfigRepository sysConfigRepository;


    public ResponseMsg saveOrUpdate(String json) {
        JSONObject obj = JSON.parseObject(json);

        double rate = Double.parseDouble(obj.getString("underwrittenTaxRate"));

        if(rate <= 0){
            return ResponseMsg.buildFailedMsg("项目年利率应大于0");
        }

        SysConfig underwrittenTaxRate = sysConfigRepository.findByCodeEquals(SysConfig.KEY_UNDERWRITTENTAXRATE);
        underwrittenTaxRate.setValue(obj.getString("underwrittenTaxRate"));
        underwrittenTaxRate.setUpdateTime(new Date());
        sysConfigRepository.saveAndFlush(underwrittenTaxRate);

        SysConfig projectContributionProfitRateThreshold = sysConfigRepository.findByCodeEquals(SysConfig.KEY_PROJECTCONTRIBUTIONPROFITRATETHRESHOLD);
        projectContributionProfitRateThreshold.setValue(obj.getString("projectContributionProfitRateThreshold"));
        projectContributionProfitRateThreshold.setUpdateTime(new Date());
        sysConfigRepository.saveAndFlush(projectContributionProfitRateThreshold);
        return ResponseMsg.buildSuccessMsg("配置成功");
    }

    public BigDecimal getUnderwrittenTaxRate(){
        return new BigDecimal(sysConfigRepository.findByCodeEquals(SysConfig.KEY_UNDERWRITTENTAXRATE).getValue());
    }
    public BigDecimal getProjectContributionProfitRateThreshold(){
        return new BigDecimal(sysConfigRepository.findByCodeEquals(SysConfig.KEY_PROJECTCONTRIBUTIONPROFITRATETHRESHOLD).getValue());
    }


    public ProjectConfigBean getProjectConfigBeanConfig(){
        ProjectConfigBean projectConfigBean = new ProjectConfigBean();
        projectConfigBean.setUnderwrittenTaxRate(getUnderwrittenTaxRate());
        projectConfigBean.setProjectContributionProfitRateThreshold(getProjectContributionProfitRateThreshold());
        return projectConfigBean;
    }
}
