package com.bohuikeji.delivery.backstage.controller.api.courier;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.constants.WxAppEm;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.socket.AdminNotice;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.component.StaticComponent;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.back.DataPage;
import com.bohuikeji.frame.module.admin.entity.sys.SysRes;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 我的钱包页面接口
 * @author 10552
 */
@Slf4j
@Api(tags = {"派送员-我的钱包页面相关接口"})
@RestController
@RequestMapping("/api/wallet")
public class CourierWalletApi extends ApiController {
    @Autowired
    ITCourierService courierService;
    @Autowired
    ITOrderService orderService;
    @Autowired
    ITCourierWithdrawService withdrawService;
    @Autowired
    ITCourierCardService courierCardService;
    @Autowired
    IWxUserService wxUserService;
    @Autowired
    ITRewardPayService rewardPayService;
    @Autowired
    ITCourierWorkExamService courierWorkExamService;
    @Autowired
    ITStoreWalletService storeWalletService;
    @Autowired
    ISocketService socketService;
    @Autowired
    RedisUtil redisUtil;


    /**
     * 根据id获取派送员
     * @return
     */
    @ApiOperation("我的钱包首页3个数据")
    @GetMapping("/get/index")

    public APIEntity index(@RequestAttribute("JwtUserId") Integer id){
        TCourier courier = courierService.getById(id);
        Object bonus=0;
        Object fines;
        SysRes res=new SysRes();
        Object waiteSum=res.sql().selectObj("select IFNULL(sum(order_courier_money),0) as sumc from t_order where courier_id={0} and order_status='已完成' and courier_sett_status='未结算'",id);//订单预结算金额
        Object overSum=res.sql().selectObj("select IFNULL(sum(reality_amount),0) as sumc from t_courier_withdraw where courier_id={0} and withdraw_state='已提现'",id);
        Object overCount=res.sql().selectCount("select IFNULL(count(withdraw_id),0) as sumc from t_courier_withdraw where courier_id={0} and withdraw_state='已提现'",id);
        Object RewardCount=res.sql().selectObj("select IFNULL(sum(reward_price),0) as sumc from t_reward_pay where courier_id={0} and pay_status='已支付'",id);//打赏金额
        Object bonusNum=res.sql().selectObj("select IFNULL(sum(examine_price),0) as sumc from t_courier_work_exam where courier_id={0} and examine_state='待奖励' and examine_type='奖励'",id);//考核奖励金额
        Object fineNum=res.sql().selectObj("select IFNULL(sum(examine_price),0) as sumc from t_courier_work_exam where courier_id={0} and examine_state='待惩罚' and examine_type='惩罚'",id);//考核罚款金额
        TStoreWallet eaxmWallet = storeWalletService.getOne(new QueryWrapper<TStoreWallet>().eq("wallet_type","考核钱包").eq("fran_id",courier.getFranId()));
        TStoreWallet storeWallet = storeWalletService.getOne(new QueryWrapper<TStoreWallet>().eq("wallet_type","门店钱包").eq("fran_id",courier.getFranId()));
        if(eaxmWallet != null && eaxmWallet.getWalletPrice().compareTo(new BigDecimal(bonusNum.toString()))>-1){
            bonus = bonusNum;
        }else if(storeWallet != null && storeWallet.getWalletPrice().compareTo(new BigDecimal(bonusNum.toString()))>-1){
            bonus = bonusNum;
        }
        if(new BigDecimal(waiteSum.toString()).compareTo(new BigDecimal(fineNum.toString()))>-1 ){
            fines = fineNum;
            log.info("订单惩罚金额1:[{}]",fines);
        }else {
            fines = 0;
            log.info("订单惩罚金额2:[{}]",fines);
        }
        if(new BigDecimal(waiteSum.toString()).compareTo(new BigDecimal("0.00")) == 0){
            return APIEntity.fail("提现金额为0!");
        }
        log.info("订单结算金额:[{}]",waiteSum);
        log.info("订单打赏金额:[{}]",RewardCount);
        log.info("订单奖励金额:[{}]",bonus);
        JSONObject result=new JSONObject();
        result.put("waiteSum",new BigDecimal(waiteSum.toString()).add(new BigDecimal(RewardCount.toString())).add(new BigDecimal(bonus.toString())).subtract(new BigDecimal(fines.toString())));
        result.put("overSum",overSum);
        result.put("overCount",overCount);
        return APIEntity.success(result);
    }

