package com.ruoyi.controller;

import cn.hutool.core.date.DateUtil;
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.extension.plugins.pagination.Page;
import com.ruoyi.annotations.UserLoginToken;
import com.ruoyi.code.DictConstant;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.page.PageResult;
import com.ruoyi.controller.req.*;
import com.ruoyi.controller.resp.*;
import com.ruoyi.enums.order.OrderStatusEnums;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.advertisingimages.entity.AdvertisingImages;
import com.ruoyi.frequency.advertisingimages.service.AdvertisingImagesService;
import com.ruoyi.frequency.block.entity.Block;
import com.ruoyi.frequency.block.service.BlockService;
import com.ruoyi.frequency.browserecord.entity.BrowseRecord;
import com.ruoyi.frequency.browserecord.service.BrowseRecordService;
import com.ruoyi.frequency.collect.service.CollectService;
import com.ruoyi.frequency.customer.entity.Customer;
import com.ruoyi.frequency.customer.service.CustomerService;
import com.ruoyi.frequency.customer.service.UserService;
import com.ruoyi.frequency.enterprise.entity.Enterprise;
import com.ruoyi.frequency.enterprise.service.EnterpriseService;
import com.ruoyi.frequency.follow.entity.Follow;
import com.ruoyi.frequency.follow.service.FollowService;
import com.ruoyi.frequency.givewallerecord.service.GiveWalletRecordService;
import com.ruoyi.frequency.illegaldeductionrecord.service.IllegalDeductionRecordService;
import com.ruoyi.frequency.order.entity.Order;
import com.ruoyi.frequency.order.mapper.OrderMapper;
import com.ruoyi.frequency.order.service.OrderService;
import com.ruoyi.frequency.refereeuser.entity.RefereeUser;
import com.ruoyi.frequency.refereeuser.service.RefereeUserService;
import com.ruoyi.frequency.sale.entity.Sale;
import com.ruoyi.frequency.sale.service.SaleService;
import com.ruoyi.frequency.shield.entity.Shield;
import com.ruoyi.frequency.shield.service.ShieldService;
import com.ruoyi.frequency.store.entity.Store;
import com.ruoyi.frequency.store.service.StoreService;
import com.ruoyi.frequency.wallerecord.mapper.WalletRecordMapper;
import com.ruoyi.frequency.wallerecord.service.WalletRecordService;
import com.ruoyi.frequency.withdrawalrecord.mapper.WithdrawalRecordMapper;
import com.ruoyi.frequency.works.entity.Works;
import com.ruoyi.frequency.works.service.WorksService;
import com.ruoyi.frequency.workstype.service.WorksTypeService;
import com.ruoyi.post.frequency.post.entity.Post;
import com.ruoyi.post.frequency.post.service.PostService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.utils.BusinessUtil;
import com.ruoyi.vo.BodyIdReq;
import com.ruoyi.vo.RyController;
import com.ruoyi.vo.UserInfo;
import com.ruoyi.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户相关（表现师(技术)列表，余额）
 */
@CrossOrigin
@RestController
@RequestMapping("/api/user")
@Api(tags = "用户相关（表现师（技术）列表，余额）））")
public class ApiUserController extends RyController {

    @Autowired
    private WorksTypeService worksTypeService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private SaleService saleService;

    @Autowired
    private FollowService followService;

    @Autowired
    private PostService postService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CollectService collectService;

    @Autowired
    private WorksService worksService;

    @Autowired
    private BlockService blockService;

    @Autowired
    private ShieldService shieldService;

    @Autowired
    private BrowseRecordService browseRecordService;

    @Autowired
    private EnterpriseService enterpriseService;


    @PostMapping("/storePage")
    @ApiOperation(value = "表现师(技术)/企业列表", notes = "表现师(技术)/企业列表")
    public ResponseData<PageResult<Page<StorePageResp>>> storePage(@Valid @RequestBody StorePageReq req) {

        //是否是企业: 1不是 2企业
        switch (req.getIsWorkingDrawing()) {
            case 1:
                return worksTypeService.storePage(req, getUserVo());
            case 2:
                return enterpriseService.enterprisePage(req, getUserVo());
            default:
                return ResponseData.error(String.format("isWorkingDrawing参数错误: %s", req.getIsWorkingDrawing()));
        }
    }


    @PostMapping("/userData")
    @UserLoginToken
    @ApiOperation(value = "我的页面用户数据", notes = "我的页面用户数据")
    public ResponseData<UserDataResp> userData() {

        UserVo userVo = getUserVo();

        UserDataResp userDataResp = userData(userVo);

        return ResponseData.success(userDataResp);
    }

