package com.yiqi.admin.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yiqi.common.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiqi.app.domain.AppUser;
import com.yiqi.app.domain.AppUserAddress;
import com.yiqi.app.domain.AppUserBillMstr;
import com.yiqi.app.domain.dto.MemberBillMstrQueryByMemberDTO;
import com.yiqi.app.domain.vo.AppUserInfoVO;
import com.yiqi.app.domain.vo.AppUserVO;
import com.yiqi.app.domain.vo.MemberInfoVO;
import com.yiqi.app.service.IAppUserAddressService;
import com.yiqi.app.service.IAppUserBillMstrService;
import com.yiqi.app.service.IAppUserService;
import com.yiqi.common.annotation.Log;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.controller.BaseController;
import com.yiqi.common.core.domain.AjaxResult;
import com.yiqi.common.core.domain.BaseEntity;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.core.page.TableDataInfo;
import com.yiqi.common.enums.BusinessType;
import com.yiqi.common.enums.SourceType;
import com.yiqi.common.enums.StatusType;
import com.yiqi.common.utils.SecurityUtils;
import com.yiqi.common.utils.StringUtils;
import com.yiqi.common.utils.poi.ExcelUtil;
import com.yiqi.recharge.domain.RechargePasswordCard;
import com.yiqi.recharge.service.IRechargePasswordCardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 * 用户Controller
 *
 * @author ruoyi
 * @date 2023-09-27
 */
@Api(tags = "管理后台 - 用户")
@RestController
@RequestMapping(UrlConstants.managerApi + "/app/user")
public class AppUserController extends BaseController {
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private IRechargePasswordCardService rechargePasswordCardService;
    @Autowired
    private IAppUserAddressService appUserAddressService;

    @Autowired
    private IAppUserBillMstrService appUserBillMstrService;

    @Validated
    @GetMapping(value = "/getUserByPhone")
    @ApiOperation("根据手机号查询用户")
    public R<AppUserVO> getUserByPhoneOrName(@RequestParam(required = false) @ApiParam("手机号")
                                             String phoneNumber
            , @RequestParam(required = false) @Param("订单类型") String orderType)
            throws Exception {
        if (StringUtils.isEmpty(phoneNumber)) {
            throw new ServiceException("请先输入手机号");
        }
        AppUser appUser = appUserService.getOne(new QueryWrapper<AppUser>().lambda().eq(AppUser::getPhoneNumber, phoneNumber)
                .eq(AppUser::getStatus, StatusType.OK.getCode()), false);
        if (appUser == null) {
            throw new ServiceException("未查询到客户");
        }
        AppUserVO appUserVO = new AppUserVO();
        BeanUtils.copyProperties(appUser, appUserVO);
        appUserVO.setPointBalance(appUser.getPoint());
        List<AppUserAddress> addresses = appUserAddressService.page(new Page<>(1, 1)
                , new QueryWrapper<AppUserAddress>().lambda()
                        .eq(AppUserAddress::getAppUserId, appUser.getId())
                        .orderByDesc(AppUserAddress::getIsDefault)
                        .orderByDesc(AppUserAddress::getCreateTime)).getRecords();
        if (addresses.size() > 0) {
            appUserVO.setDefaultAddress(addresses.get(0));
        }

        RechargePasswordCard rechargePasswordCard = rechargePasswordCardService.selectTotalBalanceGroupByAppUser(appUser.getId(), orderType);
        appUserVO.setRechargeBalance(rechargePasswordCard.getRechargeBalance());
        appUserVO.setGiveBalance(rechargePasswordCard.getGiveBalance());
        appUserVO.setWelfareBalance(rechargePasswordCard.getWelfareBalance());
        return R.ok(appUserVO);
    }

    /**
     * 查询用户列表
     */
    @PreAuthorize("@ss.hasPermi('app:user:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询用户列表")
    public TableDataInfo list(AppUser appUser) {
        startPage();
        List<AppUser> list = appUserService.selectAppUserList(appUser);
        return getDataTable(list);
    }

