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

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.OrderDonMapper;
import com.cyksj.mapper.corp.CorpFollowMapper;
import com.cyksj.mapper.corp.CorpUserMapper;
import com.cyksj.mapper.corp.CorpWelcomeTemplateMapper;
import com.cyksj.mapper.manage.coupon.CouponMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.request.corp.Attachments;
import com.cyksj.model.request.corp.CorpFollowContact;
import com.cyksj.model.views.*;
import com.cyksj.redis.RedisService;
import com.cyksj.service.corp.CorpFollowDynamicConfigService;
import com.cyksj.service.corp.CorpFollowService;
import com.cyksj.service.sys.SysConfigService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;

/** admin/企业微信/客服活码
 *项目名: netflix
 *文件名: CmsCorpFollowActiveCodeController
 *创建者: JavaZou
 *创建时间:2023/7/6 18:36
 */
@RestController
@RequestMapping("/manage/corp")
@RequiredArgsConstructor
public class CmsCorpFollowActiveCodeController {

	private final CorpFollowDynamicConfigService corpFollowDynamicConfigService;

	private final CorpFollowService corpFollowService;

	private final BeanSearcher beanSearcher;

	private final CouponMapper couponMapper;

	private final OrderDonMapper orderDonMapper;

	private final CorpUserMapper corpUserMapper;

	private final RedisService redisService;

	private final CorpWelcomeTemplateMapper corpWelcomeTemplateMapper;

	private final SysConfigService sysConfigService;

	private final HttpServletRequest request;

	private final CorpFollowMapper corpFollowMapper;

	/**
	 * 获取企业成员列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<CorpFollow>> getCorpFollow() {
		SearchResult<CorpFollow> search = beanSearcher.search(CorpFollow.class, MapUtils.flatBuilder(request.getParameterMap())
				.onlySelect(CorpFollow::getId, CorpFollow::getUserid, CorpFollow::getName)
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 编辑企业成员
	 */
	@PutMapping("/update/follow")
	public Result<String> updateFollow(@RequestBody CorpFollow corpFollow) {
		corpFollowMapper.updateById(corpFollow);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}


	/**
	 * 生成动态配置
	 */
	@PostMapping("/post/config")
	public Result<String> getCorpFollowConcat(@RequestBody CorpFollowContact corpFollowContact) throws Exception {
		String body = corpFollowDynamicConfigService.corpFollowContactConfig(corpFollowContact);
		return GatewayResponse.SUCCESS.newBuilder().toResult(body);
	}

