package com.bohuikeji.delivery.backstage.controller.admin;

import cn.hutool.core.util.StrUtil;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bohuikeji.delivery.backstage.constants.WxAppEm;
import com.bohuikeji.delivery.backstage.entity.AliPayConfig;
import com.bohuikeji.delivery.backstage.entity.TCompanyFran;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.listener.settlement.FranSettleListener;
import com.bohuikeji.delivery.backstage.pay.AliPay;
import com.bohuikeji.delivery.backstage.service.IGmsService;
import com.bohuikeji.delivery.backstage.service.ITCompanyFranService;
import com.bohuikeji.delivery.backstage.service.ITOrderService;
import com.bohuikeji.delivery.backstage.service.IWxUserService;
import com.bohuikeji.frame.module.admin.base.InterfaceBase;
import com.bohuikeji.frame.module.admin.base.PageTemplateControllerBase;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysUser;
import com.bohuikeji.frame.module.admin.entity.vo.TableDataVo;
import com.bohuikeji.frame.module.admin.entity.web.TableData;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.wx.wxPayUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 加盟商结算
 * @author 孙劲辉
 */
@Slf4j
@Controller
@ResponseBody
@RequiredArgsConstructor
@RequestMapping("/company/fran")
public class CompanyFranController extends PageTemplateControllerBase {

    final IWxUserService wxUserService;
    final IGmsService gmsService;
    final ITCompanyFranService franService;
    final MqTool mqTool;
    final ITOrderService orderService;

    /**
     * 支付宝授权地址信息
     */
    private static final String ZFB_URL ="alipays://platformapi/startapp?appId=20000067&url={}";
    private static final String AUTH_URL ="https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id={}&scope=auth_user&state=1&redirect_uri={}";
    private static final String RT_URL="https://os.tcjskd.com/delivery/views/open/zfb/oauth?id={}&type=FRAN";

    /**
     * 查询数据列表
     * @param data
     * @return
     */
    @GetMapping("/get/list/group")
    public InterfaceBase getLitGroup(TableDataVo data) {
        return TableData.success(wxUserService.page(getPage(data),
                new QueryWrapper<TWxUser>()
                        .eq("user_type","FRAN").eq("user_id",getLoginUser().getFranId())));
    }

    /**
     * 获取加盟商公众号授权二维码
     * @return
     */
    @GetMapping("/get/wx/auth/url")
    public APIEntity wxAuthUrl(){
        return APIEntity.success(wxUserService.getGzhAutoUrl(getLoginUser().getFranId(), WxAppEm.WX_USER_TYPE_FRAN,"/open/default/success",WxAppEm.GZH_TCJS));
    }

    /**
     * 获取支付宝加盟商授权二维码
     * @return
     */
    @GetMapping("/get/zfb/auth/url")
    public APIEntity zfbAuthUrl() throws UnsupportedEncodingException {
        String rtUrlFmt=URLEncoder.encode(StrUtil.format(RT_URL,getLoginUser().getFranId()),"utf-8");
        String authUrlFmt=URLEncoder.encode(StrUtil.format(AUTH_URL,AliPayConfig.appID,rtUrlFmt),"utf-8");
        return APIEntity.success(StrUtil.format(ZFB_URL,authUrlFmt));
    }

    /**
     * 发送验证号码
     * @param phone
     * @return
     */
    @GetMapping("/get/gms/code")
    public APIEntity sendCode(String phone, HttpServletRequest request){
        return APIEntity.success(gmsService.sendCode(phone,request));
    }
    /**
     * 发送验证号码
     * @param phone
     * @return
     */
    @GetMapping("/get/verify/code")
    public APIEntity verifyCode(String phone, String code){
        if (gmsService.verifyCode(phone,code)){
            return APIEntity.success();
        }
        return APIEntity.fail("验证码错误");
    }

    /**
     * 删除账户绑定信息
     * @param id
     * @return
     */
    @GetMapping("/get/del/build")
    public APIEntity delBuild(Integer id){
        TCompanyFran fran=franService.getOne(new QueryWrapper<TCompanyFran>().eq("id",id).in("sett_status","核算中","审核中"));
        if (fran!=null){
            return APIEntity.fail("您有正在处理中的申请单，暂时无法解除绑定！");
        }
        wxUserService.removeById(id);
        return APIEntity.success();
    }

    /**
     * 撤销
     * @param id
     * @return
     */
    @GetMapping("/get/del/ids")
    public APIEntity delIds(Integer id){
        TCompanyFran fran=franService.getOne(new QueryWrapper<TCompanyFran>().eq("id",id).in("sett_status","核算中","审核中"));
        if (fran!=null){
            return APIEntity.success(franService.removeById(id));
        }
        return APIEntity.fail("只有审核以前的记录才可以撤销！");
    }

