/**
 */
package com.sifang.modules.flowpath.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.flowable.service.ProcessFlowableService;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.flowpath.constant.BondApplyConstant;
import com.sifang.modules.flowpath.dao.BondApplyDao;
import com.sifang.modules.flowpath.dao.SupplyWarehouseApplyDao;
import com.sifang.modules.flowpath.entity.SupplyWarehouseApply;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.setting.dao.CrmSupplyWarehouseDao;
import com.sifang.modules.supply.setting.entity.CrmSupplyWarehouse;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.entity.Ascription;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 代理商审批信息Service
 * @author lzp
 * @version 
 */
@Component
@Transactional(readOnly = true)
public class SupplyWarehouseApplyService extends BaseService {

	@Autowired
	private SupplyWarehouseApplyDao supplyWarehouseApplyDao;

	@Autowired
	private ProcessFlowableService flowableService;

	@Autowired
	TaskService taskService;

	@Autowired
	private BondApplyDao bondApplyDao;
	@Autowired
	private CrmSupplyWarehouseDao crmSupplyWarehouseDao;


	public SupplyWarehouseApply get(String id) {
		return supplyWarehouseApplyDao.get(id);
	}






	
	public LayuiPage<Record> findApplyPage(LayuiPage<Record> page, Map<String,String> map) {

		User user = UserUtils.getUser();
		List<Record> list = supplyWarehouseApplyDao.findApplyList(page, map,user);
		page.setData(list);
		page.setCount(supplyWarehouseApplyDao.findApplyCount(map,user));
		return page;
	}


	public void save(SupplyWarehouseApply apply){
		supplyWarehouseApplyDao.save(apply);
	}

	//这个是走审批流程的，暂不用
	@Transactional(readOnly = false,rollbackFor = Exception.class)
	public void saveWarehouseApply(SupplyWarehouseApply apply) {
		User user = UserUtils.getUser();

		if(!StringUtil.equalsAny(user.getUserType(),"6","7")){
			throw new BusinessException("当前用户无操作权限");
		}

		Date date = new Date();

		String userName =user.getUserName();
		boolean fg=false;
		if(StringUtil.isNotBlank(apply.getId())){
			SupplyWarehouseApply oldApply = supplyWarehouseApplyDao.get(apply.getId());
			if(BondApplyConstant.APPLYSTATUS_THREE.equals(oldApply.getStatus())){  //已完成的编辑 后要从新申请审核；仅仅编辑了备注时，不需要重新审核；
				//判断一下修改了哪些
                fg=checkEditWhere(oldApply,apply);
				logger.info(">>>>>>>>>>>>>>saveWarehouseApply fg:{} ",fg);
			} else {
				apply.setStatus("1");
			}
			apply.setTaskId(oldApply.getTaskId());
			apply.setTaskName(oldApply.getTaskName());
			apply.setProcessInstanceId(oldApply.getProcessInstanceId());
			//修改
			apply.setUpdater(userName);
			apply.setUpdateTime(date);
		//	apply.setId(oldApply.getId());
			apply.setCreator(oldApply.getCreator());
			apply.setCreateBy(oldApply.getCreateBy());
			apply.setCreateTime(oldApply.getCreateTime());
			apply.setProcessDefId(oldApply.getProcessDefId());
			apply.setTaskName(oldApply.getTaskName());
			apply.setTaskId(oldApply.getTaskId());
			apply.setProcessInstanceId(oldApply.getProcessInstanceId());
			apply.setNumber(oldApply.getNumber());
			apply.setWarehouseId(oldApply.getWarehouseId());
			apply.setType(oldApply.getType());
			apply.setStatus(oldApply.getStatus());
			apply.setAscriptionId(oldApply.getAscriptionId());
			apply.setAscriptionName(oldApply.getAscriptionName());
			supplyWarehouseApplyDao.getSession().clear();
		}else{
			Ascription ascription=CrmUtils.getAscription();
			apply.setId(IdGen.uuid());
			apply.setCreator(userName);
			apply.setCreateTime(date);
			apply.setType("2");
			apply.setNumber(PlantformUtils.getOrderNumber());
			apply.setCreateBy(user.getId());
			apply.setAscriptionName(ascription.getAscriptionName());
			apply.setAscriptionId(ascription.getAscriptionId());
		}

		if(StringUtil.isBlank(apply.getStatus())){
			apply.setStatus("1");
		}
		//
		if("1".equals(apply.getStatus())&& StringUtil.isBlank(apply.getProcessInstanceId())){
			//提交流程
			Record rd = FormUtils.getdefLatest(FormUtils.WAREHOUSE_APPLY);
			if(rd == null){
				throw  new RuntimeException("流程未定义，不可发布申请");
			}
			//启动流程
			String processName="仓库申请-"+user.getUserName()+'-'+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"("+apply.getAscriptionName()+")";
			String processInstanceId=flowableService.startProcessFlowable(user,apply.getId(),rd, FormUtils.WAREHOUSE_APPLY,date,userName,apply.getRemarks(),processName,apply.getAscriptionId());
			apply.setProcessInstanceId(processInstanceId);
			apply.setProcessDefId(rd.getStr("id"));

			apply.setOperateUserIds(user.getId()+","+rd.getStr("oneAuditUseId"));
			String taskName=FormUtils.getOneStepTaskName(rd.getStr("id"));
			apply.setTaskName(taskName);
			supplyWarehouseApplyDao.save(apply);
		}else if(fg){  //已完成的编辑 后要从新申请审核；仅仅编辑了备注时，不需要重新审核；
            if(fg){
				//提交流程
				Record rd = FormUtils.getdefLatest(FormUtils.WAREHOUSE_APPLY);
				if(rd == null){
					throw  new RuntimeException("流程未定义，不可发布申请");
				}
				//启动流程
				String processName="仓库申请-"+user.getUserName()+'-'+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"("+apply.getAscriptionName()+")";
				String processInstanceId=flowableService.startProcessFlowable(user,apply.getId(),rd, FormUtils.WAREHOUSE_APPLY,date,userName,apply.getRemarks(),processName,apply.getAscriptionId());
				apply.setProcessInstanceId(processInstanceId);
				apply.setProcessDefId(rd.getStr("id"));
				apply.setStatus("1");
				apply.setOperateUserIds(user.getId()+","+rd.getStr("oneAuditUseId"));
				String taskName=FormUtils.getOneStepTaskName(rd.getStr("id"));
				apply.setTaskName(taskName);
			}
			Object merge = supplyWarehouseApplyDao.getSession().merge(apply);
			supplyWarehouseApplyDao.save((SupplyWarehouseApply) merge);
		}else if(StringUtil.isNotBlank(apply.getProcessInstanceId()) && !BondApplyConstant.APPLYSTATUS_THREE.equals(apply.getStatus())){
			supplyWarehouseApplyDao.save(apply);
			Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
			flowableService.approveTask2(task,"编辑后提交",apply.getId(),user, FormUtils.WAREHOUSE_APPLY);

		}

	}


