package org.springblade.activity.controller;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.validation.Valid;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springblade.activity.dto.BladeActivityDTO;
import org.springblade.activity.dto.query.ActivityPageQuery;
import org.springblade.activity.dto.vo.BladeActivityPageVo;
import org.springblade.activity.dto.vo.BladeActivityVo;
import org.springblade.activity.entity.BladeActivity;
import org.springblade.activity.entity.BladeActivityChannel;
import org.springblade.activity.entity.BladeActivityCost;
import org.springblade.activity.entity.BladeActivityPrize;
import org.springblade.activity.entity.BladeActivityProduct;
import org.springblade.activity.entity.BladeActivityResponsible;
import org.springblade.activity.service.IBladeActivityChannelService;
import org.springblade.activity.service.IBladeActivityCostService;
import org.springblade.activity.service.IBladeActivityPrizeService;
import org.springblade.activity.service.IBladeActivityProductService;
import org.springblade.activity.service.IBladeActivityResponsibleService;
import org.springblade.activity.service.IBladeActivityService;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import cn.hutool.http.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * <p>
 * 活动管理表 前端控制器
 * </p>
 *
 * @author zbc
 * @since 2021-04-21
 */
@RestController
@RequestMapping("Activity/bladeActivity")
@Api(value = "活动管理", tags = "活动管理接口")
public class BladeActivityController {


	@Autowired
	private IBladeActivityService bladeActivityService;
	@Autowired
	private IBladeActivityChannelService bladeActivityChannelService;
	@Autowired
	private IBladeActivityCostService bladeActivityCostService;
	@Autowired
	private IBladeActivityPrizeService bladeActivityPrizeService;
	@Autowired
	private IBladeActivityProductService bladeActivityProductService;
	@Autowired
	private IBladeActivityResponsibleService bladeActivityResponsibleService;


