package com.seeyon.apps.src_financing.controller;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.src_financing.dao.IFinancingContractDao;
import com.seeyon.apps.src_financing.util.FormExportUtil;
import com.seeyon.apps.src_financing.util.InterestCalculationUtil;
import com.seeyon.apps.src_financing.util.NumberUtil;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.controller.BaseController;
import com.seeyon.ctp.util.json.JSONUtil;
import com.seeyon.v3x.services.form.FormFactory;
import com.seeyon.v3x.services.form.bean.FormExport;
import com.seeyon.v3x.services.form.bean.SubordinateFormExport;
import com.seeyon.v3x.services.form.bean.ValueExport;
import nc.vo.jcom.lang.StringUtil;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

public class InterestMeasurementController extends BaseController {

    private FormFactory formFactory;

    public FormFactory getFormFactory() {
        if (formFactory == null) {
            formFactory = (FormFactory) AppContext.getBean("formFactory");
        }
        return formFactory;
    }

    public void setFormFactory(FormFactory formFactory) {
        this.formFactory = formFactory;
    }

    private IFinancingContractDao financingContractDao;

    public IFinancingContractDao getLeaseContractDao() {
        if (financingContractDao == null) {
            financingContractDao = (IFinancingContractDao) AppContext.getBean("financingContractDao");
        }
        return financingContractDao;
    }

    public void setFinancingContractDao(IFinancingContractDao financingContractDao) {
        this.financingContractDao = financingContractDao;
    }