	@Transactional(readOnly = false,rollbackFor = Exception.class)
	public void saveWarehouse(SupplyWarehouseApply req) {
		User user = UserUtils.getUser();

		if(!StringUtil.equalsAny(user.getUserType(),"6","7")){
			throw new BusinessException("当前用户无操作权限");
		}
		Date date = new Date();
		CrmSupplyWarehouse warehouse;

		if(StringUtil.isBlank(req.getId())){
			Ascription ascription=CrmUtils.getAscription();
			//判断是否有在使用的仓库
			warehouse=new CrmSupplyWarehouse();
			warehouse.setType("2");
			warehouse.setNumber(CrmUtils.no());
			warehouse.setCreateTime(date);
			warehouse.setCreator(user.getId());
			warehouse.setAscriptionId(ascription.getAscriptionId());
			warehouse.setAscriptionName(ascription.getAscriptionName());
		}else{
			warehouse=crmSupplyWarehouseDao.get(req.getId());
			if(warehouse==null){
				throw new BusinessException("该仓库不存在！");
			}
			warehouse.setUpdateTime(date);
			warehouse.setModifier(user.getId());
		}
		warehouse.setName(req.getName());
		boolean checkName=checkWarehouseName(warehouse.getName(),warehouse.getId(),warehouse.getAscriptionId());
		if(checkName){
			throw new BusinessException("仓库名称已存在，请问重复添加！");
		}
		warehouse.setPersonInCharge(req.getPersonInCharge());
		warehouse.setMobile(req.getMobile());
		warehouse.setProvince(req.getProvince());
		warehouse.setCity(req.getCity());
		warehouse.setArea(req.getArea());
		warehouse.setAddress(req.getAddress());
		warehouse.setImgs(req.getImgs());
		warehouse.setQualificationsImgs(req.getQualificationsImgs());
		warehouse.setLeaseImg(req.getLeaseImg());
		warehouse.setEvidence(req.getEvidence());
		warehouse.setAttribute(req.getAttribute());
		warehouse.setRemarks(req.getRemarks());
		crmSupplyWarehouseDao.save(warehouse);
	}

	//判断仓库名称
	public boolean checkWarehouseName(String name,String id,String ascriptionId){
		StringBuffer sb=new StringBuffer();
		sb.append("  SELECT COUNT(id) FROM `crm_supply_warehouse` w WHERE w.status='0' AND w.ascription_id=? AND w.name=? ");
		if(StringUtil.isNotBlank(id)){
			sb.append("  AND id<>'"+id+"' ");
		}
		Long count=Db.queryLong(sb.toString(),ascriptionId,name);
		return count>0?true:false;
	}