	@PostMapping("/save")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "新增活动", notes = "传入bladeActivityDTO")
	public R save(@Valid @RequestBody BladeActivityDTO bladeActivityDTO) {
		if(StringUtils.isBlank(bladeActivityDTO.getActivityUuid())){
			return R.fail("活动ID不能为空");
		}
		BladeActivity one = bladeActivityService.getOne(new LambdaQueryWrapper<BladeActivity>()
			.eq(BladeActivity::getActivityUuid, bladeActivityDTO.getActivityUuid())
		);
		if(one != null){
			return R.fail("活动ID已存在,请重试");
		}
		BladeActivity bladeActivity = new BladeActivity();
		BeanUtils.copyProperties(bladeActivityDTO,bladeActivity);
		bladeActivity.setCreateTime(new Date());
		bladeActivity.setIsDeleted(0);
		bladeActivity.setStatus(0);
		if (bladeActivityService.save(bladeActivity)) {

			StringBuffer responsibleStr = new StringBuffer();
			StringBuffer channelStr = new StringBuffer();
			StringBuffer productStr = new StringBuffer();
			StringBuffer prizeStr = new StringBuffer();

			//负责人
			List<BladeActivityResponsible> responsibleList = bladeActivityDTO.getResponsibleList();
			if (CollectionUtils.isNotEmpty(responsibleList) && responsibleList.size() > 0) {
				for (BladeActivityResponsible bladeActivityResponsible : responsibleList) {
					bladeActivityResponsible.setActivityId(bladeActivity.getId());
					bladeActivityResponsible.setCreateTime(new Date());
					bladeActivityResponsibleService.save(bladeActivityResponsible);
					responsibleStr.append(bladeActivityResponsible.getId()).append(",");
				}
				String rs = responsibleStr.toString();
				if(StringUtils.isNotBlank(rs)){
					bladeActivity.setResponsibleIds(rs.substring(0,rs.length() - 1));
				}
			}

			//渠道
			List<BladeActivityChannel> channelList = bladeActivityDTO.getChannelList();
			if (CollectionUtils.isNotEmpty(channelList) && channelList.size() > 0) {
				for (BladeActivityChannel bladeActivityChannel : channelList) {
					bladeActivityChannel.setActivityId(bladeActivity.getId());
					bladeActivityChannel.setStatus(0);
					bladeActivityChannel.setCreateTime(new Date());
					bladeActivityChannelService.save(bladeActivityChannel);
					channelStr.append(bladeActivityChannel.getId()).append(",");
				}
				String cs = channelStr.toString();
				if(StringUtils.isNotBlank(cs)){
					bladeActivity.setChannelIds(cs.substring(0,cs.length() - 1));
				}
			}

			//产品
			List<BladeActivityProduct> productList = bladeActivityDTO.getProductList();
			if (CollectionUtils.isNotEmpty(productList) && productList.size() > 0) {
				for (BladeActivityProduct bladeActivityProduct : productList) {
					bladeActivityProduct.setActivityId(bladeActivity.getId());
					bladeActivityProduct.setStatus(0);
					bladeActivityProduct.setCreateTime(new Date());
					bladeActivityProductService.save(bladeActivityProduct);
					productStr.append(bladeActivityProduct.getId()).append(",");
				}
				String ps = productStr.toString();
				if(StringUtils.isNotBlank(ps)){
					bladeActivity.setProductIds(ps.substring(0,ps.length() - 1));
				}
			}

			//奖品
			List<BladeActivityPrize> prizeList = bladeActivityDTO.getPrizeList();
			if (CollectionUtils.isNotEmpty(prizeList) && prizeList.size() > 0) {
				for (BladeActivityPrize bladeActivityPrize : prizeList) {
					bladeActivityPrize.setActivityId(bladeActivity.getId());
					bladeActivityPrize.setStatus(0);
					bladeActivityPrize.setCreateTime(new Date());
					bladeActivityPrizeService.save(bladeActivityPrize);
					prizeStr.append(bladeActivityPrize.getId()).append(",");
				}
				String pis = productStr.toString();
				if(StringUtils.isNotBlank(pis)){
					bladeActivity.setPrizeIds(pis.substring(0,pis.length() - 1));
				}
			}

			//活动成本
			List<BladeActivityCost> costList = bladeActivityDTO.getCostList();
			if (CollectionUtils.isNotEmpty(costList) && costList.size() > 0) {
				for (BladeActivityCost bladeActivityCost : costList) {
					bladeActivityCost.setActivityId(bladeActivity.getId());
					bladeActivityCost.setStatus(0);
					bladeActivityCost.setCreateTime(new Date());
				}
				bladeActivityCostService.saveBatch(costList);
			}
			bladeActivityService.updateById(bladeActivity);
			return R.success("添加活动成功");
		}
		return R.fail("添加活动失败");
	}


	@PostMapping("/remove")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "删除活动 (物理删除)", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合  1,2,3", required = true) @RequestParam String ids) {
		return R.status(bladeActivityService.removeByIds(Func.toLongList(ids)));
	}

	@PostMapping("/delete")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "删除活动 (逻辑删除)", notes = "传入ids")
	public R delete(@ApiParam(value = "主键集合  1,2,3", required = true) @RequestParam String ids) {
		if(ids.isEmpty()){
			return R.fail("ids不能为空");
		}
		List<BladeActivity> collect = bladeActivityService.list(new LambdaQueryWrapper<BladeActivity>()
			.in(BladeActivity::getId, ids)
		).stream().map(obj -> {
			obj.setIsDeleted(1);
			return obj;
		}).collect(Collectors.toList());
		return R.status(bladeActivityService.updateBatchById(collect));
	}


	@PostMapping("/update")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "修改活动", notes = "传入bladeResponsible")
	public R update(@Valid @RequestBody BladeActivityDTO bladeActivityDTO) {
		BladeActivity bladeActivity = new BladeActivity();
		BeanUtils.copyProperties(bladeActivityDTO,bladeActivity);
		bladeActivity.setUpdateTime(new Date());
		if (bladeActivityService.updateById(bladeActivity)) {

			StringBuffer responsibleStr = new StringBuffer();
			StringBuffer channelStr = new StringBuffer();
			StringBuffer productStr = new StringBuffer();
			StringBuffer prizeStr = new StringBuffer();


			//负责人
			bladeActivityResponsibleService.remove(new LambdaQueryWrapper<BladeActivityResponsible>()
				.eq(BladeActivityResponsible::getActivityId,bladeActivity.getId())
			);

			//负责人
			List<BladeActivityResponsible> responsibleList = bladeActivityDTO.getResponsibleList();
			if (CollectionUtils.isNotEmpty(responsibleList) && responsibleList.size() > 0) {
				for (BladeActivityResponsible bladeActivityResponsible : responsibleList) {
					bladeActivityResponsible.setActivityId(bladeActivity.getId());
					bladeActivityResponsible.setCreateTime(new Date());
					bladeActivityResponsibleService.save(bladeActivityResponsible);
					responsibleStr.append(bladeActivityResponsible.getId()).append(",");
				}
				String rs = responsibleStr.toString();
				if(StringUtils.isNotBlank(rs)){
					bladeActivity.setResponsibleIds(rs.substring(0,rs.length() - 1));
				}
			}

			//渠道
			bladeActivityChannelService.remove(new LambdaQueryWrapper<BladeActivityChannel>()
				.eq(BladeActivityChannel::getActivityId,bladeActivity.getId())
			);

			//渠道
			List<BladeActivityChannel> channelList = bladeActivityDTO.getChannelList();
			if (CollectionUtils.isNotEmpty(channelList) && channelList.size() > 0) {
				for (BladeActivityChannel bladeActivityChannel : channelList) {
					bladeActivityChannel.setActivityId(bladeActivity.getId());
					bladeActivityChannel.setStatus(0);
					bladeActivityChannel.setCreateTime(new Date());
					bladeActivityChannelService.save(bladeActivityChannel);
					channelStr.append(bladeActivityChannel.getId()).append(",");
				}
				String cs = channelStr.toString();
				if(StringUtils.isNotBlank(cs)){
					bladeActivity.setChannelIds(cs.substring(0,cs.length() - 1));
				}
			}

			//产品
			bladeActivityProductService.remove(new LambdaQueryWrapper<BladeActivityProduct>()
				.eq(BladeActivityProduct::getActivityId,bladeActivity.getId())
			);

			//产品
			List<BladeActivityProduct> productList = bladeActivityDTO.getProductList();
			if (CollectionUtils.isNotEmpty(productList) && productList.size() > 0) {
				for (BladeActivityProduct bladeActivityProduct : productList) {
					bladeActivityProduct.setActivityId(bladeActivity.getId());
					bladeActivityProduct.setStatus(0);
					bladeActivityProduct.setCreateTime(new Date());
					bladeActivityProductService.save(bladeActivityProduct);
					productStr.append(bladeActivityProduct.getId()).append(",");
				}
				String ps = productStr.toString();
				if(StringUtils.isNotBlank(ps)){
					bladeActivity.setProductIds(ps.substring(0,ps.length() - 1));
				}
			}

			//奖品
			bladeActivityPrizeService.remove(new LambdaQueryWrapper<BladeActivityPrize>()
				.eq(BladeActivityPrize::getActivityId,bladeActivity.getId())
			);

			//奖品
			List<BladeActivityPrize> prizeList = bladeActivityDTO.getPrizeList();
			if (CollectionUtils.isNotEmpty(prizeList) && prizeList.size() > 0) {
				for (BladeActivityPrize bladeActivityPrize : prizeList) {
					bladeActivityPrize.setActivityId(bladeActivity.getId());
					bladeActivityPrize.setStatus(0);
					bladeActivityPrize.setCreateTime(new Date());
					bladeActivityPrizeService.save(bladeActivityPrize);
					prizeStr.append(bladeActivityPrize.getId()).append(",");
				}
				String pis = productStr.toString();
				if(StringUtils.isNotBlank(pis)){
					bladeActivity.setPrizeIds(pis.substring(0,pis.length() - 1));
				}
			}

			//活动成本
			bladeActivityCostService.remove(new LambdaQueryWrapper<BladeActivityCost>()
				.eq(BladeActivityCost::getActivityId,bladeActivity.getId())
			);

			List<BladeActivityCost> costList = bladeActivityDTO.getCostList();
			if (CollectionUtils.isNotEmpty(costList) && costList.size() > 0) {
				for (BladeActivityCost bladeActivityCost : costList) {
					bladeActivityCost.setActivityId(bladeActivity.getId());
					bladeActivityCost.setStatus(0);
					bladeActivityCost.setCreateTime(new Date());
				}
				bladeActivityCostService.saveBatch(costList);
			}

			bladeActivityService.updateById(bladeActivity);
			return R.success("更新活动成功");
		}

		return R.fail("更新活动失败");
	}


	@GetMapping("/list")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "列表", notes = "传入bladeActivity")
	public R<IPage<BladeActivity>> list(BladeActivity bladeActivity, Query query) {
		IPage<BladeActivity> pages = bladeActivityService.page(Condition.getPage(query), Condition.getQueryWrapper(bladeActivity));
		return R.data(pages);
	}


	@GetMapping("/page")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "分页", notes = "传入pageQuery")
	public R page(ActivityPageQuery pageQuery, Query query) {
		IPage<BladeActivityPageVo> page = Condition.getPage(query);
		IPage<BladeActivityPageVo> pages = bladeActivityService.getPageByQuery(page, pageQuery);
		return R.data(pages);
	}


	@GetMapping("/detail")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "详情", notes = "传入bladeActivity")
	public R<BladeActivityVo> detail(BladeActivity bladeActivity) {
		if(bladeActivity == null || bladeActivity.getId() == null){
			return R.fail("参数异常");
		}
		BladeActivity detail = bladeActivityService.getOne(Condition.getQueryWrapper(bladeActivity));
		BladeActivityVo vo = new BladeActivityVo();
		BeanUtils.copyProperties(detail,vo);
		List<BladeActivityResponsible> responsiblelist = bladeActivityResponsibleService.list(new LambdaQueryWrapper<BladeActivityResponsible>()
			.eq(BladeActivityResponsible::getActivityId, vo.getId())
		);
		vo.setResponsibleList(responsiblelist);

		//渠道
		List<BladeActivityChannel> channellist = bladeActivityChannelService.list(new LambdaQueryWrapper<BladeActivityChannel>()
			.in(BladeActivityChannel::getActivityId, vo.getId())
		);
		vo.setChannelList(channellist);

		//产品
		List<BladeActivityProduct> productlist = bladeActivityProductService.list(new LambdaQueryWrapper<BladeActivityProduct>()
			.eq(BladeActivityProduct::getActivityId, vo.getId())
		);
		vo.setProductList(productlist);

		//奖品
		List<BladeActivityPrize> prizelist = bladeActivityPrizeService.list(new LambdaQueryWrapper<BladeActivityPrize>()
			.eq(BladeActivityPrize::getActivityId, vo.getId())
		);
		vo.setPrizeList(prizelist);

		//活动成本
		List<BladeActivityCost> costlist = bladeActivityCostService.list(new LambdaQueryWrapper<BladeActivityCost>()
			.eq(BladeActivityCost::getActivityId, vo.getId())
		);
		vo.setCostList(costlist);
		return R.data(vo);
	}


	@GetMapping("/getuuid")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "随机获取uuid")
	public R getuuid() {
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		return R.data(uuid);
	}


	@Value("${activity.getUrl}")
	private String activityUrl;


	@GetMapping("/getActivitySelectList")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "获取活动平台活动信息下拉列表")
	@ResponseBody
	public R getActivitySelectList() {
		String s = HttpUtil.get(activityUrl);
//		String s = HttpUtils.doGetHttp(activityUrl, null, null);
		HashMap hashMap = JSON.parseObject(s, HashMap.class);
		if(hashMap != null && !hashMap.isEmpty() && hashMap.get("code").toString().equals("10000")){
			return R.data(hashMap.get("data"));
		}
		return R.fail("获取信息异常");
	}


}

