package com.cyksj.web.controller.manage.corp;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.corp.CorpMsgBulkTaskCategoryMapper;
import com.cyksj.mapper.corp.CorpTagMapper;
import com.cyksj.mapper.manage.coupon.CouponMapper;
import com.cyksj.model.dto.CornMetaDto;
import com.cyksj.model.entity.CorpMsgBulkTask;
import com.cyksj.model.entity.CorpMsgBulkTaskCategory;
import com.cyksj.model.entity.CorpMsgBulkTaskRecord;
import com.cyksj.model.entity.CorpTag;
import com.cyksj.model.excel.ExcelCorpMsgBulkTaskSendRecordData;
import com.cyksj.model.request.CorpActiveBulkMsg;
import com.cyksj.model.request.corp.Attachments;
import com.cyksj.model.views.CorpMsgBulkTaskCorpFollowSendRecordView;
import com.cyksj.model.views.CorpMsgBulkTaskSendRecordView;
import com.cyksj.service.corp.CorpMsgBulkTaskService;
import com.cyksj.web.util.EasyExcelUtils;
import com.cyksj.xxljob.XxlJobUtil;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/*
 *项目名: netflix
 *文件名: CorpMsgBulkTaskController
 *创建者: JavaZou
 *创建时间:2023/6/21 9:31
 */
@RestController
@RequestMapping("/manage/corpMsgBulkTask")
@RequiredArgsConstructor
public class CorpMsgBulkTaskController {

	private final CorpMsgBulkTaskService corpMsgBulkTaskService;

	private final BeanSearcher beanSearcher;

	private final CouponMapper couponMapper;

	private final HttpServletRequest request;

	private final CorpTagMapper corpTagMapper;

	private final CorpMsgBulkTaskCategoryMapper corpMsgBulkTaskCategoryMapper;


	/**
	 * 新建群发
	 */
	@PostMapping("/post")
	public Result<String> saveCorpMsgBulkTask(@RequestBody @Validated CorpMsgBulkTask corpMsgBulkTask) throws Exception {
		corpMsgBulkTaskService.saveOrUpdateMsgBulkTask(corpMsgBulkTask);
		return GatewayResponse.SUCCESS.newBuilder().toResult("新建群发成功");
	}


	/**
	 * 编辑群发
	 */
	@PutMapping("/put")
	public Result<String> updateCorpMsgBulkTask(@RequestBody @Validated CorpMsgBulkTask corpMsgBulkTask) throws Exception {
		corpMsgBulkTaskService.saveOrUpdateMsgBulkTask(corpMsgBulkTask);
		return GatewayResponse.SUCCESS.newBuilder().toResult("修改群发成功");
	}

