package com.bcxin.ins.supply.business.impl;

import com.bcxin.ins.service.common.ComAreaCodeAPIService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.service.product.InsProductRuleXWCKAPIService;
import com.bcxin.ins.entity.common.ComAreaCode;
import com.bcxin.ins.entity.common.ComRegion;
import com.bcxin.ins.supply.SupplyType;
import com.bcxin.ins.supply.business.BizInsureService;
import com.bcxin.ins.supply.business.BizStrategy;
import com.bcxin.ins.supply.business.entity.InsureCommonView;
import com.bcxin.ins.util.DateUtil;
import com.bcxin.ins.util.RegionUtils;
import com.bcxin.ins.utils.FreemarkerUtil;
import com.bcxin.ins.vo.*;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 太保保险
 * @author hzp
 * @date 2018/06/12
 */
@Component
@SupplyType(type = SupplyType.SupplyTypeEnum.TAI_BAO)
public class BizStrategyTaiBao implements BizStrategy {

    public BizStrategyTaiBao(){
        System.out.print("BusinessStrategyTaiBao");
    }
    @Override
    public ResultDto calcInsuranceEndDate(String startTime, Integer limitDays) {
        try {
            //1.计算一年后的时间
            Date planTimeNextYear = DateUtil.convertStringToDate(DateUtil.dateAdd(DateUtil.DATATYPE_YEAR, startTime, 1));

            //2.计算投标日期+投标有效期+28天后的日期
            int limitFinalDays = limitDays + 28;
            //不加28天
            Date planTimeWithLimit = DateUtil.convertStringToDate(DateUtil.dateAdd(DateUtil.DATATYPE_DAY,startTime,limitDays));
            //加28天
            Date planTimeWithFinalLimit = DateUtil.convertStringToDate(DateUtil.dateAdd(3,startTime,limitFinalDays));

            //3.比较planTimeWithLimit的日期是否大于planTime，是就超出一年期限
            if (DateUtil.calculateTwoDateDvalue(planTimeNextYear, planTimeWithLimit) < 0) {
                return new ResultDto("保险期间大于一年，请重新设置投标有效期！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }

            //如果按+28天的日期来比较超出1年的限制就直接按一年算
            if (DateUtil.calculateTwoDateDvalue(planTimeNextYear, planTimeWithFinalLimit) < 0) {
                planTimeWithFinalLimit = DateUtil.convertStringToDate(DateUtil.dateAdd(DateUtil.DATATYPE_DAY, DateUtil.dateAdd(DateUtil.DATATYPE_YEAR, startTime, 1), -1));
            }

            if (planTimeWithFinalLimit != null) {
                String plannedEnd = DateUtil.convertDateToString(planTimeWithFinalLimit, DateUtil.FORMAT2);
                return new ResultDto(plannedEnd, ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            } else {
                return new ResultDto("获取失效日期失败", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ResultDto("", "301", ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
    }

    @Autowired
    private PolicyService policyService;
    @Autowired
    private ComAreaCodeAPIService comAreaCodeAPIService;
    @Autowired
    private InsProductRuleXWCKAPIService insProductRuleXWCKAPIService;
    @Autowired
    private BizInsureService bizInsureService;

    @Override
    public InsureCommonView getInsureCommonView(Map<String, Object> map) {
        String transType=map.get("transType").toString();
        String tb_code="";
        Long orderId=Long.parseLong(map.get("orderId").toString());
        OrderFormVo order = policyService.accordingToOrderIDToGetPolicyDto(orderId);
        MicroExportVo microExportVo = policyService.accordingToOrderIDToGetMicroExportVo(orderId);

        // 市级代码
        String cityCode = microExportVo.getRoleSubjectList().get(0).getReg_city();
        // 省级代码
        String provinceCode = microExportVo.getRoleSubjectList().get(0).getReg_province();
        // 产品id
        String productId=order.getProduct_oid();
        RuleXWCKVo ruleXWCKVo = insProductRuleXWCKAPIService.getRuleXWCKVoByProductIDAndCity(productId, cityCode);
        ComRegion regionCity = RegionUtils.getComRegionByCode(cityCode);
        //先匹配市级
        String val1_ = regionCity.getNamed().substring(0, regionCity.getNamed().length()-1);
        List<ComAreaCode> tbsList = comAreaCodeAPIService.findComAreaCodeByCode("","",val1_);
        ComAreaCode tb = null;
        if(tbsList.size()>0){
            tb = tbsList.get(0);
        }
        //如果市级未匹配到就匹配省级
        if(tb == null){
            ComRegion regionPro = RegionUtils.getComRegionByCode(provinceCode);
            String val2_ = regionPro.getNamed().substring(0, regionPro.getNamed().length()-1);
            List<ComAreaCode> tbpList = comAreaCodeAPIService.findComAreaCodeByCode("","",val2_);
            if(tbpList.size()>0){
                tb = tbpList.get(0);
            }
        }
        tb_code = tb.getCodes();

        Map<String,Object> mapData=new HashMap<String,Object>();
        mapData.put("order",order);
        mapData.put("policy",microExportVo);
        mapData.put("ruleXWCKVo",ruleXWCKVo);
        mapData.put("applicants",microExportVo.getRoleSubjectList().get(0));
        mapData.put("transType",transType);
        mapData.put("tb_code",tb_code);
        mapData.put("planDate",DateUtil.getThisYearLastDay());
        mapData.put("planFee",100);

        InsureCommonView insureCommonView=bizInsureService.getInsureCommonView(null,orderId);

        try {
            String templateName = SupplyType.SupplyTypeEnum.TAI_BAO.getKey()+"_XWCK_120043.ftl";
            String requestXML = FreemarkerUtil.getInstance().transferMapToString(templateName,mapData);
            System.out.println(requestXML);
            FreemarkerUtil.getInstance().transferMapToFile( mapData,templateName,"D:\\template\\xml\\XWCK_120043_result.xml");
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 生成请求报文消息
     * @param map
     * @param templateName 报文模板
     * @return
     */
    @Override
    public String createRequestMessage(Map<String,Object> map,String templateName){
        try {
//        String templateName = SupplyType.SupplyTypeEnum.TAI_BAO.getKey()+"_XWCK_120043.ftl";
            templateName = SupplyType.SupplyTypeEnum.TAI_BAO.getKey() + "_" + templateName + ".ftl";
            String transType = map.get("transType").toString();
            String tb_code = "";
            Long orderId = Long.parseLong(map.get("orderId").toString());
            InsureCommonView insureCommonView = bizInsureService.getInsureCommonView(null, orderId);

            Map<String, Object> data = Maps.newHashMap();
            data.put("order", insureCommonView.getOrderView());
            data.put("policy", insureCommonView.getPolicyHolderView());
            data.put("transType", transType);
            data.put("tb_code", tb_code);
            data.put("planDate", DateUtil.getThisYearLastDay());
            data.put("planFee", 100);

            String requestXML = FreemarkerUtil.getInstance().transferMapToString(templateName, data);
            FreemarkerUtil.getInstance().transferMapToFile( data,templateName,"D:\\template\\xml\\XWCK_120043_result1.xml");
            return requestXML;//XMLUtil.formatXML(requestXML);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("生成报文失败");
        }
    }
}
