package org.jeecg.modules.system.app.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.app.form.CreateOrderForm;
import org.jeecg.modules.app.form.InsureOrderInfoForm;
import org.jeecg.modules.app.form.UserPayForm;
import org.jeecg.modules.app.service.IOrderService;
import org.jeecg.modules.pay.config.WeChatProfitSharingService;
import org.jeecg.modules.system.app.dto.ExportConditionDTO;
import org.jeecg.modules.system.app.entity.AppOrder;
import org.jeecg.modules.system.app.entity.InsureOrderInfo;
import org.jeecg.modules.system.app.entity.InsurePrice;
import org.jeecg.modules.system.app.form.AppOrderPageForm;
import org.jeecg.modules.system.app.form.PriceChangeForm;
import org.jeecg.modules.system.app.form.RefundOrderPageForm;
import org.jeecg.modules.system.app.service.IAppOrderService;
import org.jeecg.modules.system.app.service.IInsureOrderInfoService;
import org.jeecg.modules.system.app.service.IInsurePriceService;
import org.jeecg.modules.system.app.vo.AppOrderInfoVO;
import org.jeecg.modules.system.app.vo.ExportConditionVO;
import org.jeecg.modules.system.app.vo.OrderPageVO;
import org.jeecg.modules.system.app.vo.RefundOrderPageVO;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 订单表
 * @Author: jeecg-boot
 * @Date: 2025-07-03
 * @Version: V1.0
 */
@Tag(name = "订单表")
@RestController
@RequestMapping("/app/appOrder")
@Slf4j
public class AppOrderController extends JeecgController<AppOrder, IAppOrderService> {
    @Autowired
    private IAppOrderService appOrderService;
    @Autowired
    private WeChatProfitSharingService weChatProfitSharingService;
    @Autowired
    private IOrderService orderService;

    /**
     * 分页列表查询
     *
     * @param appOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "订单表-分页列表查询")
    @Operation(summary = "订单表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<AppOrder>> queryPageList(AppOrder appOrder,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) {


        QueryWrapper<AppOrder> queryWrapper = QueryGenerator.initQueryWrapper(appOrder, req.getParameterMap());
        Page<AppOrder> page = new Page<AppOrder>(pageNo, pageSize);
        IPage<AppOrder> pageList = appOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 订单分页
     *
     * @param appOrderPageForm
     * @return
     */
    @Operation(summary = "订单-分页列表查询")
    @PostMapping(value = "/queryPage")
    public Result<Page<OrderPageVO>> queryPage(@RequestBody AppOrderPageForm appOrderPageForm) {
        return Result.OK(appOrderService.queryPage(appOrderPageForm));
    }

    /**
     * 查询详情
     *
     * @param orderId
     * @return
     */
    @Operation(summary = "订单-查询详情")
    @GetMapping(value = "/queryInfoById/{orderId}")
    public Result<AppOrderInfoVO> queryInfoById(@PathVariable(name = "orderId") String orderId) {
        return Result.OK(appOrderService.queryInfoById(orderId));
    }

