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

import cn.hutool.core.util.StrUtil;
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.CorpCustomerAcquisitionLinkMapper;
import com.cyksj.mapper.corp.CorpFollowActiveCodeMapper;
import com.cyksj.mapper.manage.coupon.CouponMapper;
import com.cyksj.model.entity.CorpCustomerAcquisitionLink;
import com.cyksj.model.entity.CorpFollowActiveCode;
import com.cyksj.model.entity.CorpWelcomeTemplate;
import com.cyksj.model.request.corp.Attachments;
import com.cyksj.service.corp.CorpWelcomeTemplateService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * admin/企业微信/欢迎语模板
 * 项目名: yhlxj
 * 文件名: CorpWelcomeTemplateController
 * 创建者: JavaZou
 * 创建时间:2023/12/5 18:23
 */
@RestController
@RequestMapping("/manage/corp/welcome")
@RequiredArgsConstructor
public class CorpWelcomeTemplateController {

	private final CorpWelcomeTemplateService corpWelcomeTemplateService;

	private final CouponMapper couponMapper;

	private final CorpFollowActiveCodeMapper corpFollowActiveCodeMapper;

	private final CorpCustomerAcquisitionLinkMapper acquisitionLinkMapper;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	/**
	 * 新增欢迎语 模板
	 */
	@PostMapping("/post")
	public Result<String> post(@RequestBody @Validated CorpWelcomeTemplate template) throws Exception {
		corpWelcomeTemplateService.saveOrUpdateTemplate(template);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 删除欢迎语 模板
	 */
	@DeleteMapping("/delete/{id}")
	public Result<String> deleteById(@PathVariable Long id) {
		CorpWelcomeTemplate byId = corpWelcomeTemplateService.getById(id);
		Integer count = null;
		if (byId.getType() == 0) {
			int count1 = corpWelcomeTemplateService.count(Wrappers.lambdaQuery(CorpWelcomeTemplate.class)
					.eq(CorpWelcomeTemplate::getType, 0).eq(CorpWelcomeTemplate::getDeleted, 1));
			if (count1 == 0) {
				throw BusinessRuntimeException.getInstance("自然渠道欢迎语默认存在一条");
			}
		} else if (byId.getType() == 1) {
			count = corpFollowActiveCodeMapper.selectCount(Wrappers.lambdaQuery(CorpFollowActiveCode.class)
					.eq(CorpFollowActiveCode::getDeleted, 1)
					.eq(CorpFollowActiveCode::getMsgId, byId.getId()));
		} else if (byId.getType() == 2) {
			count = acquisitionLinkMapper.selectCount(Wrappers.lambdaQuery(CorpCustomerAcquisitionLink.class)
					.eq(CorpCustomerAcquisitionLink::getMsgId, byId.getId()));
		}
		if (count != null && count > 0) {
			throw BusinessRuntimeException.getInstance("该欢迎语已使用");
		}
		if (byId != null) {
			byId.setDeleted(false);
			corpWelcomeTemplateService.updateById(byId);
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 修改欢迎语 模板
	 */
	@PutMapping("/update")
	public Result<String> update(@RequestBody CorpWelcomeTemplate template) throws Exception {
		corpWelcomeTemplateService.saveOrUpdateTemplate(template);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 欢迎语模板列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<CorpWelcomeTemplate>> get() {
		SearchResult<CorpWelcomeTemplate> search = beanSearcher.search(CorpWelcomeTemplate.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(CorpWelcomeTemplate::getDeleted, 1)
				.build());
		search.getDataList().forEach(e -> {
			String attachmentsStr = e.getAttachmentsStr();
			if (StrUtil.isNotEmpty(attachmentsStr)) {
				try {
					e.setAttachments(Jsons.parseList(attachmentsStr, Attachments.class));
				} catch (Exception ex) {
				}
			}
			if (StrUtil.isNotBlank(e.getCouponIds())) {
				try {
					List<Long> couponIds = Jsons.parseList(e.getCouponIds(), Long.class);
					e.setCouponName(couponMapper.getCouponNameByIds(couponIds));
				} catch (Exception ex) {
				}
			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 不分页 欢迎语模板
	 */
	@GetMapping("/get/all")
	public Result<List<CorpWelcomeTemplate>> getAll() {
		List<CorpWelcomeTemplate> list = beanSearcher.searchAll(CorpWelcomeTemplate.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(CorpWelcomeTemplate::getDeleted, 1)
				.onlySelect(CorpWelcomeTemplate::getId, CorpWelcomeTemplate::getType, CorpWelcomeTemplate::getName).build());

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