package com.dst.slms.plan.web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.dst.slms.common.config.Constant;
import com.dst.slms.common.entity.CoreInfo;
import com.dst.slms.common.entity.sic.SelectorItemCollection;
import com.dst.slms.common.excetion.BizException;
import com.dst.slms.common.service.util.DataGrid;
import com.dst.slms.common.service.util.EntityQuery;
import com.dst.slms.common.utils.R;
import com.dst.slms.common.utils.UIRuleUtil;
import com.dst.slms.common.utils.bos.BOSUuid;
import com.dst.slms.plan.entity.AnnualPaymentPlanInfo;
import com.dst.slms.plan.entity.AnnualPlanDetailsInfo;
import com.dst.slms.plan.service.IAnnualPaymentPlanService;
import com.dst.slms.system.entity.SysOrgInfo;

import cn.hutool.core.bean.BeanUtilTo;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dst.slms.base.entity.MarketAccountInfo;
import com.dst.slms.base.entity.MarketProjectInfo;
import com.dst.slms.common.annotation.SysPermissionName;
import org.springframework.web.bind.annotation.PostMapping;
/**   
 * @Title: 年度支付计划 Controller
 * @Description: 年度支付计划
 * @author 
 * @date 2020-05-02 16:24:28
 * @version V1.0   
 *
 */