    /**
     * 添加
     *
     * @param appOrder
     * @return
     */
    @AutoLog(value = "订单表-添加")
    @Operation(summary = "订单表-添加")
    @RequiresPermissions("org.jeecg.modules.app:nm_order:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody AppOrder appOrder) {
        appOrderService.save(appOrder);

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param appOrder
     * @return
     */
    @AutoLog(value = "订单表-编辑")
    @Operation(summary = "订单表-编辑")
    @RequiresPermissions("org.jeecg.modules.app:nm_order:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody AppOrder appOrder) {
        appOrderService.updateById(appOrder);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单表-通过id删除")
    @Operation(summary = "订单表-通过id删除")
    @RequiresPermissions("org.jeecg.modules.app:nm_order:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        appOrderService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 分账
     *
     * @param orderCode
     * @return
     * @throws Exception
     */
    @AutoLog(value = "分账")
    @Operation(summary = "分账")
//    @RequiresPermissions("org.jeecg.modules.app:nm_order:profitSharing")
    @PutMapping(value = "/profitSharing")
    public Result<JSONObject> profitSharing(@RequestParam(name = "orderCode", required = true) String orderCode) throws Exception {
        JSONObject jsonObject = weChatProfitSharingService.profitSharing(orderCode);
        return Result.OK(jsonObject);
    }

    /**
     * 分账结果更新
     *
     * @param orderCode
     * @return
     * @throws Exception
     */
    @AutoLog(value = "分账结果更新")
    @Operation(summary = "分账结果更新")
    @PutMapping(value = "/profitSharingReflush")
    public Result<JSONObject> profitSharingReflush(@RequestParam(name = "orderCode", required = true) String orderCode) throws Exception {
        JSONObject jsonObject = weChatProfitSharingService.getProfitSharingResult(orderCode);
        return Result.OK(jsonObject);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "订单表-批量删除")
    @Operation(summary = "订单表-批量删除")
    @RequiresPermissions("org.jeecg.modules.app:nm_order:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.appOrderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "订单表-通过id查询")
    @Operation(summary = "订单表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<AppOrder> queryById(@RequestParam(name = "id", required = true) String id) {
        AppOrder appOrder = appOrderService.getById(id);
        if (appOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(appOrder);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param appOrder
     */
    @RequiresPermissions("org.jeecg.modules.app:nm_order:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AppOrder appOrder) {
        return super.exportXls(request, appOrder, AppOrder.class, "订单表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("org.jeecg.modules.app:nm_order:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AppOrder.class);
    }


    /**
     * @description 赛事条件导出-查询赛事
     * params
     * @author SheepHy
     * @date 2025/9/17
     * return   {@link }
     **/
    @Operation(summary = "赛事条件导出-查询赛事")
    @GetMapping(value = "/exportConditionByName")
    public Result<List<ExportConditionVO>> exportConditionByName(@RequestParam(value = "name", required = false) String name) {
        return Result.OK(appOrderService.exportConditionByName(name));
    }

    /**
     * @description 赛事条件导出-查询项目
     * params
     * @author SheepHy
     * @date 2025/9/17
     * return   {@link }
     **/
    @Operation(summary = "赛事条件导出-查询项目")
    @GetMapping(value = "/exportConditionByProjectName")
    public Result<List<ExportConditionVO>> exportConditionByProjectName(@RequestParam(value = "projectName", required = false) String projectName,
                                                                        @RequestParam(value = "gameId", required = false) String gameId) {
        return Result.OK(appOrderService.exportConditionByProjectName(projectName, gameId));
    }

    /**
     * @description 赛事条件导出
     * params
     * @author SheepHy
     * @date 2025/9/17
     * return   {@link }
     **/
    @Operation(summary = "赛事条件导出")
    @PostMapping(value = "/exportCondition")
    public ResponseEntity<byte[]> exportCondition(@RequestBody ExportConditionDTO exportConditionDTO) throws IOException {
        try {
            byte[] excelBytes = appOrderService.exportCondition(exportConditionDTO);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "export_condition.xlsx");
            headers.setContentLength(excelBytes.length);

            return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("导出Excel文件失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @Operation(summary = "退款管理-分页列表查询")
    @PostMapping(value = "/refundOrderPageList")
    public Result<IPage<RefundOrderPageVO>> refundOrderPageList(@RequestBody RefundOrderPageForm refundOrderPageForm) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String orgCode = user.getOrgCode();
        if (!ObjectUtil.equals("A01", orgCode)) {
            refundOrderPageForm.setOrderCode(orgCode);
        }
        IPage<RefundOrderPageVO> page = appOrderService.refundOrderPageList(refundOrderPageForm);
        return Result.OK(page);
    }

    @Resource
    private IInsureOrderInfoService insureOrderInfoService;
    @Resource
    private IInsurePriceService insurePriceService;
    @Resource
    private ISysUserService sysUserService;

    @Transactional(rollbackFor = Exception.class)
    @Operation(summary = "订单管理-订单改价")
    @PostMapping(value = "/priceChange")
    public Result<UserPayForm> priceChange(@RequestBody PriceChangeForm priceChangeForm) {

        return Result.OK(orderService.orderChangePrice(priceChangeForm));
    }
}
