package cn.superdesk.uniorder.controller.scheduler;

import cn.superdesk.uniorder.common.enums.common.CommonServiceNoEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.jd.SysQuartzScheduleTaskStatementOfAccountIsPauseEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.jd.SysQuartzScheduleTaskStatementOfAccountRunStateEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.jd.SysQuartzScheduleTaskStatementOfAccountStatementOfAccountTypeEnum;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.lamda.AnLamdaUtils;
import cn.superdesk.uniorder.common.numerical.AnBeanUtils;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import cn.superdesk.uniorder.common.pagination.PageQueryParam;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.rest.response.ResponseResultOuterUtils;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterprise;
import cn.superdesk.uniorder.dao.entity.scheduler.SysQuartzScheduleTaskStatementOfAccount;
import cn.superdesk.uniorder.dao.entity.sys.SysUser;
import cn.superdesk.uniorder.dto.param.scheduler.SysQuartzScheduleTaskStatementOfAccountParam;
import cn.superdesk.uniorder.dto.vo.scheduler.SysQuartzScheduleTaskStatementOfAccountVo;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysEnterpriseDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.scheduler.SysQuartzScheduleTaskStatementOfAccountDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.sys.SysUserDubboConsumerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Description: 定时任务-时刻任务-对账单
 * @Author: linjinyu
 * @Email linjinyu@avic-s.com
 * @CreateDate: 2020-12-17 16:35:26
 * @UpdateUser: linjinyu
 * @UpdateDate: 2020-12-17 16:35:26
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "定时任务-时刻任务-对账单(一键生成对账单)", tags = {"定时任务-时刻任务-对账单(一键生成对账单)"})
@Slf4j
@RestController
@RequestMapping("/sysQuartzScheduleTaskStatementOfAccount")
public class SysQuartzScheduleTaskStatementOfAccountController extends BaseController {


	@Autowired
	private SysQuartzScheduleTaskStatementOfAccountDubboConsumerService sysQuartzScheduleTaskStatementOfAccountDubboConsumerService;

	@Autowired
	private SysUserDubboConsumerService       sysUserDubboConsumerService;
	@Autowired
	private SysEnterpriseDubboConsumerService sysEnterpriseDubboConsumerService;