    @ApiOperation("派送员申请提现接口")
    @GetMapping("/get/apply")
    public APIEntity saveWithdraw(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id){
        /*return APIEntity.fail("平台计费规则变更，提现功能暂停使用！");*/
        WxAppEm app= WxAppEm.MP_COURIER;
        TCourier courier=courierService.getById(id);
        String codeNum = "TX"+ NumberUtils.getRandom(4);
        /*if("全职".equals(courier.getCourierType())){
            return APIEntity.fail("仅限兼职与营销骑手使用！");
        }*/
        if(!"认证成功".equals(courier.getCourierAuth())){
            return APIEntity.fail("您还未完成身份认证，请先完成认证！");
        }
        if(redisUtil.get("courier_id_tx:"+courier.getCourierId())!=null){
            return APIEntity.fail("您已经提现了，系统正在处理中....");
        }
        /*TCourierCard card= courierCardService.getOne(new QueryWrapper<TCourierCard>()
                .eq("courier_id",id)
                .eq("bank_type","网商银行")
                .eq("card_bank","支付宝"),false);*/
        TWxUser wxUser=wxUserService.getUserByType(id, WxAppEm.WX_USER_TYPE_COURIER,app);
        if(courierCardService.list(new QueryWrapper<TCourierCard>().eq("courier_id",id)).size()<1 && wxUser == null){
            return APIEntity.fail("您尚未绑定提现账户，请先完成绑定！");
        }
        List<TCourierWithdraw> withdraws=withdrawService.list(new QueryWrapper<TCourierWithdraw>().eq("courier_id",id).eq("withdraw_state","审核中"));
        if(withdraws.size()>0){
            return APIEntity.fail("您已有在处理的提现申请，请耐心等待！");
        }
        List<TOrder> orderList=orderService.list(
                new QueryWrapper<TOrder>()
                        .eq("courier_id",id)
                        .eq("order_status","已完成")
                        .eq("courier_sett_status","未结算"));
        if(orderList.size()==0){
            return APIEntity.fail("您好，打赏、奖励的钱与您的完成订单相关，您当前没有已完成的订单无法提现！");
        }
       //计算订单打赏金额
        Object RewardCount=rewardPayService.RewardCount(courier,codeNum);
        //考核奖励金额
        Object bonusNum=courierWorkExamService.bonusCount(courier,codeNum);
        //考核扣款金额
        Object fineNum=courierWorkExamService.fineCount(courier,codeNum);
        //计算订单金额：提现订单总金额+打赏金额+考核奖励金额-考核扣款金额
        TCourierWithdraw courierWithdraw = withdrawService.saveWithdraw(orderList,courier,codeNum);
        if(courierWithdraw != null){
            courierWithdraw.setApplyAmount(courierWithdraw.getApplyAmount().add(new BigDecimal(RewardCount.toString())).add(new BigDecimal(bonusNum.toString())).subtract(new BigDecimal(fineNum.toString())));
            courierWithdraw.setRealityAmount(courierWithdraw.getApplyAmount());
            withdrawService.updateById(courierWithdraw);
        }
        /*log.info("订单结算金额222:[{}]",courierWithdraw.getApplyAmount());
        log.info("订单打赏金额222:[{}]",RewardCount);
        log.info("订单奖励金额222:[{}]",bonusNum);
        log.info("订单惩罚金额222:[{}]",fineNum);*/
        redisUtil.set("courier_id_tx:"+courier.getCourierId(),courierWithdraw,5);
        socketService.sendAdminMsg(new AdminNotice(StringUtils.formatStr("配送员{0}正在申请提现，请及时处理",courier.getCourierName())).setFranId(courier.getFranId()));
        return  APIEntity.success();
    }

