package cn.com.countrygarden.bi.main.controller.financial;

import java.rmi.RemoteException;
import java.util.*;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.financial.*;
import cn.com.countrygarden.bi.main.model.twerp.ErpNcData;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.UserRoleService;
import cn.com.countrygarden.bi.main.service.financial.*;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbHsprCommunityService;
import cn.com.countrygarden.bi.main.util.RedisUtils;
import cn.com.countrygarden.bi.main.util.StringToMapUtil;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import nc.vo.pub.BusinessException.BusinessException;
import nc.ws.intf.IWSBIGetNCWYData.IWSBIGetNCWYDataPortTypeProxy;
import nc.ws.vo.KMFZYEVO.KMFZYEVO;
import nc.ws.vo.QueryVO.QueryVO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.countrygarden.bi.main.service.financial.Impl.OrgDeptService;
import cn.com.countrygarden.bi.main.util.StringToMapUtil;

import javax.servlet.http.HttpServletResponse;

@Controller("FinanceController")
@RequestMapping("/FinanceController")
public class FinanceController {
    @Autowired
    private BaseDocNamesService basedocnamesservice;

    @Autowired
    private OrgFinanceorgService orgfinanceorgservice;

    @Autowired
    private F050Service f050service;

    @Autowired
    private F051Service f051service;

    @Autowired
    private F074Service f074Service;

    @Autowired
    private OrgAccountingBookService orgaccountingbookservice;

    @Autowired
    private TbBudgetSubService TbBudgetSubService;

    @Autowired
    private F045Service F045Service;

    @Autowired
    private F046Service F046Service;

    @Autowired
    private F047Service F047Service;

    @Autowired
    private F224Service F224Service;

    @Autowired
    private F203Service F203Service;

    @Autowired
    private F204Service F204Service;

    @Autowired
    private F205Service F205Service;

    @Autowired
    private OrgBosmemberService OrgBosmemberService;

    @Autowired
    private F206Service F206Service;

    @Autowired
    private BGY215Service BGY215Service;

    @Autowired
    private OrgDeptService OrgDeptService;

    @Autowired
    private BdAccasoaService BdAccasoaService;

    @Autowired
    private SubbalanceService SubbalanceService;

    @Autowired
    private FeeadjdataService FeeadjdataService;

    @Autowired
    private BudgetdataService BudgetdataService;

