package com.ruoyi.app.promotion;

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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.app.utils.DateUtil;
import com.ruoyi.app.utils.PayPush;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.PosOrder;
import com.ruoyi.system.mapper.PosOrderMapper;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.JwtUtil;
import io.swagger.models.auth.In;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SalesPromotion;
import com.ruoyi.system.service.ISalesPromotionService;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import redis.clients.jedis.Jedis;

/**
 * SalesPromotionController
 *
 * @author ruoyi
 * @date 2024-05-30
 */
@RestController
@RequestMapping("/system/promotion")
public class SalesPromotionController extends BaseController {
    @Autowired
    private ISalesPromotionService salesPromotionService;

    @Autowired
    private PosOrderMapper posOrderMapper;

    /**
     * 获取可参于促销活动
     *
     * @param mdId
     * @param price
     * @return
     */
    @Anonymous
    @Auth
    @GetMapping("/getorderuzt")
    public AjaxResult getorderuzt(@RequestHeader String token,
                                  @RequestParam(defaultValue = "") String mdId,
                                  @RequestParam(defaultValue = "") String price,
                                  @RequestParam(defaultValue = "") String yfPrice) {
        System.out.println("getorderuzt");
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        String language = getLanguage(id);
        DateUtil date = new DateUtil();
        System.out.println("getorderuzt输出信息用户id:" + id + "语言:" + language + "价格:" + price + "运费:" + yfPrice + "门店id:" + mdId + "当前时间:" + date.GetDateNt());
        QueryWrapper<SalesPromotion> wrapper = new QueryWrapper<>();
        wrapper.eq("sales_state", 0)
                .ge("end_time", date.GetDateNt())
                .eq("language", language)
                .eq("deleted", '0');

        if (!"".equals(mdId)) {
            wrapper.and(w -> w.eq("sh_id", mdId).or().isNull("sh_id"));
        }

        wrapper.and(sub -> {
                            sub.nested(nonShip ->
                                    nonShip.nested(cond -> cond.le("sales_condition", price)
                                            .or()
                                            .nested(cn -> cn.isNull("sales_condition"))
                                    )
                            );
                }
        );

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

//        if (hasPrice || hasYfPrice) {
//            wrapper.and(wrap -> {
//                // 非运费条件块（sales_type <> 1）
//                if (hasPrice) {
//                    wrap.and(sub ->
//                            sub.nested(nonShip ->
//                                    nonShip.nested(cond -> cond.le("sales_condition", price).ne("sales_type", "1"))
//                                            .or()
//                                            .nested(cond -> cond.isNull("sales_condition").ne("sales_type", "1"))
//                            )
//                    );
//                }
//
//                // 运费条件块（sales_type = 1）
//                if (hasYfPrice) {
//                    wrap.or(sub ->
//                            sub.nested(ship ->
//                                    ship.nested(cond -> cond.le("sales_condition", yfPrice).eq("sales_type", "1"))
//                                            .or()
//                                            .nested(cond -> cond.isNull("sales_condition").eq("sales_type", "1"))
//                            )
//                    );
//                }
//            });
//        }
        List<SalesPromotion> saleslist = salesPromotionService.list(wrapper);
        JSONArray array = new JSONArray();
        for (SalesPromotion promotion : saleslist) {
            if (promotion.getSalesFund() == null) {
                array.add(promotion);
            } else {
                int sycs = posOrderMapper.getActivity(Long.valueOf(id), promotion.getId());
                if (sycs < promotion.getSalesFund().intValue()) {
                    array.add(promotion);
                }
            }
        }
        return success(array);
    }

    private String getLanguage(String uid) {

        Jedis jedis = new Jedis("localhost", 6379);
        String lang = jedis.get(uid);
        System.out.println("从redis获取的语言是：" + lang);
        String result = "0";
        if ("zh-CN".equals(lang)) {
            result = "2";
        }
        if ("zh-TW".equals(lang)) {
            result = "3";
        }
        if ("en-US".equals(lang)) {
            result = "1";
        }
        System.out.println("获取的语言是：" + result);
        return result;
    }

    /**
     * 查询SalesPromotion列表
     */
    @PreAuthorize("@ss.hasPermi('system:promotion:list')")
    @GetMapping("/list")
    public TableDataInfo list(SalesPromotion salesPromotion) {
        startPage();
        List<SalesPromotion> list = salesPromotionService.selectSalesPromotionList(salesPromotion);
        return getDataTable(list);
    }

    /**
     * 导出SalesPromotion列表
     */
    @PreAuthorize("@ss.hasPermi('system:promotion:export')")
    @Log(title = "SalesPromotion", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SalesPromotion salesPromotion) {
        List<SalesPromotion> list = salesPromotionService.selectSalesPromotionList(salesPromotion);
        ExcelUtil<SalesPromotion> util = new ExcelUtil<SalesPromotion>(SalesPromotion.class);
        util.exportExcel(response, list, MessageUtils.message("no.export.excel.salespromotion"));
    }

    /**
     * 获取SalesPromotion详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:promotion:query')")
    @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);
    }

    /**
     * 新增SalesPromotion
     */
    @PreAuthorize("@ss.hasPermi('system:promotion:add')")
    @Log(title = "SalesPromotion", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SalesPromotion salesPromotion) {
        return toAjax(salesPromotionService.insertSalesPromotion(salesPromotion));
    }

    /**
     * 修改SalesPromotion
     */
    @PreAuthorize("@ss.hasPermi('system:promotion:edit')")
    @Log(title = "SalesPromotion", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SalesPromotion salesPromotion) {
        return toAjax(salesPromotionService.updateSalesPromotion(salesPromotion));
    }

    /**
     * 删除SalesPromotion
     */
    @PreAuthorize("@ss.hasPermi('system:promotion:remove')")
    @Log(title = "SalesPromotion", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(salesPromotionService.deleteSalesPromotionByIds(ids));
    }
}