	@ApiOperation(value = "分页查询")
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public R<List<SysQuartzScheduleTaskStatementOfAccountVo>> pageQuerySysQuartzScheduleTaskStatementOfAccounts(@RequestBody PageQueryParam param) {

		log.info("pageQuerySysQuartzScheduleTaskStatementOfAccount:\n{}", AnJsonUtils.toJson(param));

		R<List<SysQuartzScheduleTaskStatementOfAccountVo>> result     = new R<>();
		R<List<SysQuartzScheduleTaskStatementOfAccount>>   resultTemp = new R<>();

		// TODO 参数合法性判定

		resultTemp = sysQuartzScheduleTaskStatementOfAccountDubboConsumerService.pageQuery(param.getConditions(), param.getPageNo(), param.getPageSize());

		List<SysQuartzScheduleTaskStatementOfAccountVo> resultVoList = new ArrayList<>();
		List<SysQuartzScheduleTaskStatementOfAccount>   resultList   = resultTemp.getData();


		List<Long> sysUserIds           = new ArrayList<>();
		List<Long> sysUserCreateUserIds = resultList.stream().filter(o -> null != o.getCreateUserId()).filter(AnLamdaUtils.distinctByKey(o -> o.getCreateUserId())).map(o -> o.getCreateUserId()).collect(Collectors.toList());
		List<Long> sysUserUpdateUserIds = resultList.stream().filter(o -> null != o.getUpdateUserId()).filter(AnLamdaUtils.distinctByKey(o -> o.getUpdateUserId())).map(o -> o.getUpdateUserId()).collect(Collectors.toList());

		if (AnCollectionUtils.isNotEmpty(sysUserCreateUserIds)) {
			sysUserIds.addAll(sysUserCreateUserIds);
		}
		if (AnCollectionUtils.isNotEmpty(sysUserUpdateUserIds)) {
			sysUserIds.addAll(sysUserUpdateUserIds);
		}


		log.info("sysUserIds : {}", AnJsonUtils.toPrettyJson(sysUserIds));

		Map<Long, SysUser> sysUserMap = sysUserDubboConsumerService.convertSysUserIds2MapSysUserId2Entity(sysUserIds);

		List<Long>               outVirtIds          = resultList.stream().filter(o -> null != o.getOutVirtId()).map(SysQuartzScheduleTaskStatementOfAccount::getOutVirtId).distinct().collect(Collectors.toList());
		Map<Long, SysEnterprise> optionSysEnterprise = sysEnterpriseDubboConsumerService.findByOutVirtIdsConvertKV(outVirtIds);

		if (AnCollectionUtils.isNotEmpty(resultList)) {

			for (SysQuartzScheduleTaskStatementOfAccount scheduleTaskStatementOfAccount : resultTemp.getData()) {

				SysQuartzScheduleTaskStatementOfAccountVo vo = AnBeanUtils.copy(scheduleTaskStatementOfAccount, SysQuartzScheduleTaskStatementOfAccountVo.class);

				vo.setStatementOfAccountTypeName(SysQuartzScheduleTaskStatementOfAccountStatementOfAccountTypeEnum.getDesc(vo.getStatementOfAccountType()));
				vo.setIsPauseName(SysQuartzScheduleTaskStatementOfAccountIsPauseEnum.getDesc(vo.getIsPause()));
//				vo.setJobName();
				vo.setRunStateName(SysQuartzScheduleTaskStatementOfAccountRunStateEnum.getDesc(vo.getRunState()));

				vo.setServicesName(CommonServiceNoEnum.getByServiceNo(vo.getServiceNo()).getServiceName());

//				vo.setCreateUserName();fi
				if (null != vo.getCreateUserId() && sysUserMap.get(vo.getCreateUserId()) != null) {
					vo.setCreateUserName(sysUserMap.get(vo.getCreateUserId()).getFullname());
				} else if (null != vo.getCreateUserId() && vo.getCreateUserId().equals(1L)) {
					vo.setCreateUserName("系统");
				}
//				vo.setUpdateUserName();
				if (null != vo.getUpdateUserId() && sysUserMap.get(vo.getUpdateUserId()) != null) {
					vo.setUpdateUserName(sysUserMap.get(vo.getCreateUserId()).getFullname());
				} else if (null != vo.getUpdateUserId() && vo.getUpdateUserId().equals(1L)) {
					vo.setUpdateUserName("系统");
				}

				if (null != optionSysEnterprise.get(scheduleTaskStatementOfAccount.getOutVirtId()) && null != optionSysEnterprise.get(scheduleTaskStatementOfAccount.getOutVirtId())) {
					vo.setOutVirtName(optionSysEnterprise.get(scheduleTaskStatementOfAccount.getOutVirtId()).getEnterpriseName());
				} else {
					vo.setOutVirtName("企业信息异常-不存在");
				}

				resultVoList.add(vo);
			}
			result.setData(resultVoList);
			result.setCurrentPage(resultTemp.getCurrentPage());
			result.setPageSize(resultTemp.getPageSize());
			result.setCount(resultTemp.getCount());
		}

		return result;
	}

	@ApiOperation(value = "按id查询")
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	@ResponseBody
	public R<List<SysQuartzScheduleTaskStatementOfAccount>> getById(@PathVariable("id") long id) {

		R<List<SysQuartzScheduleTaskStatementOfAccount>> result = new R<>();

		// TODO 参数合法性判定

		SysQuartzScheduleTaskStatementOfAccount entity = sysQuartzScheduleTaskStatementOfAccountDubboConsumerService.findSysQuartzScheduleTaskStatementOfAccountById(id);

		List<SysQuartzScheduleTaskStatementOfAccount> data = new ArrayList<>();
		data.add(entity);

		result.setData(data);

		return result;
	}

	@ApiOperation(value = "新增")
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public R<String> addSysQuartzScheduleTaskStatementOfAccount(@RequestBody SysQuartzScheduleTaskStatementOfAccountParam param) {

		log.info("addSysQuartzScheduleTaskStatementOfAccount:\n{}", AnJsonUtils.toJson(param));


		// TODO 参数合法性判定

		sysQuartzScheduleTaskStatementOfAccountDubboConsumerService.addSysQuartzScheduleTaskStatementOfAccount(param);

		return new R<>("200", "操作成功", true);
	}


