package com.seeyon.apps.src_ydctleasebill.controller;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.common.config.ICstConfigApi;
import com.seeyon.apps.common.plugin.vo.ConfigVo;
import com.seeyon.apps.src_financing.util.InterestCalculationUtil;
import com.seeyon.apps.src_ydctleasebill.constant.YdctLeaseBillConstant;
import com.seeyon.apps.src_ydctleasebill.dao.ILeaseBillDao;
import com.seeyon.apps.src_ydctleasebill.util.DateUtil;
import com.seeyon.apps.src_ydctleasebill.util.FormExportUtil;
import com.seeyon.apps.src_ydctleasebill.util.LeaseBillUtil;
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.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 YdctLeaseBillController extends BaseController {

    private static Log log = Log.get(YdctLeaseBillController.class);
    protected ICstConfigApi cstConfigApi = (ICstConfigApi) AppContext.getBean("cstConfigApi");

    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 ILeaseBillDao leaseBillDao;

    public void setLeaseBillDao(ILeaseBillDao leaseBillDao) {
        this.leaseBillDao = leaseBillDao;
    }
    public ILeaseBillDao getLeaseBillDao() {
        if (leaseBillDao == null) {
            leaseBillDao = (ILeaseBillDao) AppContext.getBean("leaseBillDao");
        }
        return leaseBillDao;
    }



    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("进入ajax方法");
        ConfigVo configVo = getYdctLeaseBillConfig();
        DateUtil dateUtil = new DateUtil();
        LeaseBillUtil leaseBillUtil = new LeaseBillUtil();
        FormExportUtil formExportUtil = new FormExportUtil();
        //            设置返回值对象
        Map<String, Object> res = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmsssss");
        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]);
            }else{
                if(params[0].equals("bdid")){
                    jsonObject.put("bdid","0");
                }
            }
        }
        try {
            String bdidValue = jsonObject.getString("bdid");
            log.info("当前账单编号为："+bdidValue);
            if("0".equals(bdidValue)){
                Date formDate = new Date();
                String formId = simpleDateFormat.format(formDate);
//                账单编号
                bdidValue = formId;
//                formDataVo.getNewFieldDataMap().put("账单编号", formId);
            }else {
                List<String> ids = leaseBillDao.leaseBillByCode(bdidValue);
                for (int i = 0; i < ids.size(); i++) {
//            	删除明细账单
                    leaseBillDao.deleteBillsByBillId(ids.get(i));
//            	删除主表数据
                    leaseBillDao.deleteBillById(ids.get(i));
                }
            }

            String code = bdidValue;
//            开始日期
            String startDateStr = jsonObject.getString("startDate");
            Date startDate = sdf.parse(startDateStr);
//            结束日期
            String endDateStr = jsonObject.getString("endDate");
            Date endDate = sdf.parse(endDateStr);
//            设置面积
            String jifeifs = jsonObject.getString("jifeifs");
//        		设置合同开始日期
            Calendar startTime = Calendar.getInstance();
            startTime.setTime(startDate);
//				判断合同开始时间是否为月底
            boolean isMaxDay = false;
            int currentDay = startTime.get(Calendar.DAY_OF_MONTH);
            int maxDay = startTime.getActualMaximum(Calendar.DAY_OF_MONTH);
            if(currentDay==maxDay){
                isMaxDay = true;
            }
//        		设置合同结束日期
            Calendar endTime = Calendar.getInstance();
            endTime.setTime(endDate);
            endTime.add(Calendar.DAY_OF_MONTH, 1);

//            根据缴费方式设置开始结束时间
            String jiaofeifs = jsonObject.getString("jiaofeifs");
            int jfzqNum = dateUtil.getCycleNum(jiaofeifs);

            FormExport formExport = new FormExport();
//        		租金
            List<Map<String,String>> rents = new ArrayList<Map<String,String>>();
            if(jfzqNum==12){
                String njiaofeifs = jsonObject.getString("njiaofeifs");
                if(StringUtil.isEmpty(njiaofeifs)){
                    res.put("success", true);
                    res.put("name", AppContext.currentUserLoginName());
                    res.put("s", "请选择年缴费计算方式");
                    res.put("num", "");
                    render(response, JSONUtil.toJSONString(res));
                    return null;
                }else{
                    if(njiaofeifs.contains("一")){
//                        采用方式一
                        rents = leaseBillUtil.getLeaseBillYers1(startTime,endTime,isMaxDay,jfzqNum,jsonObject,jifeifs);
                    }else if(njiaofeifs.contains("二")){
//                        采用方式二
                        rents = leaseBillUtil.getLeaseBillYers2(startTime,endTime,isMaxDay,jfzqNum,jsonObject,jifeifs);
                    }
                }
            }else{
//                根据标准方法生成
                rents = leaseBillUtil.getLeaseBill(startTime,endTime,isMaxDay,jfzqNum,jsonObject,jifeifs);
            }
            log.info("创建档案");
            List<SubordinateFormExport> subordinateFormExports = formExportUtil.setSubordinateFormValue(rents);
            Map<String , String > billMap = new HashMap<String, String>();
            billMap.put("账单编号", code);
            List<ValueExport> valueExports = formExportUtil.setFormValue(billMap);
            formExport.setSubordinateForms(subordinateFormExports);
            formExport.setValues(valueExports);
            String loginName = configVo.getParamVal(YdctLeaseBillConstant.loginName.name());
            getFormFactory().importBusinessFormData(loginName, "ZJZDMX",
                    formExport, new String[] {});
            res.put("success", true);
            res.put("name", AppContext.currentUserLoginName());
            res.put("s", "");
            res.put("num", code);
        }catch (Exception e){
            e.printStackTrace();
        }
        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();
        }
    }

    public ConfigVo getYdctLeaseBillConfig() {
        return cstConfigApi.getConfig(getPluginId());
    }

    public String getPluginId() {
        return YdctLeaseBillConstant.getPluginId();
    }
}
