package com.gxwebsoft.shop.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.freewayso.image.combiner.ImageCombiner;
import com.freewayso.image.combiner.element.TextElement;
import com.freewayso.image.combiner.enums.OutputFormat;
import com.freewayso.image.combiner.enums.ZoomMode;
import com.gxwebsoft.common.core.security.JwtUtil;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.utils.RequestUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.param.MerchantParam;
import com.gxwebsoft.shop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商户控制器
 *
 * @author 科技小王子
 * @since 2024-04-05 00:03:54
 */
@Api(tags = "商户管理")
@RestController
@RequestMapping("/api/shop/merchant")
public class MerchantController extends BaseController {
    @Resource
    private MerchantService merchantService;
    @Resource
    private MerchantAccountService merchantAccountService;
    @Resource
    private OrderService orderService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private OrderGoodsService orderGoodsService;
    @Resource
    private MerchantCollectService merchantCollectService;
    @Resource
    private MerchantOfflinePayService merchantOfflinePayService;

    @Value("${config.upload-path}")
    private String uploadPath;
    final private String serverUrl = "https://nbg-img.websoft.top";

    @Autowired
    private RequestUtil requestUtil;

    @PostMapping("/data")
    public ApiResult<?> data() {
        Merchant merchant = merchantService.getByUserId(getLoginUserId());
        if (merchant == null) return fail("非法请求");
        List<Goods> goodsList = goodsService.listByMerchant(merchant.getMerchantId());
        BigDecimal totalIncome = BigDecimal.ZERO, monthIncome = BigDecimal.ZERO, todayIncome = BigDecimal.ZERO;

        Map<String, Object> data = new HashMap<>();
        if (!goodsList.isEmpty()) {
            List<OrderGoods> orderGoodsList = orderGoodsService.listByGoodsList(goodsList.stream().map(Goods::getGoodsId).toList());
            if (!orderGoodsList.isEmpty()) {
                List<Order> orderList = orderService.listByIds(orderGoodsList.stream().map(OrderGoods::getOrderId).toList());
                for (OrderGoods orderGoods : orderGoodsList) {
                    for (Order order : orderList) {
                        if (orderGoods.getOrderId().equals(order.getOrderId())) {
                            if (order.getPayStatus().equals(1)) {
                                totalIncome = totalIncome.add(orderGoods.getPrice().multiply(new BigDecimal(orderGoods.getTotalNum())));
                                if (order.getCreateTime().after(DateUtil.beginOfMonth(DateUtil.date())) && order.getCreateTime().before(DateUtil.endOfMonth(DateUtil.date()))) {
                                    monthIncome = monthIncome.add(orderGoods.getPrice().multiply(new BigDecimal(orderGoods.getTotalNum())));
                                }
                                if (order.getCreateTime().after(DateUtil.beginOfDay(DateUtil.date())) && order.getCreateTime().before(DateUtil.endOfDay(DateUtil.date()))) {
                                    todayIncome = todayIncome.add(orderGoods.getPrice().multiply(new BigDecimal(orderGoods.getTotalNum())));
                                }
                            }
                        }
                    }
                }
            }
        }

        List<MerchantOfflinePay> offlinePayList = merchantOfflinePayService.listByMerchant(merchant.getMerchantId());
        for (MerchantOfflinePay offlinePay : offlinePayList) {
            if (offlinePay.getIsPaid().equals(1)) {
                totalIncome = totalIncome.add(offlinePay.getAmount());
                if (offlinePay.getCreateTime().after(DateUtil.beginOfMonth(DateUtil.date())) && offlinePay.getCreateTime().before(DateUtil.endOfMonth(DateUtil.date()))) {
                    monthIncome = monthIncome.add(offlinePay.getAmount());
                }
                if (offlinePay.getCreateTime().after(DateUtil.beginOfDay(DateUtil.date())) && offlinePay.getCreateTime().before(DateUtil.endOfDay(DateUtil.date()))) {
                    todayIncome = todayIncome.add(offlinePay.getAmount());
                }
            }
        }
        data.put("totalIncome", totalIncome);
        data.put("monthIncome", monthIncome);
        data.put("todayIncome", todayIncome);
        data.put("goodsList", goodsList);
        return success(data);
    }

    @ApiOperation("分页查询商户")
    @GetMapping("/page")
    public ApiResult<PageResult<Merchant>> page(MerchantParam param) {
        // 使用关联查询
        System.out.println("param = " + param);
        return success(merchantService.pageRel(param));
    }

    @ApiOperation("查询全部商户")
    @GetMapping()
    public ApiResult<List<Merchant>> list(MerchantParam param, HttpServletRequest request) {
        // 使用关联查询
        List<Merchant> merchantList = merchantService.listRel(param);
//        requestUtil.setTenantId(getTenantId().toString());
//        List<Integer> userIdList = merchantList.stream().map(Merchant::getUserId).toList();
//        JSONArray refereeNumByUidList = requestUtil.getRefereeNumByUidList(userIdList);
//        for (Merchant merchant : merchantList) {
//            for (int i = 0; i < userIdList.size(); i++) {
//                JSONObject jsonObject = (JSONObject) refereeNumByUidList.get(i);
//                if (merchant.getUserId().equals(jsonObject.getInteger("userId"))) {
//                    merchant.setUserNum(jsonObject.getInteger("num"));
//                }
//            }
//            merchant.setUserNum(requestUtil.getRefereeNum(merchant.getUserId()));
//        }
        return success(merchantList);
    }