    /**
     * 导出用户列表
     */
    @PreAuthorize("@ss.hasPermi('app:user:export')")
    @Log(title = "用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出用户列表")
    public void export(HttpServletResponse response, AppUser appUser) {
        List<AppUser> list = appUserService.selectAppUserList(appUser);
        ExcelUtil<AppUser> util = new ExcelUtil<AppUser>(AppUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    /**
     * 获取用户详细信息
     */
    @PreAuthorize("@ss.hasPermi('app:user:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取用户详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(appUserService.selectAppUserById(id));
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('app:user:add')")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增用户")
    public AjaxResult add(@RequestBody AppUser appUser) {
        appUser.setCreateById(getUserId());
        appUser.setCreateBy(getUsername());
        return toAjax(appUserService.insertAppUser(appUser));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('app:user:edit')")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改用户")
    public AjaxResult edit(@RequestBody AppUser appUser) {
        appUser.setUpdateById(getUserId());
        appUser.setUpdateBy(getUsername());
        return toAjax(appUserService.updateAppUser(appUser));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('app:user:remove')")
    @Log(title = "用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除用户")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(appUserService.deleteAppUserByIds(ids));
    }

    /**
     * 修改用户状态
     */
    @PreAuthorize("@ss.hasPermi('app:user:edit')")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PostMapping(value = "updateStatus")
    @ApiOperation(value = "修改用户状态")
    public AjaxResult updateAppUserStatus(@RequestBody AppUser appUser) {
        return toAjax(appUserService.updateAppUserStatus(appUser));
    }

    @GetMapping(value = "/getMemberInfoById")
    @ApiOperation(value = "获取会员详情基本信息")
    public R<MemberInfoVO> getMemberInfoById(@RequestParam(name = "appUserId") Long appUserId) {
        MemberInfoVO memberInfoVO = new MemberInfoVO();
        AppUserInfoVO appUserInfo = appUserService.getAppUserInfoById(appUserId);
        if (appUserInfo != null) {
            BeanUtils.copyProperties(appUserInfo, memberInfoVO);
        }
        RechargePasswordCard rechargePasswordCard = rechargePasswordCardService.selectTotalBalanceGroupByAppUser(appUserId);
        if (rechargePasswordCard != null) {
            memberInfoVO.setRechargeBalance(rechargePasswordCard.getRechargeBalance());
            memberInfoVO.setGiveBalance(rechargePasswordCard.getGiveBalance());
            memberInfoVO.setPointBalance(0);
            memberInfoVO.setWelfareBalance(rechargePasswordCard.getWelfareBalance());
        } else {
            memberInfoVO.setRechargeBalance(BigDecimal.ZERO);
            memberInfoVO.setGiveBalance(BigDecimal.ZERO);
            memberInfoVO.setPointBalance(0);
            memberInfoVO.setWelfareBalance(BigDecimal.ZERO);
        }
        return R.ok(memberInfoVO);
    }

    @PostMapping(value = "/getMemberBillMstrInfo")
    @ApiOperation(value = "获取会员消费明细")
    public R<Page<AppUserBillMstr>> getMemberBillMstrInfo(@RequestBody MemberBillMstrQueryByMemberDTO memberBillMstrQueryByMemberDTO) {
        LambdaQueryWrapper<AppUserBillMstr> queryWrapper = new QueryWrapper<AppUserBillMstr>().lambda()
                .eq(AppUserBillMstr::getAppUserId, memberBillMstrQueryByMemberDTO.getAppUserId());
        if (SourceType.STORE.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
            queryWrapper.eq(AppUserBillMstr::getSourceType, SourceType.STORE.getCode());
            queryWrapper.eq(AppUserBillMstr::getOrgId, SecurityUtils.getLoginUser().getOrgId());
        }
        if(StringUtils.isNotBlank(memberBillMstrQueryByMemberDTO.getRechargeCardSn())){
            queryWrapper.eq(AppUserBillMstr::getRechargeCardNo, memberBillMstrQueryByMemberDTO.getRechargeCardSn());
        }
        queryWrapper.orderByDesc(BaseEntity::getCreateTime);
        return R.ok(appUserBillMstrService.page(new Page<>(memberBillMstrQueryByMemberDTO.getPageNum()
                        , memberBillMstrQueryByMemberDTO.getPageSize())
                , queryWrapper));
    }
}
