package com.ruoyi.app.pay;

import com.alibaba.fastjson.JSON;
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.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.order.ZaloPayCommonService;
import com.ruoyi.app.utils.DateUtil;
import com.ruoyi.app.utils.IpUtils;
import com.ruoyi.app.utils.Md5Pay;
import com.ruoyi.app.utils.zaloPay.ZaloPay;
import com.ruoyi.app.utils.zaloPay.ZaloPayConfig;
import com.ruoyi.app.utils.zaloPay.ZaloPayCreateOrderResponse;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
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.poi.ExcelUtil;
import com.ruoyi.system.domain.PosOrder;
import com.ruoyi.system.domain.UserBilling;
import com.ruoyi.system.domain.vo.BillDTO;
import com.ruoyi.system.mapper.UserBillingMapper;
import com.ruoyi.system.service.IInfoUserService;
import com.ruoyi.system.service.IPosOrderService;
import com.ruoyi.system.service.IUserBillingService;
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.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * BillingController
 *
 * @author ruoyi
 * @date 2023-09-06
 */
@RestController
@RequestMapping("/Billing/billing")
public class UserBillingController extends BaseController
{
    @Autowired
    private IUserBillingService userBillingService;
    @Autowired
    private UserBillingMapper userBillingMapper;
    @Autowired
    private IPosOrderService posOrderService;
    @Autowired
    private IInfoUserService infoUserService;
    @Autowired
    private ZaloPayCommonService zaloPayCommonService;
    @Autowired
    private ZaloPayConfig zaloPayConfig;
    @Autowired
    private ZaloPay zaloPay;

    /**
     * 商家日账单数据
     * @param token
     * @param page
     * @param size
     * @param riqi
     * @return
     */
    @Anonymous
    @Auth
    @GetMapping("/getzddaylist")
    public AjaxResult getzddaylist(@RequestHeader String token,
                                    @RequestParam Long page,
                                    @RequestParam Long size,
                                    @RequestParam String riqi)
    {
        JwtUtil jwtUtil = new JwtUtil();
        Long id = Long.valueOf(jwtUtil.getusid(token));
        List<UserBilling> list = userBillingMapper.getdaylist(id,riqi,(page-1)*size,size);
        setYhInfo(list);
        BillDTO sum = userBillingMapper.getdaysum(id,riqi);
        JSONObject org = new JSONObject();
        org.put("shul",sum.getSul());
        org.put("sum",sum.getShouru());
        org.put("list",list);
        return success(MessageUtils.message("no.success"), org);
    }

    /**
     * 商家周账单数据
     * @param token
     * @param page
     * @param size
     * @param riqi
     * @return
     */
    @Anonymous
    @Auth
    @GetMapping("/getzdmeeklist")
    public AjaxResult getzdmeeklist(@RequestHeader String token,
                                   @RequestParam Long page,
                                   @RequestParam Long size,
                                   @RequestParam String riqi)
    {
        JwtUtil jwtUtil = new JwtUtil();
        Long id = Long.valueOf(jwtUtil.getusid(token));
        List<UserBilling> list = userBillingMapper.getmeeklist(id,riqi,(page-1)*size,size);
        setYhInfo(list);
        BillDTO sum = userBillingMapper.getmeeksum(id,riqi);
        JSONObject org = new JSONObject();
        org.put("shul",sum.getSul());
        org.put("sum",sum.getShouru());
        org.put("list",list);
        return success(MessageUtils.message("no.success"), org);
    }

    private void setYhInfo(List<UserBilling> list) {
        if(!list.isEmpty()){
            List<String> orderIds=list.stream().map(UserBilling::getDdId).collect(Collectors.toList());
            LambdaQueryWrapper<PosOrder> query = new LambdaQueryWrapper<>();
            query.in(PosOrder::getDdId,orderIds);
            List<PosOrder> orders = posOrderService.list(query);
            list.forEach(billing -> {
                orders.stream().filter(o -> o.getDdId().toString().equals(billing.getDdId())).findFirst().ifPresent(o -> {
                    billing.setActivity(o.getActivity());
                    billing.setMdActivity(o.getMdActivity());
                    billing.setMdActivity(o.getMdActivity());
                    billing.setYhId(o.getYhId());
                    billing.setYhName(o.getYhName());
                    billing.setDiscountAmount(o.getDiscountAmount());
                    billing.setMdYhId(o.getMdYhId());
                    billing.setMdYhName(o.getMdYhName());
                    billing.setMdDiscountAmount(o.getMdDiscountAmount());
                    billing.setSalesName(o.getSalesName());
                    billing.setMdSalesName(o.getMdSalesName());
                    billing.setSalesReduction(o.getSalesReduction());
                    billing.setMdSalesReduction(o.getMdSalesReduction());
                    billing.setPoints(o.getPoints());
                    billing.setPointsReduction(o.getPointsReduction());
                });
            });
        }
    }