	/**
	 * 群发列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<CorpMsgBulkTask>> getCorpMsgBulkTaskList(String[] tagIds) {
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		if (tagIds != null && tagIds.length > 0) {
			List<String> collect = corpTagMapper.selectList(Wrappers.lambdaQuery(CorpTag.class)
					.in(CorpTag::getId, tagIds)).stream().map(CorpTag::getTagId).collect(Collectors.toList());
			if (CollUtil.isNotEmpty(collect)) {
				StringBuilder sb = new StringBuilder();
				for (String tagId : collect) {
					sb.append("\"" + tagId + "\"");
					sb.append(",");
					String substring = sb.substring(0, sb.lastIndexOf(","));
					builder.put("tag_id", String.format("id in (select distinct task_id from corp_msg_bulk_task_tag_relation where tag_id in(%s))", substring));
				}
			}
		}
		SearchResult<CorpMsgBulkTask> search = beanSearcher.search(CorpMsgBulkTask.class, builder
				.field(CorpMsgBulkTask::getDeleted, true)
				.orderBy(CorpMsgBulkTask::getId).desc()
				.build());
		search.getDataList().forEach(data -> {
			try {
				if (StrUtil.isNotBlank(data.getChooseTagStr())) {
					List<String> tagList = Jsons.parseList(data.getChooseTagStr(), String.class);
					data.setTagSize(tagList.size());
				}

				if (StringUtils.isNotBlank(data.getCorn())) {
					String[] s = data.getCorn().split(" ");
					CornMetaDto cornMetaDto = new CornMetaDto();
					cornMetaDto.setHour(s[2]);
					cornMetaDto.setDay(StringPool.ASTERISK.equals(s[3]) ? "" : s[3]);
					cornMetaDto.setMonth(StringPool.ASTERISK.equals(s[4]) ? "" : s[4]);
					cornMetaDto.setWeek(StringPool.QUESTION_MARK.equals(s[5]) ? "" : s[5]);
					data.setCornDto(cornMetaDto);
				}
				if (StrUtil.isNotBlank(data.getAttachmentsStr())) {
					data.setAttachments(Jsons.parseList(data.getAttachmentsStr(), Attachments.class));
				}
				if (StrUtil.isNotEmpty(data.getCouponIds())) {
					List<Long> couponIds = Jsons.parseList(data.getCouponIds(), Long.class);
					data.setCouponName(couponMapper.getCouponNameByIds(couponIds));
				}
				if (data.getCategory() != null && data.getCategory() > 0) {
					Optional.ofNullable(corpMsgBulkTaskCategoryMapper.selectById(data.getCategory())).ifPresent(e -> data.setCategoryName(e.getName()));
				}
			} catch (Exception e) {

			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 标签详情
	 */
	@GetMapping("/get/tag/detail/{id}")
	public Result<Map<String, List<CorpTag>>> getTagDetail(@PathVariable Long id) throws Exception {
		Map<String, List<CorpTag>> collect = corpMsgBulkTaskService.getTagDetail(id);
		return GatewayResponse.SUCCESS.newBuilder().toResult(collect);
	}

