package com.ruoyi.app.mendian;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.utils.DateUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.PosOrder;
import com.ruoyi.system.domain.PosStore;
import com.ruoyi.system.domain.SalesPromotion;
import com.ruoyi.system.domain.VipUserQuanyi;
import com.ruoyi.system.mapper.PosOrderMapper;
import com.ruoyi.system.service.ISalesPromotionService;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.util.List;


/**
 * 商家端促销活动管理
 */
@RestController
@RequestMapping("/system/shSalesPromotion")
public class ShSalesPromotionController  extends BaseController {
    @Autowired
    private ISalesPromotionService salesPromotionService;

    @Autowired
    private PosOrderMapper posOrderMapper;
    /**
     * 获取可参于促销活动
     * @param mdId
     * @param price
     * @param yfPrice
     * @return
     */
    @Anonymous
    @Auth
    @GetMapping("/getorderuzt")
    public AjaxResult getorderuzt(@RequestHeader String token ,
                                  @RequestParam(defaultValue = "") String mdId,
                                  @RequestParam(defaultValue = "") String price,
                                  @RequestParam(defaultValue = "") String yfPrice)
    {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        DateUtil date = new DateUtil();
        QueryWrapper<SalesPromotion> wrapper = new QueryWrapper<>();
        //传0 表示自提，去掉运费优惠券
        if(yfPrice.equals("0")){
            wrapper.ne("sales_type", "1");
        }
        wrapper.eq("sales_state",0);
        wrapper.ge("end_time",date.GetDateNt());
        if(!"".equals(mdId)){
            wrapper.and(wra->wra.eq("sh_id",mdId).or().isNull("sh_id"));
        }else {
            wrapper.isNull("sh_id");
        }

        // 动态构建价格条件
        boolean hasPrice = StringUtils.isNotBlank(price);
        boolean hasYfPrice = StringUtils.isNotBlank(yfPrice);

        if (hasPrice || hasYfPrice) {
            wrapper.and(sub -> {
                if (hasPrice) {
                    sub.and(subWrapper ->
                            subWrapper.le("sales_condition", price)
                                    .ne("sales_type", "1")
                    ).or(subWrapper ->
                            subWrapper.isNull("sales_condition")
                                    .ne("sales_type", "1")
                    );
                }
                if (hasYfPrice) {
                    if (hasPrice) { // 当两者都存在时添加 OR
                        sub.or(subWrapper ->
                                subWrapper.le("sales_condition", yfPrice)
                                        .eq("sales_type", "1")
                        ).or(subWrapper ->
                                subWrapper.isNull("sales_condition")
                                        .eq("sales_type", "1")
                        );
                    }else{
                        sub.and(subWrapper ->
                                subWrapper.le("sales_condition", yfPrice)
                                        .eq("sales_type", "1")
                        ).or(subWrapper ->
                                subWrapper.isNull("sales_condition")
                                        .eq("sales_type", "1")
                        );
                    }

                }
            });
        }

        List<SalesPromotion> saleslist = salesPromotionService.list(wrapper);
        JSONArray array = new JSONArray();
        for (int i=0;i<saleslist.size();i++){
            if(saleslist.get(i).getSalesFund()==null){
                array.add(saleslist.get(i));
            }else {
                int sycs = posOrderMapper.getActivity(Long.valueOf(id),saleslist.get(i).getId());
                int fund = Math.toIntExact(saleslist.get(i).getSalesFund());
                //促销活动开启了每个用户使用次数，使用次数小于限制才能返回
                if(sycs<fund){
                    array.add(saleslist.get(i));
                }
            }
        }
        return success(array);
    }
    /**
     * 查询查询商家促销列表
     */
    @Anonymous
    @Auth
    @GetMapping("/list")
    public AjaxResult list(@RequestHeader String token,
                              @RequestParam Integer page,
                              @RequestParam Integer size,
                           @RequestParam String language,
                           @RequestParam Long shId
    )
    {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        IPage<SalesPromotion> stlist = new Page<>(page,size);
        LambdaQueryWrapper<SalesPromotion> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SalesPromotion::getDeleted,'0');
        queryWrapper.eq(SalesPromotion::getShId,shId);
        queryWrapper.eq(SalesPromotion::getLanguage,language);
        IPage<SalesPromotion> list =  salesPromotionService.page(stlist,queryWrapper);
        return success(list);
    }


    /**
     * 获取促销活动详细信息
     */
    @Anonymous
    @Auth
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        SalesPromotion result= salesPromotionService.selectSalesPromotionById(id);
        if(result!=null) {
            LambdaQueryWrapper<PosOrder> query = new LambdaQueryWrapper<>();
            query.nested(w -> w.eq(PosOrder::getActivity, id).or().eq(PosOrder::getMdActivity, id));
            boolean exist = posOrderMapper.selectCount(query) > 0;
            if (exist) {
                result.setEdit(!exist);
            } else {
                result.setEdit(true);
            }
        }
        return success(result);
    }

    /**
     * 新增促销活动
     */
    @Anonymous
    @Auth
    @PostMapping
    public AjaxResult add(@RequestHeader String token ,@RequestBody SalesPromotion salesPromotion)
    {
//        JwtUtil jwtUtil = new JwtUtil();
//        String id = jwtUtil.getusid(token);
//        salesPromotion.setShId(Long.valueOf(id));
        salesPromotion.setType("1");
        return toAjax(salesPromotionService.insertSalesPromotion(salesPromotion));
    }

    /**
     * 修改促销活动
     */
    @Anonymous
    @Auth
    @PutMapping
    public AjaxResult edit(@RequestBody SalesPromotion salesPromotion)
    {
        return toAjax(salesPromotionService.updateSalesPromotion(salesPromotion));
    }

    /**
     * 删除促销活动
     */

    @Anonymous
    @Auth
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(salesPromotionService.deleteSalesPromotionByIds(ids));
    }
}