    @PostMapping("/otherUserData")
    @ApiOperation(value = "他人查看我的页面用户数据", notes = "我的页面用户数据")
    public ResponseData<UserDataResp> otherUserData(@RequestBody UserVo userVo) {
        UserDataResp userDataResp = userData(userVo);
        return ResponseData.success(userDataResp);
    }

    @Autowired
    private RefereeUserService refereeUserService;

    @Autowired
    private BusinessUtil businessUtil;

    @Autowired
    private OrderMapper orderMapper;

    private UserDataResp userData(UserVo userVo) {

        UserDataResp userDataResp = new UserDataResp();

        //用户类型 1设计师 2表现师 3销售(推广员)
        if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.设计师)) {
            Customer customer = customerService.getById(userVo.getUserId());
            userDataResp.setBalance(customer.getBalance());
            userDataResp.setAmount(customer.getConsumptionAmount());
            userDataResp.setOnlineDuration(customer.getOnlineDuration());
            userDataResp.setStar(customer.getStar());
            userDataResp.setIntegral(customer.getIntegral());
            userDataResp.setAccumulateIntegral(customer.getAccumulateIntegral());
        } else if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.表现师)) {
            Store store = storeService.getById(userVo.getUserId());
            userDataResp.setBalance(store.getBalance());
            userDataResp.setAmount(store.getIncome());
            userDataResp.setOnlineDuration(store.getOnlineDuration());
            userDataResp.setStar(store.getStar());
            userDataResp.setIntegral(store.getIntegral());
            userDataResp.setAccumulateIntegral(store.getAccumulateIntegral());

            //本月收益
            Date beginOfMonth = DateUtil.beginOfMonth(new Date());
            BigDecimal monthAmount = orderMapper.selectMonthBeforeAmount(beginOfMonth, userVo);
            userDataResp.setMonthAmount(monthAmount);
        } else if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.销售)) {
            Sale sale = saleService.getById(userVo.getUserId());
            userDataResp.setBalance(sale.getBalance());
        } else if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.企业)) {
            Enterprise enterprise = enterpriseService.getById(userVo.getUserId());
            userDataResp.setStar(enterprise.getStar());
            userDataResp.setAmount(enterprise.getServiceAmount());
            userDataResp.setOrderNum(enterprise.getServiceOrderNum());
        }


        //作品数
        LambdaQueryWrapper<Works> lambdaQueryWrapper = new QueryWrapper<Works>().lambda()
                .eq(Works::getDelFlag, PublicCommon.启用)
                .ne(Works::getIsHide, 2);
        if (UserEnums.customer.getCode().equals(userVo.getUserType())) {

            lambdaQueryWrapper.eq(Works::getCustomerId, userVo.getUserId());
        } else if (UserEnums.store.getCode().equals(userVo.getUserType())) {

            lambdaQueryWrapper.eq(Works::getStoreId, userVo.getUserId())
                    .eq(Works::getUserType, userVo.getUserType());
        } else if (UserEnums.enterprise.getCode().equals(userVo.getUserType())) {

            lambdaQueryWrapper.eq(Works::getStoreId, userVo.getUserId())
                    .eq(Works::getUserType, userVo.getUserType());
        }
        int worksNum = worksService.count(lambdaQueryWrapper);
        userDataResp.setWorksNum(worksNum);

        //粉丝数
        int fansNum = followService.count(new QueryWrapper<Follow>().lambda()
                .eq(Follow::getDelFlag, PublicCommon.启用)
                .eq(Follow::getFollowerUserType, userVo.getUserType())
                .eq(Follow::getFollowerUserId, userVo.getUserId()));
        userDataResp.setFansNum(fansNum);

        //动态数
        int postNum = postService.count(new QueryWrapper<Post>().lambda()
                .eq(Post::getDelFlag, PublicCommon.启用)
                .eq(Post::getUserType, userVo.getUserType())
                .eq(Post::getUserId, userVo.getUserId()));
        userDataResp.setPostNum(postNum);

        //收藏数
        CollectPageReq req = new CollectPageReq();
        req.setPageNo(1);
        req.setPageSize(1);
        req.setUserId(userVo.getUserId());
        req.setUserType(userVo.getUserType());

        //收藏作品数
        req.setType(1);
        userDataResp.setCollectWorksNum(collectService.getCollectWorksPage(req,userVo).getTotal());

        //收藏动态数
        req.setType(2);
        userDataResp.setCollectPostNum(collectService.getCollectPostPage(req,userVo).getTotal());

        //收藏新闻数
        req.setType(4);
        userDataResp.setCollectNewsNum(collectService.getCollectNewsPage(req,userVo).getTotal());

        userDataResp.setCollectNum(userDataResp.getCollectWorksNum()+userDataResp.getCollectPostNum()+userDataResp.getCollectNewsNum());


        //关注数
        int followNum = followService.count(new QueryWrapper<Follow>().lambda()
                .eq(Follow::getDelFlag, PublicCommon.启用)
                .eq(Follow::getUserType, userVo.getUserType())
                .eq(Follow::getUserId, userVo.getUserId()));
        userDataResp.setFollowNum(followNum);

        if (ObjectUtil.notEqual(userVo.getUserType(), PublicCommon.企业)) {
            //累计服务单数基数
            Integer num = Integer.valueOf(businessUtil.getDict(DictConstant.OrderDict.累计服务单数基数).getDictValue());

            //订单数
            int orderNum = orderService.count(new QueryWrapper<Order>().lambda()
                    .eq(Order::getDelFlag, PublicCommon.启用)
                    .ge(Order::getStatus, OrderStatusEnums.to_be_evaluated.getCode())
                    .eq(ObjectUtil.equal(UserEnums.customer.getCode(), userVo.getUserType()), Order::getCustomerId, userVo.getUserId())
                    .eq(ObjectUtil.equal(UserEnums.store.getCode(), userVo.getUserType()), Order::getStoreId, userVo.getUserId()));
            userDataResp.setOrderNum(orderNum + num);
        }

        //拉黑数
        int blockNum = blockService.count(new QueryWrapper<Block>().lambda()
                .eq(Block::getDelFlag, PublicCommon.启用)
                .eq(Block::getUserType, userVo.getUserType())
                .eq(Block::getUserId, userVo.getUserId()));
        userDataResp.setBlockNum(blockNum);


        //屏蔽数
        int shieldNum = shieldService.count(new QueryWrapper<Shield>().lambda()
                .eq(Shield::getDelFlag, PublicCommon.启用)
                .eq(Shield::getUserType, userVo.getUserType())
                .eq(Shield::getUserId, userVo.getUserId()));
        userDataResp.setShieldNum(shieldNum);

        //浏览数
        int browseNum = browseRecordService.count(new QueryWrapper<BrowseRecord>().lambda()
                .eq(BrowseRecord::getDelFlag, PublicCommon.启用)
                .eq(BrowseRecord::getType, 1) //浏览类型 1作品 2 动态
                .eq(BrowseRecord::getUserType, userVo.getUserType())
                .eq(BrowseRecord::getUserId, userVo.getUserId()));
        userDataResp.setBrowseNum(browseNum);

        //邀请数
        int inviteNum = refereeUserService.count(new QueryWrapper<RefereeUser>().lambda()
                .eq(RefereeUser::getDelFlag, PublicCommon.启用)
                .eq(RefereeUser::getParentUserId, userVo.getUserId())
                .eq(RefereeUser::getParentUserType, userVo.getUserType())
        );
        userDataResp.setInviteNum(inviteNum);

        userDataResp.setUserInfo(businessUtil.getUserInfo(userVo));
        return userDataResp;
    }

    @Autowired
    private UserService userService;

    @Autowired
    private WalletRecordMapper walletRecordMapper;

    @Autowired
    private WithdrawalRecordMapper withdrawalRecordMapper;

    @PostMapping("/storeAmountData")
    @UserLoginToken
    @ApiOperation(value = "表现师金额数据", notes = "用户金额数据")
    public ResponseData<StoreAmountDataResp> storeAmountData() {

        UserVo userVo = getUserVo();

        if (userVo.getUserType().equals(UserEnums.customer.getCode()) || userVo.getUserType().equals(UserEnums.sale.getCode())) {
            return ResponseData.success();
        }

        if (userVo.getUserType().equals(UserEnums.enterprise.getCode())) {
            Store one = storeService.getOne(new QueryWrapper<Store>().lambda().eq(Store::getBindEnterpriseId, userVo.getUserId()));
            userVo = new UserVo(UserEnums.store.getCode(), one.getId());
        }

        StoreAmountDataResp userAmountDataResp = new StoreAmountDataResp();

        Store store = storeService.getById(userVo.getUserId());

        //累计收益
        userAmountDataResp.setIncome(store.getIncome());

        //可提现金额(去除本月收益)
        //获取本月开始时间
        Date beginOfMonth = DateUtil.beginOfMonth(new Date());

        BigDecimal withdrawableAmount = walletRecordMapper.selectMonthBeforeAmount(beginOfMonth, userVo);
        userAmountDataResp.setWithdrawableAmount(withdrawableAmount.compareTo(BigDecimal.ZERO) == 1 ? withdrawableAmount : BigDecimal.ZERO);

        //已提现金额
        BigDecimal withdrawnAmount = withdrawalRecordMapper.withdrawnAmount(userVo);
        userAmountDataResp.setWithdrawnAmount(withdrawnAmount);

        //待提现金额
        userAmountDataResp.setToBeWithdrawnAmount(store.getBalance().subtract(userAmountDataResp.getWithdrawableAmount()));

        //扣款
        userAmountDataResp.setViolationDeduction(store.getViolationDeduction());

        return ResponseData.success(userAmountDataResp);
    }

    @Autowired
    private WalletRecordService walletRecordService;

    @Autowired
    private GiveWalletRecordService giveWalletRecordService;


    @PostMapping("/giveWalletPage")
    @UserLoginToken
    @ApiOperation(value = "抵用金明细", notes = "抵用金明细")
    public ResponseData<WalletPageResp> giveWalletPage(@RequestBody WalletPageReq req) {
        return giveWalletRecordService.giveWalletPage(req, getUserVo());
    }

    @PostMapping("/walletPage")
    @UserLoginToken
    @ApiOperation(value = "钱包明细", notes = "钱包明细")
    public ResponseData<WalletPageResp> walletPage(@RequestBody WalletPageReq req) {
        return walletRecordService.walletPage(req, getUserVo());
    }

    @PostMapping("/expenditurePage")
    @UserLoginToken
    @ApiOperation(value = "支出明细", notes = "支出明细")
    public ResponseData expenditurePage(@RequestBody WalletPageReq req) {
        return walletRecordService.expenditurePage(req, getUserVo());
    }

    @PostMapping("/walletDetail")
    @UserLoginToken
    @ApiOperation(value = "钱包明细详情", notes = "钱包明细详情")
    public ResponseData walletDetail(@RequestBody BodyIdReq req) {
        return walletRecordService.walletDetail(req, getUserVo());
    }

    @PostMapping("/customerPage")
    @UserLoginToken
    @ApiOperation(value = "设计师列表", notes = "设计师列表")
    public ResponseData<PageResult<Page<Customer>>> customerPage(@Valid @RequestBody CustomerPageReq req) {
        return customerService.customerPage(req, getUserVo());
    }

    @Autowired
    private IllegalDeductionRecordService illegalDeductionRecordService;

    @PostMapping("/illegalDeductionPage")
    @UserLoginToken
    @ApiOperation(value = "扣款明细", notes = "扣款明细")
    public ResponseData<IllegalDeductionPageResp> illegalDeductionPage(@RequestBody IllegalDeductionPageReq req) {
        return illegalDeductionRecordService.illegalDeductionPage(req, getUserVo());
    }

    @Autowired
    private AdvertisingImagesService advertisingImagesService;

    @PostMapping("/advertisingImages")
    @ApiOperation(value = "广告图", notes = "广告图")
    public ResponseData<AdvertisingImages> advertisingImages() {

        List<AdvertisingImages> list = advertisingImagesService.list(new QueryWrapper<AdvertisingImages>().lambda()
                .eq(AdvertisingImages::getDelFlag, PublicCommon.启用)
        );

        //类型 1富文本 2 设计师主页 3 表现师主页   4 首页   5活动页面   6新闻页面

        if (!list.isEmpty()){
            Set<UserVo> userVoSet = list.stream().filter(s->s.getType() == 2 || s.getType() == 3)
                    .map(s -> new UserVo(s.getType() == 2? UserEnums.customer.getCode():UserEnums.store.getCode(), Long.valueOf(s.getContent())))
                    .collect(Collectors.toSet());
            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,null);

            list.stream().forEach(s ->{
                if (s.getType() == 2 || s.getType() == 3) {
                    s.setUserInfo(userMap.get(new UserVo(s.getType() == 2 ? UserEnums.customer.getCode() : UserEnums.store.getCode(), Long.valueOf(s.getContent()))));
                }
            });
        }

        return ResponseData.success(list);
    }

    @PostMapping("/advertisingImagesDetail")
    @ApiOperation(value = "广告图", notes = "广告图")
    public ResponseData<AdvertisingImages> advertisingImages(@RequestBody BodyIdReq req) {
        return ResponseData.success(advertisingImagesService.getById(req.getId()));
    }
}
