package com.dst.slms.proapproval.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.service.util.DataGrid;
import com.dst.slms.common.service.util.EntityQuery;
import com.dst.slms.common.support.ICrudService;
import com.dst.slms.common.utils.R;
import com.dst.slms.common.utils.SysContext;
import com.dst.slms.common.utils.UIRuleUtil;
import com.dst.slms.common.utils.bos.BOSUuid;
import com.dst.slms.contractmange.entity.SaleContractInfo;
import com.dst.slms.contractmange.service.ISaleContractService;
import com.dst.slms.proapproval.entity.MonMarkMangeInfo;
import com.dst.slms.proapproval.entity.ProjectApproveInfo;
import com.dst.slms.proapproval.service.IProjectApproveService;
import com.dst.slms.system.entity.SysOrgInfo;
import com.dst.slms.system.entity.SysPersonInfo;
import com.dst.slms.util.PersonHelper;

import cn.hutool.core.bean.BeanUtilTo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.dst.slms.base.entity.MarketProjectInfo;
import com.dst.slms.base.service.IMarketProjectService;
import com.dst.slms.common.annotation.SysPermissionName;
import org.springframework.web.bind.annotation.PostMapping;
/**   
 * @Title: 立项单 Controller
 * @Description: 立项单
 * @author 
 * @date 2020-05-02 15:30:44
 * @version V1.0   
 *
 */