    /**
     * 商家月账单数据
     * @param token
     * @param page
     * @param size
     * @param riqi
     * @return
     */
    @Anonymous
    @Auth
    @GetMapping("/getzdmatlist")
    public AjaxResult getzdmatlist(@RequestHeader String token,
                                @RequestParam Long page,
                                @RequestParam Long size,
                                @RequestParam String riqi)
    {
        JwtUtil jwtUtil = new JwtUtil();
        Long id = Long.valueOf(jwtUtil.getusid(token));
        List<UserBilling> list = userBillingMapper.getmatlist(id,riqi,(page-1)*size,size);
        setYhInfo(list);
        BillDTO sum = userBillingMapper.getmatsum(id,riqi);
        JSONObject org = new JSONObject();
        org.put("shul",sum.getSul());
        org.put("sum",sum.getShouru());
        org.put("list",list);
        return success(MessageUtils.message("no.success"), org);
    }

    //充值
    @Anonymous
    @Auth
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @RequestMapping(value = "/userRecharge", method = {RequestMethod.GET,RequestMethod.POST})
    public AjaxResult userRecharge(@RequestHeader String token, @RequestParam String language, @RequestParam Long amount, HttpServletRequest request)
    {
        JwtUtil jwtUtil = new JwtUtil();
        IpUtils ipUtils = new IpUtils();
        String ip = ipUtils.getIpAddr(request);
        String id = jwtUtil.getusid(token);
        Long timeLong = System.currentTimeMillis();
        Md5Pay md5Pay = new Md5Pay();
        String orderid = "CZ"+timeLong;
        System.out.println("orderid:"+orderid);
        String obj =  md5Pay.VNPay(language,orderid,String.valueOf(amount),ip);
        UserBilling billing = new UserBilling();
        billing.setUserId(Long.valueOf(id));
        billing.setType(String.valueOf(1));
        billing.setDdId(orderid);
        billing.setAmount(Double.valueOf(amount));
        billing.setState(String.valueOf(3));
        billing.setIllustrate("用户充值");
        billing.setPaymentMethod("app线上充值");
        billing.setUrl(obj);
        Boolean reg = userBillingService.saveOrUpdate(billing);
        if(reg){
            return success(MessageUtils.message("no.order.create.success"), obj);
        }else {
            return error();
        }
    }


    /**
     *  充值使用ZaloPay
     * @param token
     * @param language
     * @param amount
     * @param request
     * @return
     */
    @Anonymous
    @Auth
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @RequestMapping(value = "/userRechargeZaloPay", method = {RequestMethod.GET,RequestMethod.POST})
    public AjaxResult userRechargeZaloPay(@RequestHeader String token, @RequestParam String language, @RequestParam Long amount,@RequestParam String payType, HttpServletRequest request) throws Exception {
        JwtUtil jwtUtil = new JwtUtil();
        String userId = jwtUtil.getusid(token);
        Long timeLong = System.currentTimeMillis();
        String orderid = "CZ"+timeLong;
        System.out.println("orderid:"+orderid);
        ZaloPayCreateOrderResponse obj =  zaloPay.createOrder(userId,orderid,amount,"user recharch by zalopay",zaloPayConfig.getZaloPayConfig(payType));
        zaloPayCommonService.setZaloPayOrder(orderid, JSON.toJSONString(obj),null,null,null,payType);
        UserBilling billing = new UserBilling();
        billing.setUserId(Long.valueOf(userId));
        billing.setType(String.valueOf(1));
        billing.setDdId(orderid);
        billing.setAmount(Double.valueOf(amount));
        billing.setState(String.valueOf(3));
        billing.setIllustrate("用户充值");
        billing.setPaymentMethod("zalopay线上充值");
        billing.setUrl(JSONObject.toJSONString(obj));
        Boolean reg = userBillingService.saveOrUpdate(billing);
        if(reg){
            return success(MessageUtils.message("no.order.create.success"), obj);
        }else {
            return error();
        }
    }