    /**
     * 检查账户
     * @return
     */
    @GetMapping("/get/check/account")
    public APIEntity checkAccount(){
        TWxUser wx= wxUserService.getUserByType(getLoginUser().getFranId(),WxAppEm.WX_USER_TYPE_FRAN,WxAppEm.GZH_TCJS);
        if (wx==null){
            return APIEntity.fail("请绑定微信收款账户！");
        }
        TWxUser zfb= wxUserService.getUserByType(getLoginUser().getFranId(),WxAppEm.WX_USER_TYPE_FRAN,WxAppEm.ZFB_WB);
        if (zfb==null){
            return APIEntity.fail("请绑定支付宝收款账户！");
        }
        return APIEntity.success();
    }

    /**
     * 加盟商结算（当前只有兼职的）
     * 发起结算
     * @return
     */
    @GetMapping("/get/to/company")
    public APIEntity toCompany(){
        TCompanyFran fran= franService.getOne(new QueryWrapper<TCompanyFran>().eq("fran_id",getLoginUser().getFranId()).in("sett_status","核算中","审核中"),false);
        if (fran!=null){
            return APIEntity.fail("您已经有一个正在处理的申请单...");
        }
        QueryWrapper<TOrder> queryWrapper=new QueryWrapper<TOrder>()
                .eq("fran_id",getLoginUser().getFranId())
                .eq("is_third",0)
                .eq("fran_sett_status","未结算")
                .eq("order_status","已完成")
                .ge("order_end_time","2022-04-01 00:00:00");
        int orderCount=orderService.count(queryWrapper);
        if (orderCount<1){
            return APIEntity.fail("您当前没有需要提现的订单！");
        }
        TCompanyFran company=new TCompanyFran();
        SysUser user=getLoginUser();
        company.setFranName(user.getFranId());
        company.setSettOrderNum(0);
        company.setSettInitiator(user.getUserId());
        company.setSettStatus("核算中");
        if(franService.save(company)){
            mqTool.sendMsg(company.getId(), FranSettleListener.class);
        }
        return APIEntity.success();
    }

    /**
     * 审核通过
     * @return
     */
    @GetMapping("/get/verify/success")
    public APIEntity verifySuccess(Integer id,String method,String rmk){
        TCompanyFran fran=franService.getById(id);
        String[] ids=fran.getSettOrderDetail();
        if(!orderService.update(new UpdateWrapper<TOrder>().set("fran_sett_status","已结算").in("order_id",ids))){
            log.error("结算单：{}结算失败，更新订单失败！",id);
            return APIEntity.fail("结算订单更新失败，请联系技术支持！");
        }
        //微信提现
        if ("微信".equals(method)){
            TWxUser wx= wxUserService.getUserByType(fran.getFranName(),WxAppEm.WX_USER_TYPE_FRAN,WxAppEm.GZH_TCJS);
            Map<String, String> rs = wxPayUtil.withdrawal(NumberUtils.get("TX"),wx.getWxUserOpenid(),fran.getOrderPayAmount(),"加盟商提现 ","GZHTCJS");
            if("SUCCESS".equals(rs.get("result_code")) && "SUCCESS".equals(rs.get("return_code"))){
                fran.setFlowNum(rs.get("payment_no"));
                fran.setSettPayee(wx.getWxUserOpenid());
            }else {
                return APIEntity.fail(rs.get("return_msg"));
            }
            //支付宝提现
        }else if("支付宝".equals(method)){
            TWxUser zfb= wxUserService.getUserByType(fran.getFranName(),WxAppEm.WX_USER_TYPE_FRAN,WxAppEm.ZFB_WB);
            AlipayFundTransUniTransferResponse res= AliPay.transferToAlipay(
                    NumberUtils.get("TX"),fran.getOrderPayAmount().setScale(2, RoundingMode.DOWN).toString(),"加盟商提现",zfb.getWxUserOpenid());
            if(res!=null){
                if(res.isSuccess()){
                    fran.setFlowNum(res.getOrderId());
                    fran.setSettPayee(zfb.getWxUserOpenid());
                }else {
                    return APIEntity.fail(res.getSubMsg());
                }
            }else {
                return APIEntity.fail("支付宝提现失败，未返回信息！");
            }
        }
        fran.setSettMethod(method);
        fran.setRemarks(rmk);
        fran.setSettEndTime(LocalDateTime.now());
        fran.setThirdSurplusAmount(new BigDecimal("0"));
        fran.setCurrentPayAmount(fran.getOrderPayAmount());
        fran.setSettAuditor(getLoginUser().getUserId());
        fran.setSettStatus("提现成功");
        fran.updateById();
        return APIEntity.success();
    }

    /**
     * 审核驳回
     * @return
     */
    @GetMapping("/get/verify/fail")
    public APIEntity verifyFail(Integer id,String method,String rmk){
        TCompanyFran fran=franService.getById(id);
        fran.setSettMethod(method);
        fran.setRemarks(rmk);
        fran.setSettEndTime(LocalDateTime.now());
        fran.setSettAuditor(getLoginUser().getUserId());
        fran.setSettStatus("审核未通过");
        fran.updateById();
        return APIEntity.success();
    }


}