@SuppressWarnings("unchecked")
@Controller
@RequestMapping("/projectApproveController")
@SysPermissionName(name="立项单",type=Constant.MENU)
public class ProjectApproveController extends AbstractProjectApproveController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(ProjectApproveController.class);
	
	@Autowired
	private IProjectApproveService iProjectApproveService;
	@Autowired
	private IMarketProjectService iMarketProjectService;
	@Autowired
	private ICrudService iCrudService;
	@Autowired
	private ISaleContractService iSaleContractService;
	/**
	 * 审核
	 */
	@SysPermissionName(name="审核")
	@RequiresPermissions("Pre:ProjectApprove:audit")
	@ResponseBody
    @PostMapping(value = "/audit")
	public R auditAction(ProjectApproveInfo info, HttpServletRequest req) {
		String[] split = info.getId().split(",");
		if(split.length>1){
			return R.error("请选择一条数据进行操作");
		}
		return iProjectApproveService.audit(info.getId(),com.dst.slms.common.utils.SysContext.getUserId());
	}
	
	/**
	 * 反审核
	 */
	@SysPermissionName(name="反审核")
	@RequiresPermissions("Pre:ProjectApprove:unAudit")	 
	@ResponseBody
    @PostMapping(value = "/unAudit")
	public R unAuditAction(ProjectApproveInfo info, HttpServletRequest req) {
		String[] split = info.getId().split(",");
		if(split.length>1){
			return R.error("请选择一条数据进行操作");
		}
		String sourcesql="select fid from yc_cost_ProjectApprove where FproAppID='"+info.getId()+"'";//判断有没有修订过
		List sourcelist = iCrudService.executeSqlQuery(sourcesql);
		if(sourcelist.size()>0){
			return R.error("该数据已有修订版本,请先删除修订版本再进行操作");
		}
		String sql="select fid from yc_cost_ProjectApprove where FID='"+info.getId()+"' and FSTATE='CANCEL'";//判断是否作废
		List sqllist = iCrudService.executeSqlQuery(sql);
		if(sqllist.size()>0){
			return R.error("该数据已作废，不允许反审批");
		}
		return iProjectApproveService.unAudit(info.getId());
	}
	@Override
	public Object createNewModel(HttpServletRequest req) {
		ProjectApproveInfo info = new ProjectApproveInfo();
		info.setNumber(getService().getNumber(info.getClass().getName()));
		info.setState("SAVE");
		String id = req.getParameter("id");
		MarketProjectInfo proinfo = iMarketProjectService.getEntity(MarketProjectInfo.class, id,new String[]{"name","org.id","org.name"});
		info.setProject(proinfo);
		info.setOrgunit(proinfo.getOrg());
		info.setIsLast(true);
		info.setVersion(1);
		return info;
	}
	@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);
		}else{
			queryExecutor.eq("project.id", "xxxx");
		}
		queryExecutor.add();
		return queryExecutor;
	}
	@Override
	public void verifyInput(CoreInfo info, HttpServletRequest req) {
		// TODO 自动生成的方法存根
		super.verifyInput(info, req);
	}
	/**
	 * 判断是否允许修订
	 * 已审批，最新版
	 */
	@ResponseBody
    @RequestMapping(value = "/checkisRevise")
	public R checkisLatest(HttpServletRequest req) {
		String id = req.getParameter("id");//
		Map map=new HashMap();
		map.put("FSTATE", "0");
		map.put("FISLATEST", "0");
		map.put("SOURCE", "0");
		String sql="select FSTATE,FisLast from yc_cost_ProjectApprove where fid='"+id+"'";
		List list = iCrudService.executeSqlQuery(sql);
		if(list.size()>0){
			Map promap=(Map) list.get(0);
			map.put("FSTATE", promap.get("FSTATE"));
			map.put("FISLATEST", promap.get("FisLast"));
		}
		String sourcesql="select fid from yc_cost_ProjectApprove where FproAppID='"+id+"'";//判断有没有修订过
		List sourcelist = iCrudService.executeSqlQuery(sourcesql);
		if(sourcelist.size()>0){
			map.put("SOURCE", "1");
		}
		ArrayList arrayList = new ArrayList();
		arrayList.add(map);
		return R.ok("",arrayList,"0");
	}
	/**
	 * 修订
	 */
	@ResponseBody
    @RequestMapping(value = "/reviseAction")
	public ModelAndView reviseAction(HttpServletRequest req) {
		String id = req.getParameter("billId");//判断该销售项目下有没有项目参数数据
		ProjectApproveInfo info=(ProjectApproveInfo) getService().getEntity(ProjectApproveInfo.class, id);
		ProjectApproveInfo newinfo=new ProjectApproveInfo();
		BeanUtilTo.copyProperties(info, newinfo);
		newinfo.setVersion(info.getVersion()+1);
		newinfo.setId(""); 
		newinfo.setState("SAVE");
		newinfo.setIsLast(false);
		newinfo.setProApp(info.getId());
		req.setAttribute("model", newinfo);
		return new ModelAndView("com/dst/slms/proapproval/projectapprove/projectApproveEdit");
	}
	/**
	 * 生成合同
	 * 1校验是否已审批的最新版
	 * 2校验是否生成过合同
	 */
	@ResponseBody
    @RequestMapping(value = "/toConAction")
	public  R toConAction(HttpServletRequest req) {
		String id = req.getParameter("id");//判断该销售项目下有没有项目参数数据
		ProjectApproveInfo info=(ProjectApproveInfo) getService().getEntity(ProjectApproveInfo.class, id);
		boolean flag=false;
		Map map=new HashMap();
		map.put("FSTATE", info.getState());
		if("AUDIT".equals(info.getState())&&info.getIsLast()&&!info.getIstoContract()){//最新版已审批并且没有生成合同
			flag=true;
		}
		map.put("FISLATEST", info.getIsLast()==true?"Y":"N");
		map.put("FIstoContract", info.getIstoContract()==true?"Y":"N");
		if(flag){
			SaleContractInfo saleContractInfo = new SaleContractInfo();
			saleContractInfo.setNumber(getService().getNumber(saleContractInfo.getClass().getName()));
			saleContractInfo.setState("SAVE");
			saleContractInfo.setSourceBillId(info.getId());
			saleContractInfo.setOrgunit(info.getOrgunit());
			saleContractInfo.setProject(info.getProject());
			saleContractInfo.setSupplier(info.getSupplier());
			saleContractInfo.setProjectApprove(info);
			saleContractInfo.setLxAmt(info.getLxAmt());
			saleContractInfo.setMarkAccount(info.getMarkaccount());
			iSaleContractService.save(saleContractInfo);
			map.put("istoCon", "Y");//生成合同成功
			String sql="update yc_cost_ProjectApprove set FistoContract='Y' where fid ='"+info.getId()+"'";
			iMarketProjectService.executeSql(sql);
		}else{
			map.put("istoCon", "N");//生成合同成功
		}
		
		ArrayList arrayList = new ArrayList();
		arrayList.add(map);
		return R.ok("",arrayList,"0");
	}
	/**
	 * 作废
	 * 作废只能作废已审批的最新版，并且把所有版本的状态改为作废
	 */
	@ResponseBody
    @RequestMapping(value = "/cancelAction")
	public  R cancelAction(HttpServletRequest req) {
		String id = req.getParameter("id");//判断该销售项目下有没有项目参数数据
		String sourcesql="select fid from yc_cost_ProjectApprove where FproAppID='"+id+"'";//判断有没有修订过，有修订的版本，不能作废
		List sourcelist = iCrudService.executeSqlQuery(sourcesql);
		Map map=new HashMap();
		boolean flag=true;
		if(sourcelist.size()>0){
			map.put("SOURCE", "1");//有新的版本
			flag=false;
		}else{
			map.put("SOURCE", "0");
		}
		String sql="select fid from yc_cost_ProjectApprove where fid='"+id+"' and FisLast='Y' and FSTATE='AUDIT' ";
		List sqllist = iCrudService.executeSqlQuery(sql);
		if(sqllist.size()==0){
			map.put("LAST", "1");//不是已审批最新版数据
			flag=false;
		}else{
			map.put("LAST", "0");
		}
		String consql="select fid from yc_cost_ProjectApprove where fid='"+id+"' and FistoContract='Y' ";
		List conlist = iCrudService.executeSqlQuery(consql);
		if(conlist.size()>0){
			map.put("TOCON", "1");//已生成合同
			flag=false;
		}else{
			map.put("TOCON", "0");
		}
		if(flag){
			boolean isup=true;//判断是否继续更新
			String upid=id;
			while(isup){
				String upsql="update yc_cost_ProjectApprove set FSTATE='CANCEL' where fid='"+upid+"'";//更新状态为作废
				iCrudService.executeSql(upsql);
				String seachsql="select FproAppID from yc_cost_ProjectApprove where fid='"+upid+"'";
				List<Map<String,String>> seachlist = iCrudService.executeSqlQuery(seachsql);//查到修订的上一版本
				if(seachlist.size()>0){
					Map<String, String> idmap = seachlist.get(0);
					upid=idmap.get("FproAppID");
				}else{
					isup=false;
				}
			}
			map.put("CANCEL", "Y");//作废成功
		}else{
			map.put("CANCEL", "N");//作废成功
		}
		

		ArrayList arrayList = new ArrayList();
		arrayList.add(map);
		return R.ok("",arrayList,"0");
	}
}