    @ApiOperation("根据id查询商户")
    @GetMapping("/{id}")
    public ApiResult<Merchant> get(@PathVariable("id") Integer id, MerchantParam param) {
        Merchant merchant = merchantService.getByIdRel(id, param);
        if (getLoginUser() != null) {
            MerchantCollect merchantCollect = merchantCollectService.check(merchant.getMerchantId(), getLoginUserId());
            merchant.setIsCollect(merchantCollect != null);
        }
        return success(merchant);
    }

    @ApiOperation("查询我的商户")
    @GetMapping("/getByUserId")
    public ApiResult<Merchant> getByUserId() {
        final Merchant one = merchantService.getOne(new LambdaQueryWrapper<Merchant>().eq(Merchant::getUserId, getLoginUserId()));
        if (ObjectUtil.isNotEmpty(one)) {
            return success(one);
        }
        return fail("未注册商户", null);
    }

    @PreAuthorize("hasAuthority('shop:merchant:save')")
    @ApiOperation("添加商户")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Merchant merchant, HttpServletRequest request) {
        if (merchantService.count(new LambdaQueryWrapper<Merchant>().eq(Merchant::getPhone, merchant.getPhone())) > 0) {
            return fail("商户手机号码" + merchant.getPhone() + "已存在");
        }
        if (merchantService.save(merchant)) {
            // 设置商家后台入口
            merchant.setAdminUrl(merchant.getTenantId() + ".m.wsdns.cn");
            merchantService.updateById(merchant);
            // 获取用户信息
            final RequestUtil requestUtil = new RequestUtil();
            String access_token = JwtUtil.getAccessToken(request);
            requestUtil.setAccessToken(access_token);
            requestUtil.setTenantId(getTenantId().toString());
            final MerchantAccount merchantAccount = new MerchantAccount();
            merchantAccount.setMerchantId(merchant.getMerchantId());
            merchantAccount.setPhone(merchant.getPhone());
            merchantAccount.setPassword(merchant.getPhone().substring(merchant.getPhone().length() - 6));
            merchantAccount.setRealName(merchant.getRealName());
            merchantAccount.setRoleId(merchant.getRoleId());
            merchantAccount.setRoleName(merchant.getRoleName());
            requestUtil.saveUserByPhone(merchantAccount);
            merchantAccountService.save(merchantAccount);
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:merchant:update')")
    @ApiOperation("修改商户")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Merchant merchant) {
        if (merchantService.updateById(merchant)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:merchant:remove')")
    @ApiOperation("删除商户")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (merchantService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:merchant:save')")
    @ApiOperation("批量添加商户")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Merchant> list) {
        if (merchantService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:merchant:update')")
    @ApiOperation("批量修改商户")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Merchant> batchParam) {
        if (batchParam.update(merchantService, "merchant_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:merchant:remove')")
    @ApiOperation("批量删除商户")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (merchantService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("生成海报")
    @PostMapping("/make-offline-poster")
    public ApiResult<?> makePoster() throws Exception {
        User loginUser = getLoginUser();
        String filePath = "qr/userPayCode_" + loginUser.getUserId() + "_full.png";
        String savePath = uploadPath + filePath;

        String qr = uploadPath + "qr/userPayCode_" + loginUser.getUserId() + ".png";
        String bgPath = uploadPath + "qr/offline-bg.png";
        Image bgImg = ImgUtil.read(bgPath);

        File qrFile = new File(qr);
        String qrPath = "file://" + qrFile.getAbsolutePath();

        ImageCombiner postCombiner = new ImageCombiner(500, 720, Color.white, OutputFormat.PNG);
        postCombiner.addImageElement(ImgUtil.toBufferedImage(bgImg), 0, 0);
        // 头像
//        if (loginUser.getAvatar() != null) {
//            postCombiner.addImageElement(loginUser.getAvatar(), 20, 30, 50, 50, ZoomMode.WidthHeight).setRoundCorner(50);
//        }

        // 二维码
        Image qrImg = ImgUtil.read(qrPath);
        qrImg = ImgUtil.scale(qrImg, 363, 363);
        postCombiner.addImageElement(ImgUtil.toBufferedImage(qrImg), 68, 192);
        //加文本元素
        Merchant merchant = merchantService.getById(loginUser.getMerchantId());
        String merchantName = merchant.getMerchantName();
        boolean addMore = false;
        if (merchant.getMerchantName().length() > 14 ) {
            merchantName = merchant.getMerchantName().substring(0, 14);
            addMore = true;
        }
        int textLength = merchantName.length() * 30;
        int x = 250 - textLength / 2;
        if (addMore) {
            merchantName = merchantName +  "···";
        }
        postCombiner.addTextElement(merchantName, 30, x, 47).setColor(255, 255, 255);
        //执行图片合并
        postCombiner.combine();
        //可以保存到本地
        postCombiner.save(savePath);
        return success("生成成功", serverUrl.concat("/" + filePath));
    }


}
