// PointsRechargeController.java
package com.yami.shop.platform.controller;

import cn.hutool.core.util.ObjectUtil;
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.yami.shop.bean.model.PointsRecharge;
import com.yami.shop.bean.po.EnterpriseUserPo;
import com.yami.shop.bean.vo.PointsRechargeVO;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.R;
import com.yami.shop.security.platform.model.YamiSysUser;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.service.PointsRechargeService;
import com.yami.shop.service.UserService;
import com.yami.shop.sys.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 积分充值 Controller
 *
 * @author fbj
 * @since 2025-09-XX
 */
@Slf4j
@RestController
@RequestMapping("/platform/pointsRecharge")
@AllArgsConstructor
public class PointsRechargeController {

    private final PointsRechargeService pointsRechargeService;
    @Autowired
    private SysUserService sysUserService;

    /**
     * 分页获取积分充值列表
     */
    @GetMapping("/page")
    public R<IPage<PointsRecharge>> page(PageParam<PointsRecharge> pageParam, PointsRecharge pointsRecharge) {
        getPointsRecharge(pointsRecharge);
//        IPage<PointsRecharge> page = pointsRechargeService.page(pageParam,new LambdaQueryWrapper<PointsRecharge>()
//                .in(ObjectUtils.isNotEmpty(pointsRecharge.getChannelIdList()),PointsRecharge::getChannelId,pointsRecharge.getChannelIdList())
//                .eq(ObjectUtils.isNotEmpty(pointsRecharge.getUserPhone()),PointsRecharge::getUserPhone,pointsRecharge.getUserPhone())
//                .orderByDesc(PointsRecharge::getCreateTime)
//        );
        return R.SUCCESS(pointsRechargeService.findPage(pageParam,pointsRecharge));
    }


    /**
     * 获取积分充值统计列表
     */
    @GetMapping("/statisticsList")
    public R<IPage<PointsRechargeVO>> statisticsList(PageParam<PointsRecharge> pageParam, PointsRecharge pointsRecharge) {
        getPointsRecharge(pointsRecharge);
        IPage<PointsRechargeVO> page = pointsRechargeService.statisticsList(pointsRecharge);
        return R.SUCCESS(page);
    }

    /**
     * 根据ID获取积分充值
     */
    @GetMapping("/{id}")
    public R<PointsRecharge> getById(@PathVariable Long id) {
        PointsRecharge pointsRecharge = pointsRechargeService.getById(id);
        return R.SUCCESS(pointsRecharge);
    }

    /**
     * 添加积分充值
     */
    @PostMapping
    public R<Void> save(@Valid @RequestBody PointsRecharge pointsRecharge) {
        pointsRechargeService.save(pointsRecharge);
        return R.SUCCESS();
    }

    /**
     * 更新积分充值
     */
    @PutMapping
    public R<Void> update(@Valid @RequestBody PointsRecharge pointsRecharge) {
        pointsRechargeService.updateById(pointsRecharge);
        return R.SUCCESS();
    }

    /**
     * 删除积分充值
     */
    @DeleteMapping
    public R<Void> delete(@RequestBody Long[] ids) {
        pointsRechargeService.removeByIds(Arrays.asList(ids));
        return R.SUCCESS();
    }


    /**
     * 导出积分充值导入模板
     */
    @GetMapping("/exportTemplate")
    @ApiOperation(value = "导出积分充值导入模板", notes = "导出积分充值导入模板")
    public void exportTemplate(HttpServletResponse response) {
        try {
            pointsRechargeService.exportTemplate(response);
        } catch (Exception e) {
            log.error("导出积分充值模板失败：", e);
            throw new RuntimeException("导出模板失败：" + e.getMessage());
        }
    }

    /**
     * 导入积分充值数据
     */
    @PostMapping("/import")
    @ApiOperation(value = "导入积分充值数据", notes = "导入积分充值数据")
    public R<String> importPointsRecharge(@RequestParam("file") MultipartFile file) {
        //需要填写操作人
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        try {
            String result = pointsRechargeService.importPointsRecharge(file,sysUserId);
            return R.SUCCESS(result);
        } catch (Exception e) {
            log.error("导入积分充值数据失败：", e);
            return R.FAIL("导入失败：" + e.getMessage());
        }
    }
    /**
     * 导出积分
     * @param pointsRecharge
     * @param response
     */
    @GetMapping("/export")
    @ApiOperation("后管端-积分列表导出")
    public void export(PointsRecharge pointsRecharge, HttpServletResponse response) {
        getPointsRecharge(pointsRecharge);
        pointsRechargeService.export(pointsRecharge,response);
    }
    private void getPointsRecharge(PointsRecharge pointsRecharge){
        if (pointsRecharge.getChannelIdList()==null||pointsRecharge.getChannelIdList().isEmpty()){
            throw new GlobalException("请求参数-所属企业不允许为空");
        }
        if (ObjectUtil.isEmpty(pointsRecharge.getUserAttrType())){
            pointsRecharge.setUserAttrType("1");//默认查询正常人员属性
        }
        if (pointsRecharge.getChannelIdList().contains(0L)){
            Long userId = null;
            try {
                userId = SecurityUtils.getSysUser().getUserId();
            } catch (Exception e) {
                throw new GlobalException("获取当前登录用户失败");
            }
            List<Long> channelIdList =  sysUserService.findByUserIdListId(userId);
            pointsRecharge.setChannelIdList(channelIdList);
            if (userId != Constant.SUPER_ADMIN_ID&&(pointsRecharge.getChannelIdList()==null||pointsRecharge.getChannelIdList().isEmpty())){
                List<Long> longs = new ArrayList<>();
                longs.add(0L);
                pointsRecharge.setChannelIdList(longs);
            }
        }
    }


}