	/**
	 * 可选客服配置
	 */
	@GetMapping("/get/available/follow")
	public Result<List<SysCorpFollowView>> getAvailableFollow() {
		List<SysCorpFollowView> corpFollowServiceDtos = beanSearcher.searchAll(SysCorpFollowView.class, MapUtils.builder().build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(corpFollowServiceDtos);
	}

	/**
	 * 创建活动活码
	 */
	@PostMapping("/post/active/code")
	public Result<String> postActiveCode(@RequestBody @Validated CorpFollowActiveCode activeCode) throws Exception {
		long adminId = StpUtil.getLoginIdAsLong();
		corpFollowService.postActiveCode(adminId, activeCode);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 编辑活动活码
	 */
	@PutMapping("/update/active/code")
	public Result<String> upActiveCode(@RequestBody @Validated CorpFollowActiveCode activeCode) throws Exception {
		corpFollowService.upActiveCode(activeCode);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 删除活码
	 */
	@DeleteMapping("/del/active/code/{id}")
	public Result<String> deleteByAcCodeById(@PathVariable Long id) throws Exception {
		corpFollowService.deleteActiveCodeById(id);
		Set<String> keys = redisService.keys(RedisService.key.CORP_FOLLOW_ACTIVE_CODE_KEY.getNameFormat(id, "*"));
		redisService.del(keys.toArray(String[]::new));
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 活动活码列表
	 */
	@GetMapping("/get/active/code")
	public Result<SearchResult<CorpFollowActiveCodeView>> getActiveCodeList() {
		SearchResult<CorpFollowActiveCodeView> search = beanSearcher.search(CorpFollowActiveCodeView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		search.getDataList().forEach(data -> {
			Integer numOfUser = corpUserMapper.selectCount(Wrappers.lambdaQuery(CorpUser.class)
					.eq(CorpUser::getAcId, data.getId()));
			data.setNumOfUser(numOfUser);
			Integer orderNum = orderDonMapper.selectCountActiveCodeOrderByAcId(data.getId());
			data.setOrderNum(orderNum);
			try {
				data.setUserIndxList(Jsons.parseList(data.getFollowStr(), Integer.class));
				if (StrUtil.isNotBlank(data.getAttachmentsStr())) {
					data.setAttachments(Jsons.parseList(data.getAttachmentsStr(), Attachments.class));
				}
			} catch (Exception e) {
			}
			CorpWelcomeTemplate corpWelcomeTemplate = corpWelcomeTemplateMapper.selectById(data.getMsgId());
			if (corpWelcomeTemplate != null) {
				data.setMsgName(corpWelcomeTemplate.getName());
			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 查看活码人数列表
	 */
	@GetMapping("/get/active/code/userList")
	public Result<SearchResult<CorpUser>> getCorpActiveCodeUser() {
		MapBuilder mapBuilder = MapUtils.flatBuilder(request.getParameterMap());
		SearchResult<CorpUser> search = beanSearcher.search(CorpUser.class, mapBuilder.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 查看活码订单 详情
	 */
	@GetMapping("/get/active/code/orderDetail")
	public Result<SearchResult<CorpActiveCodeOrderView>> getCorpActiveCodeOrderView(Long id) {
		MapBuilder mapBuilder = MapUtils.flatBuilder(request.getParameterMap());
		if (id != null) {
			mapBuilder.put("acId", String.format(" and cu.ac_id = %s", id));
		}
		SearchResult<CorpActiveCodeOrderView> search = beanSearcher.search(CorpActiveCodeOrderView.class, mapBuilder.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 活码 平台订单数据
	 */
	@GetMapping("/get/active/code/goods/order")
	public Result<SearchResult<CorpActiveCodeGoodsOrderView>> getCorpActiveCodeGoodsOrder(Long id, String startTime, String endTime) {
		String timeSql = StringUtils.EMPTY;
		if (StringUtils.isNotBlank(startTime)) {
			timeSql += " and o.created_time >= '" + startTime + "'";
		}
		if (StringUtils.isNotBlank(endTime)) {
			timeSql += " and o.created_time <= '" + endTime + "'";
		}
		MapBuilder mapBuilder = MapUtils.flatBuilder(request.getParameterMap());
		if (id != null) {
			mapBuilder.put("acId", String.format(" and cu.ac_id = %s", id));
		}
		if (StrUtil.isNotBlank(timeSql)) {
			mapBuilder.put("time", timeSql);
		}
		SearchResult<CorpActiveCodeGoodsOrderView> search = beanSearcher.search(CorpActiveCodeGoodsOrderView.class, mapBuilder.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 活码订单详情头部信息
	 */
	@GetMapping("/get/active/code/order/headData")
	public Result<CorpFollowActiveCodeView> getActiveCodeOrderHeadDataView(Long id, String startTime, String endTime) {
		CorpFollowActiveCodeView view = new CorpFollowActiveCodeView();
		view.setId(id);
		MapBuilder builder = MapUtils.builder();
		if (startTime != null && endTime != null) {
			builder.field(CorpFollowActiveCodeClickRecord::getCreatedTime, startTime, endTime).op(Operator.Between);
		}
		Number clickNumber = beanSearcher.searchCount(CorpFollowActiveCodeClickRecord.class, builder.build());
		Map<String, Object> map = orderDonMapper.selectActiveCodeOrderDetail(view.getId(), startTime, endTime);
		Object orderNum = map.get("orderNum");
		Object orderMoney = map.get("orderMoney");
		view.setClickNum(clickNumber.intValue());
		if (orderNum != null) {
			view.setOrderNum(Integer.parseInt(orderNum.toString()));
		}
		if (orderMoney != null) {
			view.setOrderMoney(BigDecimal.valueOf(Long.valueOf(orderMoney.toString())));
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(view);
	}

	/**
	 * 活码人数每日添加详情
	 * @param acId 活码记录id
	 * @return
	 */
	@GetMapping("/get/statistics/user/data/{acId}")
	public Result<SearchResult<CorpActiveCodeUserDayDataView>> getAcUserDayData(@PathVariable Long acId) {
		String condition = String.format("ac_id = %s", acId);
		SearchResult<CorpActiveCodeUserDayDataView> search = beanSearcher.search(CorpActiveCodeUserDayDataView.class, MapUtils.flatBuilder(request.getParameterMap()).put("condition", condition)
				.orderBy(CorpActiveCodeUserDayDataView::getDate).desc()
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}
}