        public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws Exception {
            logger.info("进入ajax方法");
            //            设置返回值对象
            Map<String, Object> res = new HashMap<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            InterestCalculationUtil rentCalculationUtil = new InterestCalculationUtil();
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");

            BufferedReader reader = request.getReader();
            String line;
            StringBuilder requestBody = new StringBuilder();
            while((line = reader.readLine())!=null){
                requestBody.append(line);
            }
            String data = requestBody.toString();
            String decodedParam = URLDecoder.decode(data, "UTF-8");
            String[] datas =  decodedParam.split("&");
            JSONObject jsonObject = new JSONObject();
            for(int i = 0 ; i < datas.length ; i ++ ){
                String[] params = datas[i].split("=");
                if(params.length>1){
                    jsonObject.put(params[0],params[1]);
                }
            }
            logger.info("处理参数");
            String interestType = jsonObject.getString("interestType");
            //        获取初次提款时间
            String money = jsonObject.getString("money");
            String[] moneys = money.split(";");
//        转list
            List<String> moneyList = Arrays.asList(moneys);
            Collections.sort(moneyList);
            String[] moenyValue = moneyList.get(0).split("~");
            String moneyDateStr = moenyValue[0];
            //        获取利率初次设置时间
            String interestRate = jsonObject.getString("interestRate");
            String[] interestRates = interestRate.split(";");
            //        转list
            List<String> interestRateList = Arrays.asList(interestRates);
//        list排序
            Collections.sort(interestRateList);
            String[] interestRateValue = interestRateList.get(0).split("~");
            String interestRateDateStr = interestRateValue[0];
//            获取还本金列表参数
            String principal = jsonObject.getString("principal");
            //        根据开始时间和合同年限进行时间拆分
            String startDate = jsonObject.getString("startDate");
            Date date = sdf.parse(startDate);
            //		开始日期
            Calendar start = Calendar.getInstance();
            start.setTime(date);
            //		结束日期
            Calendar end = Calendar.getInstance();
            end.setTime(date);
            String period = jsonObject.getString("period");
            period = period.substring(0,period.length()-1);
            int periodNum = NumberUtil.convertChineseNumberToArabic(period);
            end.add(Calendar.YEAR, periodNum);
            end.add(Calendar.DATE, 1);
            logger.info("设置结束时间");
            //		根据开始结束时间和周期计算时间列表
            String cycle = jsonObject.getString("cycle");
            int cycleNum = rentCalculationUtil.getCycleNum(cycle);
//            查询计划还本金列表中的最后还款日期
            Calendar maxDate =  rentCalculationUtil.getPrincipalMaxDate(principal);
            List<Date> cycleDates = rentCalculationUtil.cycleDates(start,end,cycleNum,maxDate);

//        计算开始时间
            Date lxstartDate = sdf.parse(moneyDateStr);
            //        结算结束时间
            Date lxendDate = cycleDates.get(0);
            if(lxendDate.getTime()<lxstartDate.getTime()){
                System.out.println("时间有误，初次还利息时间不能早于初次提款时间");
                res.put("success", false);
                res.put("name", AppContext.currentUserLoginName());
                res.put("msg", "时间有误，初次还利息时间不能早于初次提款时间");

                render(response, JSONUtil.toJSONString(res));
                return null;
            }
            logger.info("设置利率开始时间");
            //        利率开始时间
            Date llstartDate = sdf.parse(interestRateDateStr);
            if(llstartDate.getTime()>lxstartDate.getTime()){
                System.out.println("时间有误，初次利率设置时间不能晚于初次提款时间");
                res.put("success", false);
                res.put("name", AppContext.currentUserLoginName());
                res.put("s", "时间有误，初次利率设置时间不能晚于初次提款时间");

                render(response, JSONUtil.toJSONString(res));
                return null;
            }
            logger.info("判断是否为农发行规则");

//            数据生成前根据合同编号清楚所有的辅助表信息
                String contractCode =  jsonObject.getString("contractCode");
            if(!StringUtil.isEmpty(contractCode)){
//                删除明细表辅助数据
                int daleteFZFinancingSubnum = getLeaseContractDao().daleteFZFinancingSub(contractCode);
//                删除主表辅助数据
                int daleteFZFinancingnum = getLeaseContractDao().daleteFZFinancing(contractCode);
                if(daleteFZFinancingSubnum!=0 &&daleteFZFinancingnum!=0){
                    System.out.println("存在辅助表数据，删除成功，主表删除"+daleteFZFinancingnum+"条数据，明细表删除"+daleteFZFinancingSubnum+"条数据");
                }else{
                    System.out.println("删除失败，主表"+daleteFZFinancingSubnum+"明细表"+daleteFZFinancingnum+"合同编码"+contractCode);
                }
            }
            logger.info("删除历史生成的数据");
//            创建保存利息明细信息
            List<Map<String,Object>> sublist = new ArrayList<Map<String,Object>>();
//            判断利息测算类型
            String type = "";
            String loanType = jsonObject.getString("loanType");
            if("政府专项债券".equals(loanType)){
                type = "政府专项利息测算";
            }else{

                String[] principals = principal.split(";");
                String str = principals[0].substring(principals[0].length()-2);
                if(!"~0".equals(str)){
                    if("农发行利息测算".equals(interestType)&& interestRates.length!=moneys.length){
                        System.out.println("数据有误，农发行融资利息测算提款明细行数与融资利率明细行数必须相等");
                        res.put("success", false);
                        res.put("name", AppContext.currentUserLoginName());
                        res.put("s", "数据有误，农发行融资利息测算提款明细行数与融资利率明细行数必须相等");

                        render(response, JSONUtil.toJSONString(res));
                        return null;

                    }
                    type = "农发行利息测算";
                }else{
                    type = "银行贷款利息测算";
                }
            }
//            设置更新触发规则
            String updateCode = jsonObject.getString("updateCode");
            int codenum = 0;
            if(!StringUtil.isEmpty(updateCode)){
                String code = updateCode.substring(updateCode.length()-1);
                codenum = Integer.parseInt(code);
                codenum =codenum%10;
                codenum +=1;
            }

//            计算利息信息保存利息明细对象
            sublist = rentCalculationUtil.detailedHandle(jsonObject,type);
            logger.info("生成完成所有利息");
            Map<String,Object> mainmap = new HashMap<String,Object>();
            mainmap.put("合同编号", contractCode);
            mainmap.put("触发文本更新", contractCode+codenum);
            FormExportUtil formExportUtil = new FormExportUtil();
            FormExport formExport = new FormExport();
            List<SubordinateFormExport> subordinateFormExports = formExportUtil.setSubordinateFormValue(sublist);
            List<ValueExport> valueExports = formExportUtil.setFormValue(mainmap);
            formExport.setSubordinateForms(subordinateFormExports);
            formExport.setValues(valueExports);
            logger.info("创建档案");
//            getFormFactory().importBusinessFormData("shenxian", "LXCSMX",
//                    formExport, new String[] {});
//            getFormFactory().importBusinessFormData("admin1", "LXCSMX",
//                    formExport, new String[] {});
            getFormFactory().importBusinessFormData("demo2", "LXCSMX",
                    formExport, new String[] {});
            res.put("success", true);
            res.put("name", AppContext.currentUserLoginName());
            res.put("s", "");
            res.put("num", contractCode+codenum);

            render(response, JSONUtil.toJSONString(res));
        return null;
    }

    /**
     * 给前台渲染json数据
     * @param response
     * @param text
     */
    private void render(HttpServletResponse response, String text) {
        response.setContentType("application/json;charset=UTF-8");
        try {
            response.setContentLength(text.getBytes("UTF-8").length);
            response.getWriter().write(text);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
