/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.modules.apply.operationSiteApply.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jodd.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.flow.demo.leave.service.impl.LeaveServiceImpl;
import org.springblade.modules.apply.operationSiteApply.pojo.dto.OperationSiteApplyDTO;
import org.springblade.modules.apply.operationSiteApply.pojo.entity.OperationSiteApplyEntity;
import org.springblade.modules.apply.operationSiteApply.pojo.vo.OperationSiteApplyVO;
import org.springblade.modules.apply.operationSiteApply.excel.OperationSiteApplyExcel;
import org.springblade.modules.apply.operationSiteApply.mapper.OperationSiteApplyMapper;
import org.springblade.modules.apply.operationSiteApply.service.IOperationSiteApplyService;
import org.springblade.modules.flowable.processForm.mapper.ProcessDefAuditStepMapper;
import org.springblade.modules.flowable.processForm.mapper.ProcessDefMapper;
import org.springblade.modules.flowable.processForm.pojo.vo.ProcessDefReq;
import org.springblade.modules.flowable.processForm.utils.FormUtils;
import org.springblade.modules.operation.pojo.entity.OperationSiteEntity;
import org.springblade.modules.operation.service.impl.OperationSiteServiceImpl;
import org.springblade.modules.system.pojo.entity.Region;
import org.springblade.modules.system.service.IRegionService;
import org.springblade.modules.system.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 运维商准入申请表 服务实现类
 *
 * @author lzp
 * @since 2024-08-09
 */
@Service
public class OperationSiteApplyServiceImpl extends ServiceImpl<OperationSiteApplyMapper, OperationSiteApplyEntity> implements IOperationSiteApplyService {
	@Autowired
	UserServiceImpl userService;

	@Autowired
	ProcessDefMapper processDefMapper;
	@Autowired
	ProcessDefAuditStepMapper stepMapper;

	@Autowired
	LeaveServiceImpl leaveService;

	@Autowired
	TaskService taskService;

	@Autowired
	OperationSiteServiceImpl siteService;

	@Autowired
	private  IRegionService regionService;
	@Override
	public IPage<OperationSiteApplyVO> selectOperationSiteApplyPage(IPage<OperationSiteApplyVO> page, OperationSiteApplyDTO operationSiteApply) {
		BladeUser user = AuthUtil.getUser();
		operationSiteApply.setUserId(user.getUserId());
		return page.setRecords(baseMapper.selectOperationSiteApplyPage(page, operationSiteApply));
	}

