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.CyclePaymentPlanE1Info;
import com.dst.slms.plan.entity.CyclePaymentPlanInfo;
import com.dst.slms.plan.entity.ProjectYearBudgetE1Info;
import com.dst.slms.plan.entity.ProjectYearBudgetInfo;
import com.dst.slms.plan.service.IProjectYearBudgetService;

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.common.annotation.SysPermissionName;
import org.springframework.web.bind.annotation.PostMapping;
/**   
 * @Title: 项目年度预算 Controller
 * @Description: 项目年度预算
 * @author 
 * @date 2020-05-02 11:14:38
 * @version V1.0   
 *
 */
@SuppressWarnings("unchecked")
@Controller
@RequestMapping("/projectYearBudgetController")
@SysPermissionName(name="项目年度预算",type=Constant.MENU)
public class ProjectYearBudgetController extends AbstractProjectYearBudgetController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(ProjectYearBudgetController.class);
	
	@Autowired
	private IProjectYearBudgetService iProjectYearBudgetService;
	
	/**
	 * 审核
	 */
	@SysPermissionName(name="审核")
	@RequiresPermissions("Prt:ProjectYearBudget:audit")
	@ResponseBody
    @PostMapping(value = "/audit")
	public R auditAction(ProjectYearBudgetInfo info, HttpServletRequest req) {
		R audit = iProjectYearBudgetService.audit(info.getId(),com.dst.slms.common.utils.SysContext.getUserId());
		
		info = iProjectYearBudgetService.getEntity(ProjectYearBudgetInfo.class, info.getId());
		info.setIsnew(true);
		iProjectYearBudgetService.save(info);
		String number = info.getNumber();
		Integer editionnumber = info.getEditionnumber();
		editionnumber = editionnumber-1;
		EntityQuery eq = new EntityQuery(ProjectYearBudgetInfo.class);
		eq.eq("number", number);
		eq.eq("editionnumber", editionnumber);
		eq.add();
		List entityList = iProjectYearBudgetService.getEntityList(eq);
		if(entityList.size()>0){
			ProjectYearBudgetInfo object = (ProjectYearBudgetInfo) entityList.get(0);
			String sql = "update yc_cost_ProjectYearBudget set fisnew = 'N' where fid = '"+object.getId()+"'";
			iProjectYearBudgetService.executeSql(sql);
		}
		
		return audit;
	}
	
	/**
	 * 反审核
	 */
	@SysPermissionName(name="反审核")
	@RequiresPermissions("Prt:ProjectYearBudget:unAudit")	 
	@ResponseBody
    @PostMapping(value = "/unAudit")
	public R unAuditAction(ProjectYearBudgetInfo info, HttpServletRequest req) {
		info = iProjectYearBudgetService.getEntity(ProjectYearBudgetInfo.class, info.getId());
		String sql = "select fid from yc_cost_ProjectYearBudget where fstate != 'AUDIT' and fnumber ='"+info.getNumber()+"'";
		List<Map<String,Object>> executeSqlQuery = iProjectYearBudgetService.executeSqlQuery(sql);
		if(executeSqlQuery.size()>0){
			throw new BizException("当前数据已有新版本，不能反审批该版本数据");
		}
		if(!info.getIsnew()){
			throw new BizException("当前数据不是最新版本，不能反审批");
		}
		
		R unAudit = iProjectYearBudgetService.unAudit(info.getId());
		SelectorItemCollection sic = new SelectorItemCollection();
		sic.add("isnew");
		info.setIsnew(false);
		iProjectYearBudgetService.save(info,sic);
		String number = info.getNumber();
		Integer editionnumber = info.getEditionnumber();
		editionnumber = editionnumber-1;
		
		EntityQuery eq = new EntityQuery(ProjectYearBudgetInfo.class);
		eq.eq("number", number);
		eq.eq("editionnumber", editionnumber);
		eq.add();
		List entityList = iProjectYearBudgetService.getEntityList(eq);
		if(entityList.size()>0){
			ProjectYearBudgetInfo object = (ProjectYearBudgetInfo) entityList.get(0);
			sql = "update yc_cost_ProjectYearBudget set fisnew = 'Y' where fid = '"+object.getId()+"'";
			iProjectYearBudgetService.executeSql(sql);
		}
		return unAudit;
	}
	
	@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("project.id", split);
		}
		queryExecutor.add();
		return queryExecutor;
	}
	
	@Override
	public Object createNewModel(HttpServletRequest req) {
		ProjectYearBudgetInfo createNewModel = (ProjectYearBudgetInfo) super.createNewModel(req);
		createNewModel.setId(BOSUuid.create("WAN594UG"));
		createNewModel.setIsnew(false);
		createNewModel.setEditionnumber(1);
		
		EntityQuery eq = new EntityQuery(MarketAccountInfo.class);
		eq.eq("isEnable", true);
		eq.add();
		List entityList = iProjectYearBudgetService.getEntityList(eq);
		for (int i = 0; i < entityList.size(); i++) {
			MarketAccountInfo account = (MarketAccountInfo) entityList.get(i);
			ProjectYearBudgetE1Info e1Info = new ProjectYearBudgetE1Info();
			e1Info.setAccount(account);
			e1Info.setAccountName(account.getName());
			createNewModel.getProjectYearBudgetE1().add(e1Info);
		}
		
		return createNewModel;
	}
	
	/**
	 * 修订
	 */
	@ResponseBody
	@RequestMapping(value="/revise")
	public ModelAndView revise(HttpServletRequest request){
		String billid = request.getParameter("id");
		ProjectYearBudgetInfo maninfo = iProjectYearBudgetService.getEntity(ProjectYearBudgetInfo.class, billid);
		
		ProjectYearBudgetInfo info = new ProjectYearBudgetInfo();
		BeanUtilTo.copyProperties(maninfo, info);
		info.setEditionnumber(maninfo.getEditionnumber()+1);
		info.setId(""); 
		info.setState("SAVE");
		info.setIsnew(false);
		for (int i = 0; i < info.getProjectYearBudgetE1().size(); i++) {
			info.getProjectYearBudgetE1().get(i).setId("");
			info.getProjectYearBudgetE1().get(i).setParent(null);
		}
		request.setAttribute("model", info);
		request.setAttribute("oldId", billid);
		return new ModelAndView("com/dst/slms/plan/projectyearbudget/projectYearBudgetEdit");
	}
	
	/**
	 * 是否最新版
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/isLast")
	@ResponseBody
	public R isLast(HttpServletRequest request){
		String billid = request.getParameter("billid");//
		ProjectYearBudgetInfo info = iProjectYearBudgetService.getEntity(ProjectYearBudgetInfo.class, billid);
		String sql = "select fid from yc_cost_ProjectYearBudget where fstate != 'AUDIT' and fnumber ='"+info.getNumber()+"'";
		String key = "true";
		List<Map<String,Object>> executeSqlQuery = iProjectYearBudgetService.executeSqlQuery(sql);
		if(info.getIsnew()){
			key = "false";
			if(executeSqlQuery.size()>0){
				key = "noAudit";
			}
		}
		return R.ok("", key, "0");
	}
	
	/**
	 * 获取数据
	 * @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,ProjectYearBudgetE1Info> e1InfoMapping = new HashMap<>();
		eq = new EntityQuery(ProjectYearBudgetE1Info.class);
		eq.eq("parent.id", id);
		eq.add();
		List<ProjectYearBudgetE1Info> entityList = getService().getEntityList(eq);
		entityList.forEach(per->{
			if(per.getAccount()!=null){
				e1InfoMapping.put(per.getAccount().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", "");
			
			ProjectYearBudgetE1Info 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.getAmount():BigDecimal.ZERO); //合计金额
			value.put("one",  e1Info!=null?e1Info.getOne():BigDecimal.ZERO); //1
			value.put("two",  e1Info!=null?e1Info.getTwo():BigDecimal.ZERO); //2
			value.put("three",  e1Info!=null?e1Info.getThree():BigDecimal.ZERO); //3
			value.put("four",  e1Info!=null?e1Info.getFour():BigDecimal.ZERO); //4
			value.put("five",  e1Info!=null?e1Info.getFive():BigDecimal.ZERO); //5
			value.put("six",  e1Info!=null?e1Info.getSix():BigDecimal.ZERO); //6
			value.put("seven",  e1Info!=null?e1Info.getSeven():BigDecimal.ZERO); //7
			value.put("eight",  e1Info!=null?e1Info.getEight():BigDecimal.ZERO); //8
			value.put("nine",  e1Info!=null?e1Info.getNine():BigDecimal.ZERO); //9
			value.put("ten",  e1Info!=null?e1Info.getTen():BigDecimal.ZERO); //10
			value.put("eleven",  e1Info!=null?e1Info.getEleven():BigDecimal.ZERO); //11
			value.put("twelve",  e1Info!=null?e1Info.getTwelve():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);
		ProjectYearBudgetInfo baseInfo = (ProjectYearBudgetInfo)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.getProjectYearBudgetE1().add(getCastJsonTOEntity((JSONObject) children1.get(j)));
							}
						}
						baseInfo.getProjectYearBudgetE1().add(getCastJsonTOEntity(tempObj));
					}
				}
				baseInfo.getProjectYearBudgetE1().add(getCastJsonTOEntity(eObj));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	private ProjectYearBudgetE1Info getCastJsonTOEntity(JSONObject eObj){
		ProjectYearBudgetE1Info e1Info = new ProjectYearBudgetE1Info();
		e1Info.setAccountName(UIRuleUtil.getString(eObj.get("name")));
		MarketAccountInfo accountInfo = new MarketAccountInfo();
		accountInfo.setId(UIRuleUtil.getString(eObj.get("id")));
		e1Info.setAccount(accountInfo);
		e1Info.setAmount(UIRuleUtil.getBigDecimal(eObj.get("amount")));
		e1Info.setOne(UIRuleUtil.getBigDecimal(eObj.get("one")));
		e1Info.setTwo(UIRuleUtil.getBigDecimal(eObj.get("two")));
		e1Info.setThree(UIRuleUtil.getBigDecimal(eObj.get("three")));
		e1Info.setFour(UIRuleUtil.getBigDecimal(eObj.get("four")));
		e1Info.setFive(UIRuleUtil.getBigDecimal(eObj.get("five")));
		e1Info.setSix(UIRuleUtil.getBigDecimal(eObj.get("six")));
		e1Info.setSeven(UIRuleUtil.getBigDecimal(eObj.get("seven")));
		e1Info.setEight(UIRuleUtil.getBigDecimal(eObj.get("eight")));
		e1Info.setNine(UIRuleUtil.getBigDecimal(eObj.get("nine")));
		e1Info.setTen(UIRuleUtil.getBigDecimal(eObj.get("ten")));
		e1Info.setEleven(UIRuleUtil.getBigDecimal(eObj.get("eleven")));
		e1Info.setTwelve(UIRuleUtil.getBigDecimal(eObj.get("twelve")));
		
		return e1Info;
	}
}