    @ApiOperation("派送员小程序提现接口")
    @GetMapping("/get/mp/apply")
    public APIEntity saveMpWithdraw(@RequestAttribute("JwtUserId") Integer id){
        /*return APIEntity.fail("平台计费规则变更，提现功能暂停使用！");*/
        TCourier courier=courierService.getById(id);
        String codeNum = "TX"+ NumberUtils.getRandom(4);
        /*if("全职".equals(courier.getCourierType())){
            return APIEntity.fail("仅限兼职与营销骑手使用！");
        }*/
        if(!"认证成功".equals(courier.getCourierAuth())){
            return APIEntity.fail("您还未完成身份认证，请先完成认证！");
        }
        List<TCourierWithdraw> withdraws=withdrawService.list(new QueryWrapper<TCourierWithdraw>().eq("courier_id",id).eq("withdraw_state","审核中"));
        if(withdraws.size()>0){
            return APIEntity.fail("您已有在处理的提现申请，请耐心等待！");
        }
        List<TOrder> orderList=orderService.list(
                new QueryWrapper<TOrder>()
                        .eq("courier_id",id)
                        .eq("order_status","已完成")
                        .eq("courier_sett_status","未结算"));
        if(orderList.size()==0){
            return APIEntity.fail("您好，打赏、奖励的钱与您的完成订单相关，您当前没有已完成的订单无法提现！");
        }
        //计算订单打赏金额
        Object RewardCount=rewardPayService.RewardCount(courier,codeNum);
        //考核奖励金额
        Object bonusNum=courierWorkExamService.bonusCount(courier,codeNum);
        //考核扣款金额
        Object fineNum=courierWorkExamService.fineCount(courier,codeNum);
        //计算订单金额：提现订单总金额+打赏金额+考核奖励金额-考核扣款金额
        TCourierWithdraw courierWithdraw = withdrawService.saveWithdraw(orderList,courier,codeNum);
        if(courierWithdraw != null){
            courierWithdraw.setApplyAmount(courierWithdraw.getApplyAmount().add(new BigDecimal(RewardCount.toString())).add(new BigDecimal(bonusNum.toString())).subtract(new BigDecimal(fineNum.toString())));
            courierWithdraw.setRealityAmount(courierWithdraw.getApplyAmount());
            withdrawService.updateById(courierWithdraw);
        }
        /*log.info("订单结算金额222:[{}]",courierWithdraw.getApplyAmount());
        log.info("订单打赏金额222:[{}]",RewardCount);
        log.info("订单奖励金额222:[{}]",bonusNum);
        log.info("订单惩罚金额222:[{}]",fineNum);*/
        socketService.sendAdminMsg(new AdminNotice(StringUtils.formatStr("配送员{0}正在申请提现，请及时处理",courier.getCourierName())).setFranId(courier.getFranId()));
        return  APIEntity.success();
    }


    @ApiOperation("派送员查询提现记录")
    @GetMapping("/get/record")

    public APIEntity getRecord(@RequestAttribute("JwtUserId") Integer id,DataPage page){
        QueryWrapper<TCourierWithdraw> wrapper = new QueryWrapper<>();
        wrapper.eq("courier_id",id);
        page.setDesc("withdraw_id");
        return APIEntity.success(withdrawService.page(page,wrapper));
    }

    @ApiOperation("派送员账单查询")
    @GetMapping("/get/bill")

    /*@ApiImplicitParams({
            @ApiImplicitParam(name="year",value="查询年",dataType="string", paramType = "query",example = "2019"),
            @ApiImplicitParam(name="month",value="查询月",dataType="string", paramType = "query",example = "06")})*/
    public APIEntity getBill(@RequestAttribute("JwtUserId") Integer id,Integer current,Integer size){
        QueryWrapper queryWrapper=new QueryWrapper<TOrder>()
                .eq("courier_id",id)
                .eq("order_status","已完成")
                .gt("order_courier_money",0).orderByDesc("order_id");
        if(current==null||size==null){
            return APIEntity.success(orderService.list(queryWrapper));
        }
        DataPage page=new DataPage(current,size);
        return APIEntity.success(orderService.page(page,queryWrapper));
    }

    /**
     * https://os.tcjskd.com/delivery
     * @param id
     * @return
     * @throws UnsupportedEncodingException
     */
    @ApiOperation("派送员绑定支付宝")
    @GetMapping("/build/alipay")

    public APIEntity buildAliPay(@RequestAttribute("JwtUserId") Integer id) throws UnsupportedEncodingException {
        TCourierCard courierCard=courierCardService.getOne(new QueryWrapper<TCourierCard>().eq("courier_id",id).eq("card_bank","支付宝"),false);
        String url="alipays://platformapi/startapp?appId=20000067&url=" + URLEncoder.encode("https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id="+ AliPayConfig.appID +"&scope=auth_user&&state="+id+"&redirect_uri="+URLEncoder.encode("https://os.tcjskd.com/delivery/test/ali","utf-8"),"utf-8");
        log.error("生成连接：[{}]",url);
        if(courierCard==null){
            return APIEntity.success(url);
        }
        return APIEntity.fail("您已绑定成功！");
    }
}