	@Override
	public boolean saveApply(OperationSiteApplyEntity entry) {
		BladeUser user = AuthUtil.getUser();

		Date date = new Date();

		if(StringUtil.isBlank(entry.getSiteId())){
			String loginName = entry.getLoginName().trim();
			entry.setLoginName(loginName);
			if(userService.userByAccount(user.getTenantId(), entry.getLoginName()) != null){
				throw new ServiceException("登录账号已存在！");
			}
			if(getBaseMapper().findApplyLoginName(loginName,entry.getId())>0){
				throw new ServiceException("登录账号已存在！");
			}

		}
		Region region = new Region();
		if(StringUtil.isBlank(entry.getProvinceCode())){
			region.setProvinceName(entry.getProvince());
			region.setRegionLevel(1);
			Region detail = regionService.getOne(Condition.getQueryWrapper(region));
			if(detail!= null){
				entry.setProvinceCode(detail.getProvinceCode());
			}
		}
		if(StringUtil.isBlank(entry.getCityCode())){
			region.setCityName(entry.getCity());
			region.setRegionLevel(2);
			Region citys = regionService.getOne(Condition.getQueryWrapper(region));
			if(citys!= null){
				entry.setCityCode(citys.getCityCode());
			}
		}

		if(StringUtil.isBlank(entry.getAreaCode())){
			region.setDistrictName(entry.getArea());
			region.setRegionLevel(3);
			Region distr = regionService.getOne(Condition.getQueryWrapper(region));
			if(distr!= null){
				entry.setAreaCode(distr.getDistrictCode());
			}
		}

		entry.setStatus("1");
		if(StringUtil.isBlank(entry.getId())){
			entry.setDepartmentId(user.getDeptId());
			entry.setDepartmentName(user.getNickName());
			entry.setCreator(user.getNickName());
			entry.setCreateBy(user.getUserId().toString());
			entry.setCreateTime(date);

			entry.setId(IdUtil.randomUUID().replaceAll("-", ""));
			//提交流程
			ProcessDefReq rd = processDefMapper.getDefByFormId(FormUtils.AGENT_ADMISSION_APPLICATION);
			if(rd == null){
				throw  new RuntimeException("流程未定义，不可发布申请");
			}
			//启动流程
			String processName="代理商准入申请-"+user.getUserName()+'-'+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"("+entry.getName()+")";
			String processInstanceId=leaveService.startProcessFlowable(entry.getId(),rd, FormUtils.AGENT_ADMISSION_APPLICATION,date,user.getNickName(),entry.getRemarks(),processName,entry.getProvince(),entry.getCity());
			entry.setProcessInstanceId(processInstanceId);
			entry.setProcessDefId(rd.getId());
			String taskName=stepMapper.getOneStepTaskName(rd.getId());
			entry.setTaskName(taskName);
			entry.setOperateUserIds(user.getUserId().toString());
			return save(entry);
		}else if(StringUtil.isNotBlank(entry.getProcessInstanceId())){
			boolean upche = updateById(entry);
			Task task = taskService.createTaskQuery().processInstanceId(entry.getProcessInstanceId()).taskAssignee(user.getUserId().toString()).singleResult();
			leaveService.approveTask(task,"编辑后提交",entry.getId(),user, FormUtils.AGENT_ADMISSION_APPLICATION);
			return upche;
		}
		return false;
	}

	/**
	 * 审核通过
	 */
	@Override
	public boolean examineSiteApply(String id, String taskId, String content){
		log.debug(">>>>>>>>>>>>>examineDistributionGoodsApprove  id:"+id+",task:"+taskId);
		BladeUser user = AuthUtil.getUser();
		OperationSiteApplyEntity apply=getById(id);
		apply.setContent(content);
		boolean check = updateById(apply);
		Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getUserId().toString()).singleResult();
		leaveService.approveTask(task,content,apply.getId(),user, FormUtils.AGENT_ADMISSION_APPLICATION);
		return check;
	}

	@Override
	public boolean deleteSiteApply(String id) {
		OperationSiteApplyEntity apply=getById(id);
		if("0".equals(apply.getStatus()) && "2".equals(apply.getStatus())){
			throw new ServiceException("当前信息不满足删除条件");
		}
		apply.setStatus("4");

		BladeUser user = AuthUtil.getUser();
		//删除流程
		if(StringUtil.isNotBlank(apply.getProcessInstanceId())){
			leaveService.deleteApplication(apply.getId(),apply.getProcessInstanceId(),user.getUserName(),"2",FormUtils.AGENT_ADMISSION_APPLICATION);
		}
		return updateById(apply);
	}

	@Override
	public boolean rejectTask(String id, String taskId, String content) {
		//log.info(">>>>>>>>>>>>>rejectTask  id:{},task:{}",id,taskId);
		BladeUser user = AuthUtil.getUser();
		OperationSiteApplyEntity apply=getById(id);
		apply.setContent(content);
		boolean check =updateById(apply);
		Task task=taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getUserId().toString()).singleResult();;
		leaveService.rejectTask(task,content,id,user,FormUtils.AGENT_ADMISSION_APPLICATION,apply.getCreateBy());
		return check;
	}


	@Override
	public List<OperationSiteApplyExcel> exportOperationSiteApply(Wrapper<OperationSiteApplyEntity> queryWrapper) {
		List<OperationSiteApplyExcel> operationSiteApplyList = baseMapper.exportOperationSiteApply(queryWrapper);

		return operationSiteApplyList;
	}

	public String getLastAuditStep(String depId){
		return stepMapper.getLastAuditStep(depId);
	}

}
