package com.bohuikeji.delivery.backstage.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.constants.discountConst;
import com.bohuikeji.delivery.backstage.entity.TCustomer;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountMall;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountPattern;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountRecord;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.frame.module.admin.annotation.InitLog;
import com.bohuikeji.frame.module.admin.base.ControllerBase;
import com.bohuikeji.frame.module.admin.base.EntityBase;
import com.bohuikeji.frame.module.admin.base.InterfaceBase;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysLog;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import netscape.javascript.JSObject;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;


/**
 * 优惠商城
 */
@Slf4j
@RestController
@RequestMapping("/discount")
public class DiscountController extends ControllerBase {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    ITDiscountMallService discountMallService;
    @Autowired
    ITDiscountRecordService discountRecordService;
    @Autowired
    ITDiscountPatternService discountPatternService;
    @Autowired
    ITCustomerService customerService;
    @Autowired
    ITNewsService newsService;

    /**
     * 后台新增优惠提交接口
     * @return
     */
    @PostMapping("/table/dis/mall/add")
    public InterfaceBase formSubmit(@RequestParam Map<String,String> params) throws Exception{
        TDiscountMall discountMall=crateEntityByMap(params);
        if("会员".equals(discountMall.getConsType())){
            List<TDiscountPattern> discountPatterns = discountPatternService.list(new QueryWrapper<TDiscountPattern>().eq("receive_method",discountMall.getReceiveMethod()).eq("pattern_type",discountMall.getConsType()));
            JSONObject jsObject = discountConst.getMemberUrl(discountMall,discountPatterns);
            discountMall.setUrlPicture(jsObject.getString("templateList"));
            discountMall.setFrameUrl(jsObject.getString("templateDetails"));
            discountMall.setDisMode("正常");
        }else {
            TDiscountPattern discountPattern = discountPatternService.getOne(new QueryWrapper<TDiscountPattern>().eq("receive_method",discountMall.getReceiveMethod()).eq("pattern_type",discountMall.getConsType()));
            if(discountPattern == null){
                return APIEntity.fail("未搜索到优惠样式模板，请稍后再试！");
            }
            discountMall.setUrlPicture(discountConst.getUrl(discountMall,discountPattern.getTemplateUrl()));
            if(discountConst.contrast(discountMall.getDisSign())){
                TDiscountPattern pattern = discountPatternService.getOne(new QueryWrapper<TDiscountPattern>().eq("receive_method",discountMall.getReceiveMethod()).eq("pattern_name",discountMall.getDisSign()));
                if(pattern == null){
                    return APIEntity.fail("未搜索到优惠样式模板，请稍后再试！");
                }
                discountMall.setDisMode("弹框");
                discountMall.setFrameUrl(discountConst.frameTemplate(discountMall,pattern.getTemplateUrl()));
            }
            if("无标识".equals(discountMall.getDisSign())){
                discountMall.setDisMode("正常");
                discountMall.setFrameUrl("");
            }
        }
        if(discountMall.insertOrUpdate()){
            return APIEntity.success();
        }
        return APIEntity.fail("新增或修改失败，请稍后再试！");
    }


    /**
     * 根据营销骑手名字和模板名字搜索
     * @return
     */
    @GetMapping("/search/key")
    public APIEntity getSearchByName(String key,Integer customerId){
        log.info("查询条件:[{}]",key);
        log.info("客户id:[{}]",customerId);
        List<Object> disIds = discountRecordService.listObjs(new QueryWrapper<TDiscountRecord>().select("dis_id").eq("customer_id",customerId));
        List<TDiscountMall> discountMalls = null;
        if(StringUtils.isBlank(key)){
            log.info("获取已领取的优惠卷数量111:[{}]",disIds.size());
            if(disIds.size()<1){
                discountMalls =discountMallService.list(new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","后台发放").eq("grant_type","全部"));
            }else {
                discountMalls =discountMallService.list(new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","后台发放").notIn("dis_id",disIds).eq("grant_type","全部"));

            }
            return APIEntity.success(discountMalls);
        }else {
            log.info("获取已领取的优惠卷数量222:[{}]",disIds.size());
            if(disIds.size()<1){
                discountMalls =discountMallService.list(new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","后台发放").eq("grant_type","全部").eq("coupon_name",key));
            }else {
                discountMalls =discountMallService.list(new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","后台发放").notIn("dis_id",disIds).eq("grant_type","全部").eq("coupon_name",key));
            }
        }
        return APIEntity.success(discountMalls);
    }

    /**
     * 提交发放优惠卷
     * @param customerId
     * @param disId
     * @return
     */
    @InitLog("绑定提交")
    @GetMapping("/grant/submit")
    public APIEntity exceptionAssign(Integer customerId, Integer disId) throws Exception {
        TCustomer customer = customerService.getById(customerId);
        TDiscountRecord discountRecord = new TDiscountRecord();
        if(customer == null){
            return APIEntity.fail("当前客户不存在，请刷新");
        }
        TDiscountMall discountMall = discountMallService.getById(disId);
        if(discountMall == null){
            return APIEntity.fail("当前优惠卷不存在，请刷新");
        }
        if("会员卡".equals(discountMall.getDisType())){
            discountRecord.setUsageStatus("使用中");
            discountRecord.setBeginDate(LocalDate.now());
            discountRecord.setEndDate(discountConst.getEndDate(discountMall.getDisName()));
            TDiscountPattern discountPattern = discountPatternService.getOne(new QueryWrapper<TDiscountPattern>().eq("description","展示模板").eq("receive_method",discountMall.getReceiveMethod()).eq("pattern_type",discountMall.getConsType()));
            discountRecord.setUrlPicture(discountConst.getMemberDisUrl(discountMall,discountPattern));
        }else {
            discountRecord.setUsageStatus("未使用");
            discountRecord.setBeginDate(discountMall.getBeginDate());
            discountRecord.setEndDate(discountMall.getEndDate());
            discountRecord.setUrlPicture(discountMall.getUrlPicture());
        }
        discountRecord.setDisId(discountMall.getDisId());
        discountRecord.setConsType(discountMall.getConsType());
        discountRecord.setDisRemark(discountMall.getDisRemark());
        discountRecord.setUseExplain(discountMall.getUseExplain());
        discountRecord.setStartAmount(discountMall.getStartAmount());
        discountRecord.setCustomerId(customerId);
        discountRecord.setDisValue(discountMall.getDisValue());
        discountRecord.setCollectionTime(LocalDateTime.now());
        discountRecord.setDisType(discountMall.getDisType());
        discountRecord.setReceiveMethod(discountMall.getReceiveMethod());
        discountRecord.setGrantType(discountMall.getGrantType());
        if(discountRecordService.save(discountRecord)){
            discountMall.setReceiveNum(discountMall.getReceiveNum()+1);
            discountMallService.updateById(discountMall);
        }
        return APIEntity.success("发放成功");
    }
}