	@ApiOperation(value = "更新")
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public R<String> updateSysQuartzScheduleTaskStatementOfAccount(@RequestBody SysQuartzScheduleTaskStatementOfAccountParam param) {

		log.info("updateSysQuartzScheduleTaskStatementOfAccount:\n{}", AnJsonUtils.toJson(param));

		sysQuartzScheduleTaskStatementOfAccountDubboConsumerService.updateSysQuartzScheduleTaskStatementOfAccount(param);

		return new R<>("200", "操作成功", true);
	}

	@ApiOperation(value = "删除")
	@RequestMapping(value = "delete/{id}", method = RequestMethod.POST)
	@ResponseBody
	public R<String> deleteSysQuartzScheduleTaskStatementOfAccount(@PathVariable("id") long id) {

		// TODO 参数合法性判定

		sysQuartzScheduleTaskStatementOfAccountDubboConsumerService.deleteSysQuartzScheduleTaskStatementOfAccount(id);

		return new R<>("200", "操作成功", true);
	}

	@ApiOperation(value = "批量删除")
	@RequestMapping(value = "delete_ids", method = RequestMethod.POST)
	@ResponseBody
	public R<String> deleteIdsSysQuartzScheduleTaskStatementOfAccount(@RequestParam(value = "ids") long[] ids) {

		log.info(AnJsonUtils.toJson(ids));

		for (long id : ids) {
			sysQuartzScheduleTaskStatementOfAccountDubboConsumerService.deleteSysQuartzScheduleTaskStatementOfAccount(id);
		}

		return new R<>("200", "操作成功", true);

	}


	/**
	 * 前端单个任务任务是用得这个
	 * http://192.168.6.223:8089/web/sysQuartzScheduleTaskStatementOfAccount/runTask/{id}
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "运行任务")
	@RequestMapping(value = "runTask/{id}", method = RequestMethod.POST)
	@ResponseBody
	public R<String> runTask(@PathVariable("id") long id) {

		SysQuartzScheduleTaskStatementOfAccount entity = sysQuartzScheduleTaskStatementOfAccountDubboConsumerService.findById(id);

		if (null == entity) {
			return ResponseResultOuterUtils.createErrorResult("500", "任务没有找到");
		}

		// TODO 要开启异步 在dubbo实现类上实现了
		sysQuartzScheduleTaskStatementOfAccountDubboConsumerService.runAsyncTaskSysQuartzScheduleTaskStatementOfAccount(getToken(), entity);

		log.info("SysQuartzScheduleTaskStatementOfAccountController call StatementOfAccountDimOrderTask 任务执行");

		// 运行结果待完善(目前没有计划优化)！
		return new R<>("200", "任务已执行,异步任务,结果请等待推送", true);
	}

	/**
	 * http://192.168.1.223:8089/web/sysQuartzScheduleTaskStatementOfAccount/runTask
	 *
	 * @param param
	 * @return
	 */
	@ApiOperation(value = "执行一个任务样例")
	@RequestMapping(value = "runTask", method = RequestMethod.POST)
	@ResponseBody
	public R<String> runTaskSysQuartzScheduleTaskStatementOfAccount(@RequestBody PageQueryParam param) {

		log.info("addSysQuartzScheduleTaskStatementOfAccount:\n{}", AnJsonUtils.toJson(param));

		// TODO 参数合法性判定

		List<SysQuartzScheduleTaskStatementOfAccount> result = sysQuartzScheduleTaskStatementOfAccountDubboConsumerService.getToDoSysQuartzScheduleTaskStatementOfAccountList(param.getPageNo(), param.getPageSize());

		if (AnCollectionUtils.isEmpty(result)) {
			return new R<>("500", "已经没有任务", false);
		}

		sysQuartzScheduleTaskStatementOfAccountDubboConsumerService.runAsyncTaskSysQuartzScheduleTaskStatementOfAccount(getToken(), result.get(0));

		return new R<>("200", "操作成功", true);

	}

}