@SuppressWarnings("unchecked")
@Controller
@RequestMapping("/annualPaymentPlanController")
@SysPermissionName(name="年度支付计划",type=Constant.MENU)
public class AnnualPaymentPlanController extends AbstractAnnualPaymentPlanController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(AnnualPaymentPlanController.class);
	
	@Autowired
	private IAnnualPaymentPlanService iAnnualPaymentPlanService;
	
	/**
	 * 审核
	 */
	@SysPermissionName(name="审核")
	@RequiresPermissions("ann:annualPaymentPlan:audit")
	@ResponseBody
    @PostMapping(value = "/audit")
	public R auditAction(AnnualPaymentPlanInfo info, HttpServletRequest req) {
		R audit = iAnnualPaymentPlanService.audit(info.getId(),com.dst.slms.common.utils.SysContext.getUserId());
		
		info = iAnnualPaymentPlanService.getEntity(AnnualPaymentPlanInfo.class, info.getId());
		info.setIsnew(true);
		iAnnualPaymentPlanService.save(info);
		String number = info.getNumber();
		Integer editionnumber = info.getEditionnumber();
		editionnumber = editionnumber-1;
		EntityQuery eq = new EntityQuery(AnnualPaymentPlanInfo.class);
		eq.eq("number", number);
		eq.eq("editionnumber", editionnumber);
		eq.add();
		List entityList = iAnnualPaymentPlanService.getEntityList(eq);
		if(entityList.size()>0){
			AnnualPaymentPlanInfo object = (AnnualPaymentPlanInfo) entityList.get(0);
			String sql = "update yc_cost_annualPaymentPlan set fisnew = 'N' where fid = '"+object.getId()+"'";
			iAnnualPaymentPlanService.executeSql(sql);
		}
		
		return audit;
	}
	
	/**
	 * 反审核
	 */
	@SysPermissionName(name="反审核")
	@RequiresPermissions("ann:annualPaymentPlan:unAudit")	 
	@ResponseBody
    @PostMapping(value = "/unAudit")
	public R unAuditAction(AnnualPaymentPlanInfo info, HttpServletRequest req) {
		info = iAnnualPaymentPlanService.getEntity(AnnualPaymentPlanInfo.class, info.getId());
		String sql = "select fid from yc_cost_annualPaymentPlan where fstate != 'AUDIT' and fnumber ='"+info.getNumber()+"'";
		List<Map<String,Object>> executeSqlQuery = iAnnualPaymentPlanService.executeSqlQuery(sql);
		if(executeSqlQuery.size()>0){
			throw new BizException("当前数据已有新版本，不能反审批该版本数据");
		}
		if(!info.getIsnew()){
			throw new BizException("当前数据不是最新版本，不能反审批");
		}
		
		R unAudit = iAnnualPaymentPlanService.unAudit(info.getId());
		SelectorItemCollection sic = new SelectorItemCollection();
		sic.add("isnew");
		info.setIsnew(false);
		iAnnualPaymentPlanService.save(info,sic);
		String number = info.getNumber();
		Integer editionnumber = info.getEditionnumber();
		editionnumber = editionnumber-1;
		
		EntityQuery eq = new EntityQuery(AnnualPaymentPlanInfo.class);
		eq.eq("number", number);
		eq.eq("editionnumber", editionnumber);
		eq.add();
		List entityList = iAnnualPaymentPlanService.getEntityList(eq);
		if(entityList.size()>0){
			AnnualPaymentPlanInfo object = (AnnualPaymentPlanInfo) entityList.get(0);
			sql = "update yc_cost_annualPaymentPlan set fisnew = 'Y' where fid = '"+object.getId()+"'";
			iAnnualPaymentPlanService.executeSql(sql);
		}
		return unAudit;
	}
	
	@Override
	public Object createNewModel(HttpServletRequest req) {
		AnnualPaymentPlanInfo createNewModel = (AnnualPaymentPlanInfo) super.createNewModel(req);
		createNewModel.setId(BOSUuid.create("RZJ5TWD5"));
		createNewModel.setIsnew(false);
		createNewModel.setEditionnumber(1);
		
		EntityQuery eq = new EntityQuery(MarketAccountInfo.class);
		eq.eq("isEnable", true);
		eq.add();
		List entityList = iAnnualPaymentPlanService.getEntityList(eq);
		for (int i = 0; i < entityList.size(); i++) {
			MarketAccountInfo account = (MarketAccountInfo) entityList.get(i);
			AnnualPlanDetailsInfo e1Info = new AnnualPlanDetailsInfo();
			e1Info.setMarketAccoun(account);
			e1Info.setMarketAccounName(account.getName());
			createNewModel.getAnnualPlanDetails().add(e1Info);
		}
		return createNewModel;
	}
	
	@Override
	public EntityQuery getQueryExecutor(HttpServletRequest request, CoreInfo info, DataGrid dataGrid) {
		EntityQuery queryExecutor = super.getQueryExecutor(request, info, dataGrid);
		//选中左边树节点ID
		String selectTreeId = request.getParameter("selectTreeId");
		 
		if(UIRuleUtil.isNotNull(selectTreeId)){
			String[] split = selectTreeId.split(",");
			queryExecutor.in("marketProject.id", split);
		}
		queryExecutor.add();
		return queryExecutor;
	}
	
	
	/**
	 * 修订
	 */
	@ResponseBody
	@RequestMapping(value="/revise")
	public ModelAndView revise(HttpServletRequest request){
		String billid = request.getParameter("id");
		AnnualPaymentPlanInfo maninfo = iAnnualPaymentPlanService.getEntity(AnnualPaymentPlanInfo.class, billid);
		
		AnnualPaymentPlanInfo info = new AnnualPaymentPlanInfo();
		BeanUtilTo.copyProperties(maninfo, info);
		info.setEditionnumber(maninfo.getEditionnumber()+1);
		info.setId(""); 
		info.setState("SAVE");
		info.setIsnew(false);
		for (int i = 0; i < info.getAnnualPlanDetails().size(); i++) {
			info.getAnnualPlanDetails().get(i).setId("");
			info.getAnnualPlanDetails().get(i).setParent(null);
		}
		request.setAttribute("model", info);
		request.setAttribute("oldId", billid);
		return new ModelAndView("com/dst/slms/plan/annualpaymentplan/annualPaymentPlanEdit");
	}
	
	/**
	 * 是否最新版
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/isLast")
	@ResponseBody
	public R isLast(HttpServletRequest request){
		String billid = request.getParameter("billid");//
		AnnualPaymentPlanInfo info = iAnnualPaymentPlanService.getEntity(AnnualPaymentPlanInfo.class, billid);
		String sql = "select fid from yc_cost_annualPaymentPlan where fstate != 'AUDIT' and fnumber ='"+info.getNumber()+"'";
		String key = "true";
		List<Map<String,Object>> executeSqlQuery = iAnnualPaymentPlanService.executeSqlQuery(sql);
		if(info.getIsnew()){
			key = "false";
			if(executeSqlQuery.size()>0){
				key = "noAudit";
			}
		}
		return R.ok("", key, "0");
	}
	
	/**
	 * 根据营销项目获取组织
	 */
	@ResponseBody
	@RequestMapping(value="/getOrg")
	public JSONObject getOrgUnit(HttpServletRequest request){
		String projectId = request.getParameter("projectId");
		JSONObject json = new JSONObject();
		if(UIRuleUtil.isNotNull(projectId)){
			MarketProjectInfo project = iAnnualPaymentPlanService.getEntity(MarketProjectInfo.class, projectId);
			SysOrgInfo admin = project.getOrg();
			json.put("admin", admin);
		}
		return json;
	}
	
	/**
	 * 获取数据
	 * @param request
	 */
	@ResponseBody
    @RequestMapping(value = "getAccountEntryData")
	public void list(HttpServletRequest request) {
		String id = UIRuleUtil.getString(request.getParameter("id"));
		String oldId = UIRuleUtil.getString(request.getParameter("oldId"));
		if(UIRuleUtil.isNull(id)){
			id = oldId;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("number", "asc");
		EntityQuery eq = new EntityQuery(MarketAccountInfo.class);
		eq.eq("isEnable", true);
		eq.setOrder(map);
		eq.add();
		List<MarketAccountInfo> list  = getService().getEntityList(eq);
		
		Map<String,AnnualPlanDetailsInfo> e1InfoMapping = new HashMap<>();
		eq = new EntityQuery(AnnualPlanDetailsInfo.class);
		eq.eq("parent.id", id);
		eq.add();
		List<AnnualPlanDetailsInfo> entityList = getService().getEntityList(eq);
		entityList.forEach(per->{
			if(per.getMarketAccoun()!=null){
				e1InfoMapping.put(per.getMarketAccoun().getNumber(), per);
			}
		});
		
		MarketAccountInfo rootInfo = new MarketAccountInfo();
		rootInfo.setName("营销科目");
		rootInfo.setNumber("N000");
		rootInfo.setId("ROOT");
		list.add(0,rootInfo);
		
		List<Map<String,Object>> resultList = new ArrayList<>();
		list.forEach(per->{
			
			Map<String,Object> value = new HashMap<>();
			if(per.getParent()!=null) {
				value.put("_parentId", per.getParent().getId());
			}else if(!"N000".equals(per.getNumber())){
				value.put("_parentId", "ROOT");
			}
			value.put("id", per.getId());
			value.put("state", "open");
			value.put("icon", "");
			
			AnnualPlanDetailsInfo e1Info = e1InfoMapping.get(per.getNumber());
			
			value.put("isLeaf", per.getIsLeaf());
			value.put("name", per.getName());
			value.put("number",per.getNumber());
			value.put("amount", e1Info!=null?e1Info.getAmountTotal():BigDecimal.ZERO); //合计金额
			value.put("one",  e1Info!=null?e1Info.getJan():BigDecimal.ZERO); //1
			value.put("two",  e1Info!=null?e1Info.getFeb():BigDecimal.ZERO); //2
			value.put("three",  e1Info!=null?e1Info.getMar():BigDecimal.ZERO); //3
			value.put("four",  e1Info!=null?e1Info.getApr():BigDecimal.ZERO); //4
			value.put("five",  e1Info!=null?e1Info.getMay():BigDecimal.ZERO); //5
			value.put("six",  e1Info!=null?e1Info.getJun():BigDecimal.ZERO); //6
			value.put("seven",  e1Info!=null?e1Info.getJul():BigDecimal.ZERO); //7
			value.put("eight",  e1Info!=null?e1Info.getAug():BigDecimal.ZERO); //8
			value.put("nine",  e1Info!=null?e1Info.getSep():BigDecimal.ZERO); //9
			value.put("ten",  e1Info!=null?e1Info.getOct():BigDecimal.ZERO); //10
			value.put("eleven",  e1Info!=null?e1Info.getNov():BigDecimal.ZERO); //11
			value.put("twelve",  e1Info!=null?e1Info.getDec():BigDecimal.ZERO); //12
			resultList.add(value);
		});
		Map mp = new HashMap<>();
		mp.put("rows", resultList);
		mp.put("total", list.size());
		writeSuccessJson(mp);
	}
	
	@Override
	public void verifyInput(CoreInfo info, HttpServletRequest req) {
		super.verifyInput(info, req);
		AnnualPaymentPlanInfo baseInfo = (AnnualPaymentPlanInfo)info;
		String parameter = req.getParameter("editTreeGrid_JSON");
		try {
			String json = URLDecoder.decode(parameter,"utf-8");
			JSONArray arrayList = JSON.parseArray(json);
			for(Object obj:arrayList){
				JSONObject eObj = (JSONObject)obj;
				if(eObj.get("children") != null && eObj.get("children") instanceof JSONArray){
					JSONArray children = (JSONArray)eObj.get("children");
					for (int i = 0; i < children.size(); i++) {
						JSONObject tempObj = (JSONObject) children.get(i);
						
						if(tempObj.get("children") != null && tempObj.get("children") instanceof JSONArray){
							JSONArray children1 = (JSONArray)tempObj.get("children");
							for (int j = 0; j < children1.size(); j++) {
								baseInfo.getAnnualPlanDetails().add(getCastJsonTOEntity((JSONObject) children1.get(j)));
							}
						}
						baseInfo.getAnnualPlanDetails().add(getCastJsonTOEntity(tempObj));
					}
				}
				baseInfo.getAnnualPlanDetails().add(getCastJsonTOEntity(eObj));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	private AnnualPlanDetailsInfo getCastJsonTOEntity(JSONObject eObj){
		AnnualPlanDetailsInfo e1Info = new AnnualPlanDetailsInfo();
		e1Info.setMarketAccounName(UIRuleUtil.getString(eObj.get("name")));
		MarketAccountInfo accountInfo = new MarketAccountInfo();
		accountInfo.setId(UIRuleUtil.getString(eObj.get("id")));
		e1Info.setMarketAccoun(accountInfo);
		e1Info.setAmountTotal(UIRuleUtil.getBigDecimal(eObj.get("amount")));
		e1Info.setJan(UIRuleUtil.getBigDecimal(eObj.get("one")));
		e1Info.setFeb(UIRuleUtil.getBigDecimal(eObj.get("two")));
		e1Info.setMar(UIRuleUtil.getBigDecimal(eObj.get("three")));
		e1Info.setApr(UIRuleUtil.getBigDecimal(eObj.get("four")));
		e1Info.setMay(UIRuleUtil.getBigDecimal(eObj.get("five")));
		e1Info.setJun(UIRuleUtil.getBigDecimal(eObj.get("six")));
		e1Info.setJul(UIRuleUtil.getBigDecimal(eObj.get("seven")));
		e1Info.setAug(UIRuleUtil.getBigDecimal(eObj.get("eight")));
		e1Info.setSep(UIRuleUtil.getBigDecimal(eObj.get("nine")));
		e1Info.setOct(UIRuleUtil.getBigDecimal(eObj.get("ten")));
		e1Info.setNov(UIRuleUtil.getBigDecimal(eObj.get("eleven")));
		e1Info.setDec(UIRuleUtil.getBigDecimal(eObj.get("twelve")));
		
		return e1Info;
	}
}