	/**
	 * 删除群发
	 */
	@DeleteMapping("/delete/{id}")
	public Result<String> deleteBulkTaskList(@PathVariable Long id) throws Exception {
		CorpMsgBulkTask task = corpMsgBulkTaskService.getById(id);
		if (task == null || !task.getDeleted()) {
			throw BusinessRuntimeException.getInstance("群发任务不存在");
		}
		task.setDeleted(!task.getDeleted());
		corpMsgBulkTaskService.updateById(task);

		if (task.getJobId() != null) {
			XxlJobUtil.deleteJob(task.getJobId());
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 群发记录
	 */
	@GetMapping("/get/sendRecord/{id}")
	public Result<SearchResult<CorpMsgBulkTaskSendRecordView>> getSendRecord(@PathVariable Long id, Long startTime, Long endTime) {
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		builder.put("task_id", String.format("task_id = %s", id));
		String time = StrUtil.EMPTY;
		if (startTime != null) {
			time += String.format(" and created_time >= '%s'", DateTime.of(startTime));
		}
		if (endTime != null) {
			time += String.format(" and created_time < '%s'", DateTime.of(endTime));
		}
		if (StrUtil.isNotEmpty(time)) {
			builder.put("time", time);
		}
		SearchResult<CorpMsgBulkTaskSendRecordView> search = beanSearcher.search(CorpMsgBulkTaskSendRecordView.class, builder
				.orderBy(CorpMsgBulkTaskSendRecordView::getCreateTime).desc()
				.build());
		search.getDataList().forEach(e -> {
			e.setTotal(beanSearcher.searchSum(CorpMsgBulkTaskRecord.class, MapUtils.builder().field(CorpMsgBulkTaskRecord::getSendId, e.getSenId()).build(), "total").intValue());
			e.setNotSend(e.getTotal() - e.getSend());
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 导出某任务群发记录
	 */
	@GetMapping("/export/sendRecord/{id}")
	public void exportSendRecord(@PathVariable Long id, Long startTime, Long endTime, HttpServletResponse response) {
		CorpMsgBulkTask byId = corpMsgBulkTaskService.getById(id);
		if (byId == null) {
			throw BusinessRuntimeException.getInstance("群发任务不存在");
		}
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		builder.put("task_id", String.format("task_id = %s", id));
		String time = StrUtil.EMPTY;
		if (startTime != null) {
			time += String.format(" and created_time >= '%s'", DateTime.of(startTime));
		}
		if (endTime != null) {
			time += String.format(" and created_time < '%s'", DateTime.of(endTime));
		}
		if (StrUtil.isNotEmpty(time)) {
			builder.put("time", time);
		}
		List<ExcelCorpMsgBulkTaskSendRecordData> list = beanSearcher.searchAll(ExcelCorpMsgBulkTaskSendRecordData.class, builder
				.orderBy(ExcelCorpMsgBulkTaskSendRecordData::getCreateTime).desc()
				.build());
		String fileName = String.format("%s群发任务发送记录", byId.getName());
		EasyExcelUtils.createExcelStreamMutilByEasyExcel(response, ExcelCorpMsgBulkTaskSendRecordData.class, list, fileName, fileName, ExcelTypeEnum.XLSX, null);
	}

	/**
	 * 群发记录 客服发送详情
	 */
	@GetMapping("/get/corpFollow/sendRecord/{id}")
	public Result<SearchResult<CorpMsgBulkTaskCorpFollowSendRecordView>> getCorpFollowSendRecord(@PathVariable Long id) {
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		builder.put("send_id", String.format("send_id = %s", id));
		SearchResult<CorpMsgBulkTaskCorpFollowSendRecordView> search = beanSearcher.search(CorpMsgBulkTaskCorpFollowSendRecordView.class, builder
				.orderBy(CorpMsgBulkTaskCorpFollowSendRecordView::getCreateTime).desc()
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 提醒群发
	 */
	@PutMapping("/remind/{msgid}")
	public Result<String> remindBulkTask(@PathVariable String msgid) {
		corpMsgBulkTaskService.remindBulkTask(msgid);
		return GatewayResponse.SUCCESS.newBuilder().toResult("提醒群发成功");
	}

	/**
	 * 立即执行 打动态标签
	 */
	@PostMapping("/execute/dynamicRuleTag/{tagId}")
	public Result<String> executeDynamicRuleTagTask(@PathVariable Long tagId) throws Exception {
		corpMsgBulkTaskService.executeDynamicRuleTagTask(tagId);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 群发任务通知
	 */
	@PostMapping("/send/active/corpBulkMsg")
	public Result<String> sendActiveCorpBulkMsg(@RequestBody CorpActiveBulkMsg msg) {
		corpMsgBulkTaskService.sendActiveCorpBulkMsg(msg);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}


	/**
	 * 新增分类
	 */
	@PostMapping("/category/post")
	public Result<String> postCategory(@RequestBody @Validated CorpMsgBulkTaskCategory corpMsgBulkTaskCategory) {
		try {
			corpMsgBulkTaskCategoryMapper.insert(corpMsgBulkTaskCategory);
		} catch (DuplicateKeyException e) {
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 编辑分类
	 */
	@PutMapping("/category/update")
	public Result<String> upCategory(@RequestBody @Validated CorpMsgBulkTaskCategory corpMsgBulkTaskCategory) {
		try {
			corpMsgBulkTaskCategoryMapper.updateById(corpMsgBulkTaskCategory);
		} catch (DuplicateKeyException e) {
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 删除分类
	 */
	@DeleteMapping("/category/delete/{id}")
	public Result<String> delCategory(@PathVariable Long id) {
		int count = corpMsgBulkTaskService.count(Wrappers.lambdaQuery(CorpMsgBulkTask.class).eq(CorpMsgBulkTask::getCategory, id).eq(CorpMsgBulkTask::getDeleted, 1));
		if (count > 0) {
			throw BusinessRuntimeException.getInstance("存在该分类下的群发任务");
		}
		corpMsgBulkTaskCategoryMapper.deleteById(id);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 分类列表
	 */
	@GetMapping("/category/get")
	public Result<SearchResult<CorpMsgBulkTaskCategory>> getCategory() {
		SearchResult<CorpMsgBulkTaskCategory> search = beanSearcher.search(CorpMsgBulkTaskCategory.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}
}