    //查询用户账户及余额
    @Anonymous
    @Auth
    @GetMapping("/getUsbalance")
    public AjaxResult getUsbalance(@RequestHeader String token,
                                   @RequestParam Integer page,
                                   @RequestParam Integer size,
                                   @RequestParam boolean sort,
                                   @RequestParam(defaultValue = "") String type)
    {
        JwtUtil jwtUtil = new JwtUtil();
        DateUtil dateUtil = new DateUtil();
        String id = jwtUtil.getusid(token);
        if (!"".equals(type)){
            JSONObject org = new JSONObject();
            IPage<UserBilling> palist = new Page<>(page,size);
            QueryWrapper<UserBilling> wrapper = new QueryWrapper<>();
            int sumlist = userBillingMapper.gettypesum(Long.valueOf(id), Long.valueOf(type));
            wrapper.eq("user_id",id);
            wrapper.eq("type",type);
            wrapper.orderBy(true, sort, "cretim");
            IPage<UserBilling> mmlist =  userBillingService.page(palist,wrapper);
            List<UserBilling> list = mmlist.getRecords();
            JSONArray arr = new JSONArray();
            for(int i=0;i<list.size();i++){
                JSONObject ject = new JSONObject();
                ject.put("id",list.get(i).getId());
                ject.put("user",infoUserService.getById(list.get(i).getUserId()));
                ject.put("type",list.get(i).getType());
                PosOrder order = posOrderService.getById(list.get(i).getDdId());
                ject.put("ddId",order==null?list.get(i).getDdId():order.getDdId());
                ject.put("amount",list.get(i).getAmount());
                ject.put("divvy",list.get(i).getDivvy());
                ject.put("state",list.get(i).getState());
                ject.put("mdId",list.get(i).getMdId());
                ject.put("illustrate",list.get(i).getIllustrate());
                ject.put("paymentMethod",list.get(i).getPaymentMethod());
                ject.put("accountNumber",list.get(i).getAccountNumber());
                ject.put("url",list.get(i).getUrl());
                ject.put("cretim",dateUtil.setDate(list.get(i).getCretim()));
                arr.add(ject);
            }
            org.put("sum",sumlist);
            org.put("list",arr);
            return success(MessageUtils.message("no.success"), org);
        }else {
            JSONObject org = new JSONObject();
            IPage<UserBilling> palist = new Page<>(page,size);
            QueryWrapper<UserBilling> wrapper = new QueryWrapper<>();
            int zlist = userBillingMapper.gettypesum(Long.valueOf(id), 1L);
            int txlist = userBillingMapper.gettypesum(Long.valueOf(id), 2L);
            int xfei = userBillingMapper.gettypesum(Long.valueOf(id), 3L);
            wrapper.eq("user_id",id);
            wrapper.orderBy(true, sort, "cretim");
            IPage<UserBilling> mmlist =  userBillingService.page(palist,wrapper);
            List<UserBilling> list = mmlist.getRecords();
            JSONArray arr = new JSONArray();
            for(int i=0;i<list.size();i++){
                JSONObject ject = new JSONObject();
                ject.put("id",list.get(i).getId());
                ject.put("user",infoUserService.getById(list.get(i).getUserId()));
                ject.put("type",list.get(i).getType());
                PosOrder order = posOrderService.getById(list.get(i).getDdId());
                ject.put("ddId",order==null?list.get(i).getDdId():order.getDdId());
                ject.put("amount",list.get(i).getAmount());
                ject.put("divvy",list.get(i).getDivvy());
                ject.put("state",list.get(i).getState());
                ject.put("mdId",list.get(i).getMdId());
                ject.put("illustrate",list.get(i).getIllustrate());
                ject.put("paymentMethod",list.get(i).getPaymentMethod());
                ject.put("accountNumber",list.get(i).getAccountNumber());
                ject.put("cretim",dateUtil.setDate(list.get(i).getCretim()));
                ject.put("url",list.get(i).getUrl());
                arr.add(ject);
            }
            int sum = zlist-txlist-xfei;
            org.put("sum",sum);
            org.put("list",arr);
            return success(MessageUtils.message("no.success"), org);
        }
    }
    /**
     * 查询Billing列表
     */
    @PreAuthorize("@ss.hasPermi('Billing:billing:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserBilling userBilling)
    {
        startPage();
        List<UserBilling> list = userBillingService.selectUserBillingList(userBilling);
        return getDataTable(list);
    }

    /**
     * 导出Billing列表
     */
    @PreAuthorize("@ss.hasPermi('Billing:billing:export')")
    @Log(title = "Billing", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserBilling userBilling)
    {
        List<UserBilling> list = userBillingService.selectUserBillingList(userBilling);
        ExcelUtil<UserBilling> util = new ExcelUtil<UserBilling>(UserBilling.class);
        util.exportExcel(response, list, MessageUtils.message("no.export.excel.billing"));
    }

    /**
     * 获取Billing详细信息
     */
    @PreAuthorize("@ss.hasPermi('Billing:billing:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(userBillingService.selectUserBillingById(id));
    }

    /**
     * 新增Billing
     */
    @PreAuthorize("@ss.hasPermi('Billing:billing:add')")
    @Log(title = "Billing", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserBilling userBilling)
    {
        return toAjax(userBillingService.insertUserBilling(userBilling));
    }

    /**
     * 修改Billing
     */
    @PreAuthorize("@ss.hasPermi('Billing:billing:edit')")
    @Log(title = "Billing", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserBilling userBilling)
    {
        return toAjax(userBillingService.updateUserBilling(userBilling));
    }

    /**
     * 删除Billing
     */
    @PreAuthorize("@ss.hasPermi('Billing:billing:remove')")
    @Log(title = "Billing", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(userBillingService.deleteUserBillingByIds(ids));
    }
}
