package com.brilliance.isc.common.warmod.service.impl;

import com.brilliance.isc.bo.Finwar;
import com.brilliance.isc.common.counter.service.CounterService;
import com.brilliance.isc.common.warmod.service.WarmodService;
import com.brilliance.isc.common.warmod.vo.WarmodVo;
import com.brilliance.isc.mda.dao.FinwarMapper;
import com.brilliance.mda.runtime.mda.util.Dates;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;

@Service
public class WarmodServiceImpl implements WarmodService {

    @Autowired
    private CounterService counterService;

    @Autowired
    private FinwarMapper finwarMapper;

    @Override
    public WarmodVo setFinanceTenorCheck(Date opndat, Date matdat, int tenday, String tentyp) {
        WarmodVo warmodVo = new WarmodVo();
        warmodVo.setOpndat(opndat);
        warmodVo.setMatdat(matdat);
        if (tenday > 0) {
            warmodVo.setTenorday(tenday);
        } else {
            warmodVo.setTenorday(0);
        }
        if (!MdaUtils.isEmpty(tentyp)) {
            warmodVo.setTenortyp(tentyp);
        } else {
            warmodVo.setTenortyp("D");
        }
        return warmodVo;
    }

    @Override
    public String checkFinTenor(WarmodVo warmodVo) {
        //argwarflg:X 若为X代表，超过期限
        //超过期限需要在提交是弹窗提示，但需要弹框选择是否需要继续，若继续则存表，在复核交易再次提醒，过不继续，这阻断提交
        String argwarflg = "";
        // 交易无需检查融资期限
        Date begdat = null;
        if (MdaUtils.compareTo(warmodVo.getTenortyp(), "D") == 0) {
            begdat = Dates.add(warmodVo.getOpndat(), -warmodVo.getTenorday());
        } else {
            if (MdaUtils.compareTo(warmodVo.getTenortyp(), "M") == 0) {
                begdat = Dates.add(warmodVo.getOpndat(), Calendar.MONTH, -warmodVo.getTenorday());
            }
        }
        Date tenorMaxDay = Dates.add(begdat, Calendar.MONTH, 6);
        if (Dates.diff(warmodVo.getMatdat(), tenorMaxDay) >= 0) {
            argwarflg = "X";
        }
        return argwarflg;
    }

    @Override
    public void saveWarn(WarmodVo warmodVo, String opt) {
        Finwar finwar = new Finwar();
        finwar.setInr(counterService.dbCounterFormat("FINWAR"));
        if (MdaUtils.compareTo(opt, "USRCON") == 0) {
            finwar.setObjtyp("ORD");
            finwar.setObjinr(warmodVo.getOrdinr());
        } else {
            // SAV
            finwar.setObjtyp("TRN");
            finwar.setObjinr(warmodVo.getTrninr());
        }
        finwar.setWartxt("融资期限超半年，请确认是否完成超权限审批");
        finwarMapper.insert(finwar);
    }
}