	@Transactional(readOnly = false,rollbackFor = Exception.class)
	public void saveWarehouseApplyFromWareEdit(CrmSupplyWarehouse req) {
		CrmSupplyWarehouse warehouse=crmSupplyWarehouseDao.get(req.getId());
		if(warehouse==null){
			throw new BusinessException("该仓库不存在！");
		}

		User user = UserUtils.getUser();

		if(!StringUtil.equalsAny(user.getUserType(),"6","7")){
			throw new BusinessException("当前用户无操作权限");
		}

		Date date = new Date();

		String userName =user.getUserName();

		SupplyWarehouseApply apply = new SupplyWarehouseApply();
		apply.setWarehouseId(warehouse.getId());

		apply.setName(req.getName());
		apply.setMobile(req.getMobile());
		apply.setPersonInCharge(req.getPersonInCharge());
		apply.setProvince(req.getProvince());
		apply.setCity(req.getCity());
		apply.setArea(req.getArea());
		apply.setAddress(req.getAddress());
		apply.setRemarks(req.getRemarks());
		apply.setImgs(req.getImgs());
		apply.setQualificationsImgs(req.getQualificationsImgs());

		apply.setId(IdGen.uuid());
		apply.setAttribute(warehouse.getAttribute());
		apply.setEvidence(warehouse.getEvidence());
		apply.setImgs(warehouse.getImgs());
		apply.setCreator(userName);
		apply.setCreateTime(date);
		apply.setType("2");
		apply.setNumber(PlantformUtils.getOrderNumber());
		apply.setCreateBy(user.getId());
		apply.setAscriptionName(warehouse.getAscriptionName());
		apply.setAscriptionId(warehouse.getAscriptionId());
		apply.setStatus("1");
		//
		if("1".equals(apply.getStatus())&& StringUtil.isBlank(apply.getProcessInstanceId())){
			//提交流程
			Record rd = FormUtils.getdefLatest(FormUtils.WAREHOUSE_APPLY);
			if(rd == null){
				throw  new RuntimeException("流程未定义，不可发布申请");
			}
			//启动流程
			String processName="仓库申请-"+user.getUserName()+'-'+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"("+apply.getAscriptionName()+")";
			String processInstanceId=flowableService.startProcessFlowable(user,apply.getId(),rd, FormUtils.WAREHOUSE_APPLY,date,userName,apply.getRemarks(),processName,apply.getAscriptionId());
			apply.setProcessInstanceId(processInstanceId);
			apply.setProcessDefId(rd.getStr("id"));
			apply.setOperateUserIds(user.getId()+","+rd.getStr("oneAuditUseId"));
			String taskName=FormUtils.getOneStepTaskName(rd.getStr("id"));
			apply.setTaskName(taskName);
			logger.info(">>>>>>>>>>>>>>>>>saveWarehouseApplyFromWareEdit  processInstanceId:{},taskName:{}",processInstanceId,taskName);
		}
		supplyWarehouseApplyDao.save(apply);
	}
	public boolean checkEditWhere(SupplyWarehouseApply oldApply,SupplyWarehouseApply newSupply){
        if(!oldApply.equals(newSupply)){
           return true;
		}
		return false;
	}
	
	@Transactional(readOnly = false,rollbackFor = Exception.class)
	public void delete(String id) {
		SupplyWarehouseApply apply=supplyWarehouseApplyDao.get(id);
		if(!"0".equals(apply.getStatus())){
			throw new BusinessException("当前数据不满足删除条件");
		}
		User user = UserUtils.getUser();
		String userName= CrmUtils.getUserXM(user);
		apply.setStatus(BondApplyConstant.APPLYSTATUS_FOUR);
		supplyWarehouseApplyDao.save(apply);
		//删除流程
		flowableService.deleteApplication(apply.getId(),apply.getProcessInstanceId(),userName,apply.getStatus(),FormUtils.WAREHOUSE_APPLY);
	}


	/**
	 * 审核通过
	 */
	public void examineWarehouseApply(String id,String taskId,String content){
		logger.info(">>>>>>>>>>>>>examineDistributionGoodsApprove  id:{},task:{}",id,taskId);
		User user = UserUtils.getUser();
		SupplyWarehouseApply apply=supplyWarehouseApplyDao.get(id);
		Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
		flowableService.approveTask2(task,content,apply.getId(),user, FormUtils.WAREHOUSE_APPLY);
	}

	/**
	 * 驳回
	 */
	public void rejectTask(String id,String taskId,String content){
		logger.info(">>>>>>>>>>>>>rejectTask  id:{},task:{}",id,taskId);
		User user = UserUtils.getUser();
		SupplyWarehouseApply apply=supplyWarehouseApplyDao.get(id);
		apply.setContent(content);
		supplyWarehouseApplyDao.save(apply);
		Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
		flowableService.rejectTask2(task,content,id,user,FormUtils.WAREHOUSE_APPLY,apply.getCreateBy());
	}
	
}