    @Autowired
    private FinancialService financialService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private TbHsprCommunityService tbHsprCommunityService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @ResponseBody
    @RequestMapping(value = "/Finance", method = {RequestMethod.POST, RequestMethod.GET})
    public void Finance(@RequestParam(value = "year") String year, @RequestParam(value = "month") String month) {
        IWSBIGetNCWYDataPortTypeProxy IPTP = new IWSBIGetNCWYDataPortTypeProxy();
        List<Basedocnames> bsedocnames = new ArrayList<Basedocnames>();
        List<org_financeorg> org_financeorg = new ArrayList<org_financeorg>();
        List<F050> f050 = new ArrayList<F050>();
        List<F051> f051 = new ArrayList<F051>();
        List<F074> f074 = new ArrayList<F074>();
        List<OrgAccountingBook> org_accountingbook = new ArrayList<OrgAccountingBook>();
        List<TbBudgetSub> tb_budgetsub = new ArrayList<TbBudgetSub>();
        List<F045> f045 = new ArrayList<F045>();
        List<F046> f046 = new ArrayList<F046>();
        List<F047> f047 = new ArrayList<F047>();
        List<F224> f224 = new ArrayList<F224>();
        List<F203> f203 = new ArrayList<F203>();
        List<F204> f204 = new ArrayList<F204>();
        List<org_bosmember> org_bosmember = new ArrayList<org_bosmember>();
        List<F205> f205 = new ArrayList<F205>();
        List<BGY216> bgy216 = new ArrayList<BGY216>();
        List<F206> f206 = new ArrayList<F206>();
        List<BGY215> bgy215 = new ArrayList<BGY215>();
        List<org_dept> org_dept = new ArrayList<org_dept>();
        List<bd_accasoa> bd_accasoa = new ArrayList<bd_accasoa>();
        List<Subbalance> subbalance = new ArrayList<Subbalance>();
        List<Feeadjdata> feeadjdata = new ArrayList<Feeadjdata>();
        List<Budgetdata> budgetdata = new ArrayList<Budgetdata>();
        try {
				/*//获取档案编码及名称
				 String subbalance = IPTP.getBaseDocNames();
	    		System.out.println(subbalance);
	    		Map<String,String> map = StringToMapUtil.ToMap(subbalance);
	    		Iterator iter = map.entrySet().iterator(); 
	    		 Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); */
            /*while (it.hasNext()) { */
	    			/*Map.Entry<String, String> entry =  it.next(); 
	    		    String keyo =  entry.getKey();	
	    		    String valueo = entry.getValue(); 
	    		    Basedocnames bdc = new Basedocnames();    		   
	    		    bdc.setKeyo(keyo);
	    		    bdc.setValueo(valueo);			
	    		    bsedocnames.add(bdc);*/
            /*  System.out.println(keyo);    */
            //获取档案数据
            //注意这里  判断属于哪个档案额编码  对应的则导入库表
            String keyo = "org_accountingbook";
            if (keyo.equals("org_financeorg")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                ArrayList<String> list = new ArrayList<String>();
	    		   /*int a = strarray.length;
	    		   System.out.println(a);*/
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String pk_financeorg = map1.get("pk_financeorg");
                    String pk_fatherorg = map1.get("pk_fatherorg");
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    org_financeorg org = new org_financeorg();
                    org.setPk_financeorg(pk_financeorg);
                    org.setPk_fatherorg(pk_fatherorg);
                    org.setName(name);
                    org.setCodo(codo);
                    org_financeorg.add(org);
                    list.add(codo);

                }
                /*orgfinanceorgservice.insertOrUpdate(org_financeorg);*/
                String[] bookCodes = new String[list.size()];
                list.toArray(bookCodes);
                QueryVO qv = new QueryVO();
                qv.setBookCodes(bookCodes);
                //后面接口月份需要为单数，所以这里加了判断
                if (month.length() == 1) {
                    String mon = "0" + month;
                    qv.setMonth(mon);
                } else {
                    qv.setMonth(month);
                }
                qv.setYear(year);
                String su = null;
                try {
                    su = IPTP.getFYTZ(qv);
                } catch (BusinessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (su == null) {
                    System.out.println("我是空值");
                } else {
                    String newsu = su.substring(1, su.length() - 1);
                    String[] str = newsu.split("\\},");
                    for (int i = 0; i < str.length; i++) {
                        String newstrarray = str[i] + "}";
                        System.out.println(str);
                        Map<String, String> map = StringToMapUtil.ToMap(newstrarray);
                        Feeadjdata fd = new Feeadjdata();
                        String assume_amoun = map.get("assume_amount");
                        fd.setAssume_amount(assume_amoun);
                        String objname = map.get("objname");
                        fd.setObjname(objname);
                        String jylb_name = map.get("jylb_name");
                        fd.setJylb_name(jylb_name);
                        String dept_name = map.get("dept_name");
                        fd.setDept_name(dept_name);
                        String org_name = map.get("org_name");
                        fd.setOrg_name(org_name);
                        String ysdate = map.get("ysdate");
                        fd.setYsdate(ysdate);
                        String tzlx_name = map.get("tzlx_name");
                        fd.setTzlx_name(tzlx_name);
                        String memo = map.get("memo");
                        fd.setMemo(memo);
                        String bbje = map.get("bbje");
                        fd.setBbje(bbje);
                        feeadjdata.add(fd);
                    }
                }
                FeeadjdataService.insertOrUpdate(feeadjdata);
                orgfinanceorgservice.insertOrUpdate(org_financeorg);
            } else if (keyo.equals("F050")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                int a = strarray.length;
                System.out.println(a);
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    F050 f5 = new F050();
                    f5.setName(name);
                    f5.setCodo(codo);
                    f050.add(f5);
                }
                int b = f050.size();
                System.out.println(b);
                f050service.insertOrUpdate(f050);
            } else if (keyo.equals("F051")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    F051 f51 = new F051();
                    f51.setName(name);
                    f51.setCodo(codo);
                    f051.add(f51);
                }
                f051service.insertOrUpdate(f051);
            } else if (keyo.equals("F074")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    F074 f74 = new F074();
                    f74.setName(name);
                    f74.setCodo(codo);
                    f074.add(f74);
                }
                f074Service.insertOrUpdate(f074);
            } else if (keyo.equals("org_accountingbook")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                ArrayList<String> list = new ArrayList<String>();
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String pk_org = map1.get("pk_org");
                    String pk_fatherorg = map1.get("pk_fatherorg");
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    OrgAccountingBook orgb = new OrgAccountingBook();
                    orgb.setPk_org(pk_org);
                    orgb.setPk_fatherorg(pk_fatherorg);
                    orgb.setName(name);
                    orgb.setCodo(codo);
                    org_accountingbook.add(orgb);
                    //（一）获取科目辅助余额
                    list.add(codo);
                }
                /*orgaccountingbookservice.insertOrUpdate(org_accountingbook);*/
                ////（一）获取科目辅助余额
                String[] bookCodes = new String[list.size()];
                list.toArray(bookCodes);
                QueryVO qv = new QueryVO();
                qv.setBookCodes(bookCodes);
                //后面接口月份需要为单数，所以这里加了判断
                if (month.length() == 1) {
                    String mon = "0" + month;
                    qv.setMonth(mon);
                } else {
                    qv.setMonth(month);
                }
                qv.setYear(year);
                KMFZYEVO[] a = null;
                try {
                    a = IPTP.getKMFZYE(qv);
                } catch (BusinessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (a == null) {
                    System.out.println("我是空值");
                } else {
//                    for (int i = 0; i < a.length; i++) {
//                        Subbalance sb = new Subbalance();
//                        String adjustperiod = a[i].getAdjustperiod();
//                        sb.setAdjustperiod(adjustperiod);
//                        String assid = a[i].getAssid();
//                        sb.setAssid(assid);
//                        String assValue = a[i].getAssValue();
//                        sb.setAssValue(assValue);
//                        String b_orient = a[i].getB_orient();
//                        sb.setB_orient(b_orient);
//                        String begin_amou = a[i].getBegin_amoumt();
//                        sb.setBegin_amou(begin_amou);
//                        String creditamount = a[i].getCreditamount();
//                        sb.setCreditamount(creditamount);
//                        String debitamount = a[i].getDebitamount();
//                        sb.setDebitamount(debitamount);
//                        String sum_credit = a[i].getSum_credit();
//                        sb.setSum_credit(sum_credit);
//                        String sum_debit = a[i].getSum_debit();
//                        sb.setSum_debit(sum_debit);
//                        String end_amoumt = a[i].getEnd_amoumt();
//                        sb.setEnd_amoumt(end_amoumt);
//                        String e_orient = a[i].getE_orient();
//                        sb.setE_orient(e_orient);
//                        String period = a[i].getPeriod();
//                        sb.setPeriod(period);
//                        String pk_accasoa = a[i].getPk_accasoa();
//                        sb.setPk_accasoa(pk_accasoa);
//                        String accasoa_nam = a[i].getAccasoa_name();
//                        sb.setAccasoa_nam(accasoa_nam);
//                        String pk_accountin = a[i].getPk_accountingbook();
//                        sb.setPk_accountin(pk_accountin);
//                        String accountingbookName = a[i].getAccountingbookName();
//                        sb.setAccountingbookName(accountingbookName);
//                        String accountingbookCode = a[i].getAccountingbookCode();
//                        sb.setAccountingbookCode(accountingbookCode);
//                        String year1 = a[i].getYear();
//                        sb.setYear(year1);
//                        subbalance.add(sb);
//                    }
//                    SubbalanceService.insertOrUpdate(subbalance);
                }
            } else if (keyo.equals("tb_budgetsub")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String objname = map1.get("objname");
                    String pk_obj = map1.get("pk_obj");
                    String objcode = map1.get("objcode");
                    String createddate = map1.get("createddate");
                    String pk_parent = map1.get("pk_parent");
                    TbBudgetSub tbs = new TbBudgetSub();
                    tbs.setObjname(objname);
                    tbs.setPk_obj(pk_obj);
                    tbs.setObjcode(objcode);
                    tbs.setCreateddate(createddate);
                    tbs.setPk_parent(pk_parent);
                    tb_budgetsub.add(tbs);
                }
                TbBudgetSubService.insertOrUpdate(tb_budgetsub);
            } else if (keyo.equals("F045")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    F045 f45 = new F045();
                    f45.setName(name);
                    f45.setCodo(codo);
                    f045.add(f45);
                }
                F045Service.insertOrUpdate(f045);
            } else if (keyo.equals("F046")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    F046 f46 = new F046();
                    f46.setName(name);
                    f46.setCodo(codo);
                    f046.add(f46);
                }
                F046Service.insertOrUpdate(f046);
            } else if (keyo.equals("F047")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    F047 f47 = new F047();
                    f47.setName(name);
                    f47.setCodo(codo);
                    f047.add(f47);
                }
                F047Service.insertOrUpdate(f047);
            } else if (keyo.equals("F224")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    F224 f24 = new F224();
                    f24.setName(name);
                    f24.setCodo(codo);
                    f224.add(f24);
                }
                F224Service.insertOrUpdate(f224);
            } else if (keyo.equals("F203")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    F203 f03 = new F203();
                    f03.setName(name);
                    f03.setCodo(codo);
                    f203.add(f03);
                }
                F203Service.insertOrUpdate(f203);
            } else if (keyo.equals("F204")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    F204 f04 = new F204();
                    f04.setName(name);
                    f04.setCodo(codo);
                    f204.add(f04);
                }
                F204Service.insertOrUpdate(f204);
            } else if (keyo.equals("org_bosmember")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                ArrayList<String> list = new ArrayList<String>();
		    		    /*int a = strarray.length;
		    		    System.out.println(a);	*/
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String father_code = map1.get("father_code");
                    String isbudge = map1.get("isbudge");
                    String curr_name = map1.get("curr_name");
                    String balanceorg = map1.get("balanceorg");
                    String virtualorg = map1.get("virtualorg");
                    String curr_code = map1.get("curr_code");
                    String pk_entityorg = map1.get("pk_entityorg");
                    String father_name = map1.get("father_name");
                    org_bosmember orgb = new org_bosmember();
                    orgb.setFather_code(father_code);
                    orgb.setIsbudge(isbudge);
                    orgb.setCurr_name(curr_name);
                    orgb.setBalanceorg(balanceorg);
                    orgb.setVirtualorg(virtualorg);
                    orgb.setCurr_code(curr_code);
                    orgb.setPk_entityorg(pk_entityorg);
                    orgb.setFather_name(father_name);
                    org_bosmember.add(orgb);
                    list.add(curr_code);
		            		/*orgb=null;
		            		map1=null;
		            		System.gc();*/
                }
                String[] bookCodes = new String[list.size()];
                list.toArray(bookCodes);
                for (int j = 0; j < bookCodes.length; j++) {
                    String[] bookCode = new String[]{bookCodes[j]};
                    QueryVO qv = new QueryVO();
                    qv.setBookCodes(bookCode);
                    //后面接口月份需要为单数，所以这里加了判断
                    qv.setMonth(month);
                    qv.setYear(year);
                    String su = null;
                    String nsu = null;
                    try {
                        su = IPTP.getYSBZ(qv);
                        nsu = su.substring(1, su.length() - 1);
                    } catch (BusinessException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (nsu.equals("")) {
                        System.out.println("我是空值");
                    } else {
                        String newsu = su.substring(1, su.length() - 1);
                        String[] str = newsu.split("\\},");
                        for (int i = 0; i < str.length; i++) {
                            String newstrarray = str[i] + "}";
                            /*System.out.println(str);*/
                            Map<String, String> map = StringToMapUtil.ToMap(newstrarray);
                            Budgetdata bd = new Budgetdata();
                            String mont = map.get("month");
                            bd.setMonth(mont);
                            String subject_code = map.get("subject_code");
                            bd.setSubject_code(subject_code);
                            String subject_name = map.get("subject_name");
                            bd.setSubject_name(subject_name);
                            String bus_name = map.get("bus_name");
                            bd.setBus_name(bus_name);
                            String pk_mvtype = map.get("pk_mvtype");
                            bd.setPk_mvtype(pk_mvtype);
                            String org_name = map.get("org_name");
                            bd.setOrg_name(org_name);
                            String pk_tb_wy01 = map.get("pk_tb_wy01");
                            bd.setPk_tb_wy01(pk_tb_wy01);
                            String op_type = map.get("op_type");
                            bd.setOp_type(op_type);
                            String op_code = map.get("op_code");
                            bd.setOp_code(op_code);
                            String quarter = map.get("quarter");
                            bd.setQuarter(quarter);
                            String value = map.get("value");
                            bd.setValue(value);
                            String yearo = map.get("year");
                            bd.setYear(yearo);
                            String status2 = map.get("status2");
                            bd.setStatus2(status2);
                            String status3 = map.get("status3");
                            bd.setStatus3(status3);
                            budgetdata.add(bd);
                            map = null;
                            bd = null;
                            System.gc();
                        }
                    }
                    qv = null;
                    su = null;
                    nsu = null;
                    bookCode = null;
                    System.gc();
                }
                BudgetdataService.insertOrUpdate(budgetdata);
                /*OrgBosmemberService.insertOrUpdate(org_bosmember);*/
            } else if (keyo.equals("F205")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    F205 f05 = new F205();
                    f05.setName(name);
                    f05.setCodo(codo);
                    f205.add(f05);
                }
                F205Service.insertOrUpdate(f205);
            } else if (keyo.equals("BGY216")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                System.out.println("我暂时没有数据");
		    		   /* String newdangandata = dangandata.substring(1,dangandata.length()-1);
		    		    String [] strarray = newdangandata.split("\\},");
		    		    for(int i=0;i<strarray.length;i++){
		            		String newstrarray =strarray[i]+"}";
		            		Map<String,String> map1 = StringToMapUtil.ToMap(newstrarray);
		            		String pk_org= map1.get("pk_org");
		            		String pk_fatherorg= map1.get("pk_fatherorg");
		            		String name= map1.get("name");
		            		String codo= map1.get("code");
		            		org_financeorg org = new org_financeorg();
		            		org.setPk_org(pk_org);
		            		org.setPk_fatherorg(pk_fatherorg);
		            		org.setName(name);
		            		org.setCodo(codo);
		            		org_financeorg.add(org);*/

            } else if (keyo.equals("F206")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    F206 f06 = new F206();
                    f06.setName(name);
                    f06.setCodo(codo);
                    f206.add(f06);
                }
                F206Service.insertOrUpdate(f206);
            } else if (keyo.equals("BGY215")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    BGY215 b215 = new BGY215();
                    b215.setName(name);
                    b215.setCodo(codo);
                    bgy215.add(b215);
                }
                BGY215Service.insertOrUpdate(bgy215);
            } else if (keyo.equals("org_dept")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String pk_org = map1.get("pk_org");
                    String pk_fatherorg = map1.get("pk_fatherorg");
                    String org_name = map1.get("org_name");
                    String pk_dept = map1.get("pk_dept");
                    String name = map1.get("name");
                    String codo = map1.get("code");
                    org_dept orgd = new org_dept();
                    orgd.setPk_org(pk_org);
                    orgd.setPk_fatherorg(pk_fatherorg);
                    orgd.setOrg_name(org_name);
                    orgd.setPk_dept(pk_dept);
                    orgd.setName(name);
                    orgd.setCodo(codo);
                    org_dept.add(orgd);
                }
                OrgDeptService.insertOrUpdate(org_dept);
            } else if (keyo.equals("bd_accasoa")) {
                String dangandata = IPTP.getBaseDoc(keyo);
                String newdangandata = dangandata.substring(1, dangandata.length() - 1);
                String[] strarray = newdangandata.split("\\},");
                for (int i = 0; i < strarray.length; i++) {
                    String newstrarray = strarray[i] + "}";
                    Map<String, String> map1 = StringToMapUtil.ToMap(newstrarray);
                    String type_name = map1.get("type_name");
                    String accassitem = map1.get("accassitem");
                    String pk_account = map1.get("pk_account");
                    String name = map1.get("name");
                    String pid = map1.get("pid");
                    String cashtype = map1.get("cashtype");
                    String code = map1.get("code");
                    String balanorient = map1.get("balanorient");
                    bd_accasoa bdoa = new bd_accasoa();
                    bdoa.setType_name(type_name);
                    bdoa.setAccassitem(accassitem);
                    bdoa.setPk_account(pk_account);
                    bdoa.setName(name);
                    bdoa.setPid(pid);
                    bdoa.setCashtype(cashtype);
                    bdoa.setCodo(code);
                    bdoa.setBalanorient(balanorient);
                    bd_accasoa.add(bdoa);
                }
                BdAccasoaService.insertOrUpdate(bd_accasoa);
            }
            System.out.println("===================结束导入===================");
            /*}*/
            /*basedocnamesservice.insertOrUpdate(bsedocnames);*/
        } catch (BusinessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @ResponseBody
    @RequestMapping(value = "/newFinance", method = {RequestMethod.POST, RequestMethod.GET})
    public void newFinance(@RequestParam(value = "year") String year, @RequestParam(value = "month") String month) {
        IWSBIGetNCWYDataPortTypeProxy IPTP = new IWSBIGetNCWYDataPortTypeProxy();
        List<Basedocnames> basedocnames = new ArrayList<Basedocnames>(); //19张表，对应19个model
        int kmfzyevo_num = 0; // 每个code对应的记录条数
        // 辅助余额对象集
        List<Subbalance> subbalance = new ArrayList<Subbalance>();
        try {
            String baseDocNames = IPTP.getBaseDocNames(); //调用接口4
            Map<String, String> map = StringToMapUtil.ToMap(baseDocNames);
            Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> entry = it.next();
                String keyo = entry.getKey();
                String valueo = entry.getValue();
                Basedocnames bdc = new Basedocnames();
                bdc.setKeyo(keyo);
                bdc.setValueo(valueo);
                basedocnames.add(bdc); //保存19个对象
                System.out.println(keyo);
            }
            /*
             * 遍历对象列表，分别调用接口5（getBaseDoc）
             */
            for (Basedocnames bdn : basedocnames) {
                System.out.println("===============" + bdn.getKeyo());
                List<String> codoList = new ArrayList<String>();
                //取账簿编码表code值
                if ("org_accountingbook".equals(bdn.getKeyo())) {
                    String code = bdn.getKeyo();
                    String baseDocStr = IPTP.getBaseDoc(code); //调用接口5，拿到code对应的明细信息
                    String subBaseDocStr = baseDocStr.substring(1, baseDocStr.length() - 1); //去掉首位中括号
                    String[] subBaseDocStrArray = subBaseDocStr.split("\\},"); //按 '},'分割字符串
                    for (int i = 0; i < subBaseDocStrArray.length; i++) {
                        String str = subBaseDocStrArray[i] + "}"; //补齐分割是去掉的右括号
                        Map<String, String> baseDocMap = StringToMapUtil.ToMap(str);//将每条数据转换成map
                        String codo = baseDocMap.get("code");
                        codoList.add(codo);// 保存接口5 中的code用于调用接口1 取得辅助余额信息
                    }
                    for (String codo : codoList) {
                        QueryVO qv = new QueryVO();
                        // 接口性能太差，数组中每次放一个值
                        qv.setBookCodes(new String[]{codo});
                        qv.setYear(year);
                        //后面接口月份需要为单数，所以这里加了判断
                        if (month.length() == 1) {
                            String mon = "0" + month;
                            qv.setMonth(mon);
                        } else {
                            qv.setMonth(month);
                        }
                        KMFZYEVO[] kmfzyevo = null;
                        try {
                            kmfzyevo = IPTP.getKMFZYE(qv); //调用接口 1
                            if (kmfzyevo == null) {
                                System.out.println("kmfzyevo 是空值 ..............");
                            } else {
                                kmfzyevo_num += kmfzyevo.length;
                                for (int i = 0; i < kmfzyevo.length; i++) {
                                    Subbalance sb = new Subbalance();
                                    String adjustperiod = kmfzyevo[i].getAdjustperiod();
                                    sb.setAdjustperiod(adjustperiod);
                                    String assid = kmfzyevo[i].getAssid();
                                    sb.setAssid(assid);
                                    String assValue = kmfzyevo[i].getAssValue();
                                    sb.setAssValue(assValue);
                                    String b_orient = kmfzyevo[i].getB_orient();
                                    sb.setB_orient(b_orient);
                                    String begin_amou = kmfzyevo[i].getBegin_amoumt();
                                    sb.setBegin_amou(begin_amou);
                                    String creditamount = kmfzyevo[i].getCreditamount();
                                    sb.setCreditamount(creditamount);
                                    String debitamount = kmfzyevo[i].getDebitamount();
                                    sb.setDebitamount(debitamount);
                                    String sum_credit = kmfzyevo[i].getSum_credit();
                                    sb.setSum_credit(sum_credit);
                                    String sum_debit = kmfzyevo[i].getSum_debit();
                                    sb.setSum_debit(sum_debit);
                                    String end_amoumt = kmfzyevo[i].getEnd_amoumt();
                                    sb.setEnd_amoumt(end_amoumt);
                                    String e_orient = kmfzyevo[i].getE_orient();
                                    sb.setE_orient(e_orient);
                                    String period = kmfzyevo[i].getPeriod();
                                    sb.setPeriod(period);
                                    String pk_accasoa = kmfzyevo[i].getPk_accasoa();
                                    sb.setPk_accasoa(pk_accasoa);
                                    String accasoa_nam = kmfzyevo[i].getAccasoa_name();
                                    sb.setAccasoa_nam(accasoa_nam);
                                    //accasoa_nam 包含转移字符'\'，select 时 参数需要转义为'\\'
//				                    String escape_accasoa_nam = accasoa_nam.replace("\\", "\\\\");
//				                	sb.setAccasoa_nam(escape_accasoa_nam);
//				                	System.out.println("Begin ======================="+escape_accasoa_nam);
                                    String pk_accountin = kmfzyevo[i].getPk_accountingbook();
                                    sb.setPk_accountin(pk_accountin);
                                    String accountingbookName = kmfzyevo[i].getAccountingbookName();
                                    sb.setAccountingbookName(accountingbookName);
                                    String accountingbookCode = kmfzyevo[i].getAccountingbookCode();
                                    sb.setAccountingbookCode(accountingbookCode);
                                    String year1 = kmfzyevo[i].getYear();
                                    sb.setYear(year1);
//				                	int flag = SubbalanceService.selectByParam(sb);
//				                	if(flag == 0){
                                    SubbalanceService.insertSubbalance(sb);
//				                	}else{
//				                		SubbalanceService.updateSubbalance(sb);
//				                	}
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        } catch (BusinessException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        System.out.println("程序执行完毕............ getKMFZYE 返回 " + kmfzyevo_num + " 数据");
        try {
            Thread.sleep(1000 * 30); //程序休眠 30s 便于观察
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/PLExport", method = {RequestMethod.POST, RequestMethod.GET})
    public Result pLExport(HttpServletResponse response, String organCode, String year, Integer startMonth, Integer endMonth, Integer userType, String commId, Integer exportType) {
        if (year == null) {
            return Response.responseFail("请传递正确的年份！");
        }
        if (organCode == null && commId == null) {
            return Response.responseFail("请传递区域编号或者项目编号！");
        }
        if (userType == null) {
            return Response.responseFail("请传递用户所属类型！");
        }
        if (exportType == null) {
            return Response.responseFail("请传递用户所需要导出的报表类型！");
        }
        if (exportType == 1) {
            if (startMonth == null || endMonth == null || startMonth < 1 || endMonth > 12) {
                return Response.responseFail("请传递正确的起始月份或结束月份！");
            }
        }
        if (commId.equals("") || commId.equals("null")) {
            commId = null;
        }

        if (organCode.equals("") || organCode.equals("null")) {
            organCode = null;
        }

        if (exportType == 2 && userType == 0) {
            userType = 1;
        }
        financialService.exportPL(response, organCode, year, startMonth, endMonth, userType, commId, exportType);
        return Response.response();
    }

    @ResponseBody
    @RequestMapping(value = "/getPLByMonth", method = {RequestMethod.POST, RequestMethod.GET})
    public Result getPLByMonth(@RequestParam(value = "organCode", required = false) String organCode, @RequestParam(value = "commId", required = false) String commId, @RequestParam("userType") Integer userType,
                               @RequestParam("year") String year, @RequestParam("startMonth") Integer startMonth,
                               @RequestParam("endMonth") Integer endMonth) {
        if (year == null) {
            return Response.responseFail("请传递正确的年份！");
        }
        if (organCode == null && commId == null) {
            return Response.responseFail("请传递区域编号或者项目编号！");
        }
        if (startMonth == null || endMonth == null || startMonth < 1 || endMonth > 12) {
            return Response.responseFail("请传递正确的起始月份或结束月份！");
        }
        if (userType == null) {
            return Response.responseFail("请传递用户所属类型！");
        }
        if (userType == 1 && (organCode == null || StringUtil.isBlankOrEmpty(organCode) || "null".equals(organCode))) {
            return Response.responseFail("请传递正确的参数！");
        }

        if (userType == 2 && (commId == null || StringUtil.isBlankOrEmpty(commId) || "null".equals(commId))) {
            return Response.responseFail("请传递正确的参数！");
        }

        if (commId.equals("") || commId.equals("null")) {
            commId = null;
        }

        if (organCode.equals("") || organCode.equals("null")) {
            organCode = null;
        }
        return Response.response(financialService.getPLByMonth(organCode, commId, year, startMonth, endMonth, userType, 1));
    }

    @ResponseBody
    @RequestMapping(value = "/getPLByProject", method = {RequestMethod.POST, RequestMethod.GET})
    public Result getPLByProject(@RequestParam("year") String year, @RequestParam("userType") Integer userType,
                                 @RequestParam(value = "organCode", required = false) String organCode, @RequestParam(value = "commId", required = false) String commId) {
        if (year == null) {
            return Response.responseFail("请传递正确的年份！");
        }
        if (userType == null) {
            return Response.responseFail("请传递用户所属类型！");
        }
        if (userType == 0) {
            userType = 1;
        }
        if (organCode == null && commId == null) {
            return Response.responseFail("请传递区域编号或者项目编号！");
        }

        if (userType == 1 && (organCode == null || StringUtil.isBlankOrEmpty(organCode) || "null".equals(organCode))) {
            return Response.responseFail("请传递正确的参数！");
        }

        if (userType == 2 && (commId == null || StringUtil.isBlankOrEmpty(commId) || "null".equals(commId))) {
            return Response.responseFail("请传递正确的参数！");
        }
        if (commId.equals("") || commId.equals("null")) {
            commId = null;
        }

        if (organCode.equals("") || organCode.equals("null")) {
            organCode = null;
        }
        List<JSONObject> jsonObjects = new ArrayList<>();
        List<PLByProject> plByProjects = financialService.getPLByProject(organCode, commId, year, userType);
        if (plByProjects.size() != 0) {
            for (PLByProject plByProject : plByProjects) {
                JSONObject source = JSON.parseObject(plByProject.toString());
                JSONObject target = new JSONObject();
                reduceJSON(source, target, "root");
                jsonObjects.add(target);
            }
        }
        return Response.response(jsonObjects);
    }

    @ResponseBody
    @RequestMapping(value = "/getPLByProfit", method = {RequestMethod.POST, RequestMethod.GET})
    public Result getPLByProfit(String year, String organCode) {
        if (year == null) {
            return Response.responseFail("请传递正确的年份！");
        }
        if (organCode == null) {
            return Response.responseFail("请传递区域编号！");
        }
        return Response.response(financialService.getPLByProfit(organCode, year));
    }


    @ResponseBody
    @RequestMapping(value = "/getOrganInfo", method = {RequestMethod.POST, RequestMethod.GET})
    public Object getOrganInfo(String AccessToken, Integer index) {
        JSONObject returnJson = new JSONObject();
        List<JSONObject> organList = new ArrayList<>();
        List<JSONObject> commIdList = new ArrayList<>();

        AccessToken accessToken = accessTokenService.findByToken(AccessToken);
        if (accessToken == null) {
            return Response.responseFail("该token已过期！");
        }
        if (accessToken.getUserCode() == null) {
            return Response.responseFail("userCode is null！");
        }
        String userCode = accessToken.getUserCode();
        int userType = userRoleService.judgeRole(accessToken.getUserCode());
        returnJson.put("userType", userType);

        List<ErpNcData> erpNcDataList = new ArrayList<>();

        if (userType == 0 && index != 1) {
            userType = 1;
        }
        if (userType == 1) {
            erpNcDataList = tbHsprCommunityService.selectRegionByUserCode(userCode);
        }

        if (userType == 2) {
            erpNcDataList = tbHsprCommunityService.selectProjectByUserCode(userCode);
        }

        Map<String, List<JSONObject>> organMap = new HashMap<>();
        Map<String, String> organCodeMap = new HashMap<>();
        for (ErpNcData erpNcData : erpNcDataList) {
            if (organMap.keySet().contains(erpNcData.getOrganCode())) {
                List<JSONObject> jsonObjects = organMap.get(erpNcData.getOrganCode());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("commID", erpNcData.getCommID());
                jsonObject.put("commName", erpNcData.getPropertyProject());
                jsonObjects.add(jsonObject);
            } else {
                List<JSONObject> jsonObjects = new ArrayList<>();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("commID", erpNcData.getCommID());
                jsonObject.put("commName", erpNcData.getPropertyProject());
                jsonObjects.add(jsonObject);
                organMap.put(erpNcData.getOrganCode(), jsonObjects);
            }
            organCodeMap.put(erpNcData.getOrganCode(), erpNcData.getOrganName());
        }


        for (String organCode : organMap.keySet()) {
            List<JSONObject> jsonObjects = organMap.get(organCode);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("organCode", organCode);
            jsonObject.put("organName", organCodeMap.get(organCode));
            if (index == 1) {
                commIdList.addAll(jsonObjects);
            }
            if (index == 2) {
                jsonObject.put("commList", jsonObjects);
            }
            organList.add(jsonObject);
        }

        returnJson.put("organList", organList);
        returnJson.put("commIdList", commIdList);
        return Response.response(returnJson);
    }

    @ResponseBody
    @RequestMapping(value = "/FinanceSaveReasonList", method = RequestMethod.POST)
    public Result financeSaveReasonList(String data) {
        List<Reason> reasons = JSON.parseObject(data, new TypeReference<List<Reason>>() {
        });
        financialService.saveReasonList(reasons);
        return Response.response("插入成功");

    }

    @ResponseBody
    @RequestMapping(value = "/delPLRedisData", method = RequestMethod.POST)
    public Result delPLRedisData(int flagNum) {
        if (flagNum == 1) logger.info(String.valueOf(RedisUtils.del("bgyNCFinanicalPLByMonth")));
        else if (flagNum == 2) logger.info(String.valueOf(RedisUtils.del("bgyNCFinanicalPLByProject")));
        else if (flagNum == 3) {
            logger.info(String.valueOf(RedisUtils.del("bgyNCFinanicalPLByMonth")));
            logger.info(String.valueOf(RedisUtils.del("bgyNCFinanicalPLByProject")));
        }
        return Response.response();
    }

    @ResponseBody
    @RequestMapping(value = "/delRedisRegionData", method = RequestMethod.POST)
    public Result delRedisRegionData(String year, String organCode) {
        if (organCode.equals("") || organCode.equals("null")) {
            organCode = null;
        }
        financialService.deleteErpDataFromRedis(year, organCode);
        return Response.response("success");
    }

    @ResponseBody
    @RequestMapping(value = "/saveRedisRegionData", method = RequestMethod.POST)
    public Result saveRedisRegionData(String year, String organCode) {
        if (organCode.equals("") || organCode.equals("null")) {
            organCode = null;
        }
        try {
            financialService.saveErpDataToRedis(year, organCode);
            return Response.response("success");
        } catch (Exception e) {
            return Response.responseFail(e.getMessage());
        }

    }

    @ResponseBody
    @RequestMapping(value = "/getRedisRegionData", method = RequestMethod.POST)
    public Result getRedisRegionData(String organCode) {
        if (!StringUtil.isBlankOrEmpty(organCode)) {
            return Response.response(RedisUtils.hget("NCFinancial-ERP-RegionData", organCode));
        } else {
            return Response.response(RedisUtils.hgetAll("NCFinancial-ERP-RegionData").keySet());
        }
    }

    private void reduceJSON(JSONObject source, JSONObject target, String fatherKey) {
        Iterator<String> iterator = source.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            if (source.get(key) == null) {
                target.put(fatherKey + "-" + key, "null");
            } else {
                if (source.get(key) instanceof JSONObject) {
                    reduceJSON(source.getJSONObject(key), target, fatherKey + "-" + key);
                } else {
                    target.put(fatherKey + "-" + key, source.getString(key));

                }
            }
        }
    }

}