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

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.utils.EmployeRoleUtils;
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.entity.TraderApply;
import com.sifang.modules.sunshine.SystemSetting.dao.CrmPlatformEmpDao;
import com.sifang.modules.sunshine.SystemSetting.dao.DepartmentSettingDao;
import com.sifang.modules.sunshine.SystemSetting.dao.SiteInformationDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmDepartment;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmPlatformEmployee;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.setting.entity.CrmSupplySupplier;
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.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.sifang.modules.flowpath.entity.SupplySupplierApply;
import com.sifang.modules.flowpath.dao.SupplySupplierApplyDao;

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

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

	@Autowired
	private SupplySupplierApplyDao supplySupplierApplyDao;

	@Autowired
	private ProcessFlowableService flowableService;

	@Autowired
	TaskService taskService;

	@Autowired
	private DepartmentSettingDao departmentSettingDao;

	@Autowired
	private CrmPlatformEmpDao platformEmpDao;

	@Autowired
	private SiteInformationDao siteInformationDao;
	@Autowired
	private BondApplyDao bondApplyDao;


	public SupplySupplierApply get(String id) {
		return supplySupplierApplyDao.get(id);
	}

	public SupplySupplierApply findBySupplierId(String supplierId){
		return supplySupplierApplyDao.findBySupplierId(supplierId);
	}
	
	public LayuiPage<Record> findApplyPage(LayuiPage<Record> page, Map<String,String> map) {
		User user = UserUtils.getUser();
		if (User.USER_TYPE_WXG.equals(user.getUserType())) {
			//平台人员
			EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
		}
		List<Record> list = supplySupplierApplyDao.findApplyList(page, map,user);
		page.setData(list);
		page.setCount(supplySupplierApplyDao.findApplyCount(map,user));
		return page;
	}
	
	@Transactional(readOnly = false,rollbackFor = Exception.class)
	public void save(SupplySupplierApply apply) {
		User user = UserUtils.getUser();
		CrmDepartment dep = departmentSettingDao.get(user.getDepartmentId());
		if(dep ==null){
			throw new BusinessException("当前用户无操作权限");
		}
		String userId = "";
		if(StringUtil.isNotBlank(apply.getSupplierId())){
			userId = Db.queryStr("SELECT user_id FROM `crm_supply_supplier` WHERE id=?",apply.getSupplierId());
			if (siteInformationDao.getExistsLoginNameNew(userId,apply.getLoginName())) {
				throw new BusinessException("登录账号已存在！");
			}
		}else if (siteInformationDao.getExistsLoginName(apply.getLoginName())) {
			throw new BusinessException("登录账号已存在！");
		}


		Date date = new Date();

		//获取当前业务人员信息
		CrmPlatformEmployee emp = platformEmpDao.findByUserId(user.getId());
		String userName = emp.getName();
		boolean fg=false;
		if(StringUtil.isNotBlank(apply.getId())){
			SupplySupplierApply oldApply = supplySupplierApplyDao.get(apply.getId());
			if(BondApplyConstant.APPLYSTATUS_THREE.equals(oldApply.getStatus())){  //已完成的编辑 后要从新申请审核；仅仅编辑了备注时，不需要重新审核；
				//判断一下修改了哪些
                fg=checkEditWhere(oldApply,apply);
				logger.info(">>>>>>>>>>>>>>saveSupply fg:{} ",fg);
			} else {
				apply.setStatus("1");
			}
			apply.setTaskId(oldApply.getTaskId());
			apply.setTaskName(oldApply.getTaskName());
			apply.setProcessInstanceId(oldApply.getProcessInstanceId());
			//修改
			apply.setUpdateBy(user.getId());
			apply.setUpdater(userName);
			apply.setUpdateTime(date);
			apply.setId(oldApply.getId());
			apply.setDepartmentId(oldApply.getDepartmentId());
			apply.setDepartmentName(oldApply.getDepartmentName());
			apply.setLoginName(oldApply.getLoginName());
			apply.setPassword(oldApply.getPassword());
			apply.setCreateBy(oldApply.getCreateBy());
			apply.setCreator(oldApply.getCreator());
			apply.setCreateTime(oldApply.getCreateTime());
			apply.setProcessDefId(oldApply.getProcessDefId());
			apply.setTaskName(oldApply.getTaskName());
			apply.setTaskId(oldApply.getTaskId());
			apply.setProcessInstanceId(oldApply.getProcessInstanceId());
			apply.setSupplierId(oldApply.getSupplierId());
			supplySupplierApplyDao.getSession().clear();
		}else{
			apply.setId(IdGen.uuid());
			apply.setDepartmentId(user.getDepartmentId());
			apply.setDepartmentName(dep.getName());
			apply.setCreateBy(user.getId());
			apply.setCreator(emp.getName());
			apply.setCreateTime(date);
		}
		if(StringUtil.isNotBlank(apply.getLicenseImg()) && apply.getLicenseImg().startsWith(",")){
            apply.setLicenseImg(apply.getLicenseImg().substring(1));
		}
		if(StringUtil.isBlank(apply.getStatus())){
			apply.setStatus("1");
		}
		//
		if("1".equals(apply.getStatus())&& StringUtil.isBlank(apply.getProcessInstanceId())){
			//提交流程
			Record rd = FormUtils.getdefLatest(FormUtils.SUPPLIER_ADMISSION_APPLICATION);
			if(rd == null){
				throw  new RuntimeException("流程未定义，不可发布申请");
			}
			//启动流程
			String processName="供应商准入申请-"+user.getUserName()+'-'+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"("+apply.getName()+")";
			String processInstanceId=flowableService.startProcessFlowable2(user,apply.getId(),rd, FormUtils.SUPPLIER_ADMISSION_APPLICATION,date,userName,apply.getRemarks(),processName,apply.getProvince(),apply.getCity());
			apply.setProcessInstanceId(processInstanceId);
			apply.setProcessDefId(rd.getStr("id"));
			String taskName=FormUtils.getOneStepTaskName(rd.getStr("id"));
			apply.setTaskName(taskName);
			apply.setOperateUserIds(user.getId()+","+rd.getStr("oneAuditUseId"));
		}else if(fg){  //已完成的编辑 后要从新申请审核；仅仅编辑了备注时，不需要重新审核；
            if(fg){
				//提交流程
				Record rd = FormUtils.getdefLatest(FormUtils.SUPPLIER_ADMISSION_APPLICATION);
				if(rd == null){
					throw  new RuntimeException("流程未定义，不可发布申请");
				}
				//启动流程
				String processName="供应商准入申请-"+user.getUserName()+'-'+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"("+apply.getName()+")";
				String processInstanceId=flowableService.startProcessFlowable2(user,apply.getId(),rd, FormUtils.SUPPLIER_ADMISSION_APPLICATION,date,userName,apply.getRemarks(),processName,apply.getProvince(),apply.getCity());
				apply.setProcessInstanceId(processInstanceId);
				apply.setProcessDefId(rd.getStr("id"));
				apply.setStatus("1");
				String taskName=FormUtils.getOneStepTaskName(rd.getStr("id"));
				apply.setTaskName(taskName);
			}
		}else if(StringUtil.isNotBlank(apply.getProcessInstanceId()) && !BondApplyConstant.APPLYSTATUS_THREE.equals(apply.getStatus())){
			Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
			flowableService.approveTask2(task,"编辑后提交",apply.getId(),user, FormUtils.SUPPLIER_ADMISSION_APPLICATION);

		}
		/*supplySupplierApplyDao.getSession().clear();*/
		supplySupplierApplyDao.save(apply);
	}

	public boolean checkEditWhere(SupplySupplierApply oldApply,SupplySupplierApply newSupply){
        if(!oldApply.equals(newSupply)){
           return true;
		}
		return false;
	}
	
	@Transactional(readOnly = false,rollbackFor = Exception.class)
	public void delete(String id) {
		SupplySupplierApply apply=supplySupplierApplyDao.get(id);
		if(!"0".equals(apply.getStatus())){
			throw new BusinessException("当前数据不满足删除条件");
		}
		User user = UserUtils.getUser();
		String userName= CrmUtils.getUserXM(user);
		apply.setStatus(BondApplyConstant.APPLYSTATUS_FOUR);
		supplySupplierApplyDao.save(apply);
		//删除流程
		flowableService.deleteApplication(apply.getId(),apply.getProcessInstanceId(),userName,apply.getStatus(),FormUtils.SUPPLIER_ADMISSION_APPLICATION);
	}


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

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

	}
	
}
