package cn.pluss.platform.controller;

import cn.hutool.core.util.DesensitizedUtil;
import cn.pluss.platform.IdCardCacheService;
import cn.pluss.platform.ali.AliService;
import cn.pluss.platform.annotation.OpLog;
import cn.pluss.platform.api.PageInfo;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.baidu.BaiduOCRService;
import cn.pluss.platform.cash.CashService;
import cn.pluss.platform.dto.*;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.leshua.*;
import cn.pluss.platform.leshua.impl.LeshuaMerchantAuditService;
import cn.pluss.platform.level.LevelService;
import cn.pluss.platform.mapper.MerchantImageMapper;
import cn.pluss.platform.mapper.MerchantOrderMapper;
import cn.pluss.platform.mapper.MerchantRateMapper;
import cn.pluss.platform.merchant.AccountService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantBankCard.MerchantBankCardService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.merchantProfit.MerchantProfitService;
import cn.pluss.platform.merchantStore.MerchantStoreService;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.systemInfo.SystemInfoService;
import cn.pluss.platform.user.UserProfitService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.*;
import cn.pluss.platform.vo.*;
import cn.pluss.platform.wechat.WechatService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.reflect.TypeToken;
import io.swagger.annotations.*;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

/**
 * @author Administrator
 */
@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/userApp")
@Transactional
@Api(value = "UserApp控制类", tags = { "UserApp接口" })
public class UserAppController {

  private final AccountService accountService;

  private final UserAppService userAppService;

  private final MerchantStoreService merchantStoreService;

  private final MerchantBaseInfoService merchantBaseInfoService;

  private final MerchantImageMapper merchantImageMapper;

  private final UserInfoService userInfoService;

  private final SystemConfigService systemConfigService;

  private final MerchantOrderService merchantOrderService;

  private final CashService cashService;

  private final LevelService levelService;

  private final SystemInfoService systemInfoService;

  private final LeshuaService leshuaService;

  private final LeshuaMerchantAuditService leshuaMerchantAuditService;

  private final MerchantBankCardService merchantBankCardService;

  private final AliService aliService;

  private final BaiduOCRService baiduOCRService;

  private final MerchantProfitService merchantProfitService;

  private final MerchantOrderMapper merchantOrderMapper;

  private final MerchantRateMapper merchantRateMapper;

  private final WechatService wechatService;

  @Autowired
  @Lazy
  private IdCardCacheService idCardCacheService;

  @Autowired
  private UserProfitService userProfitService;

  @Setter(onMethod_ = { @Autowired, @Lazy })
  private MerchantChannelStatusService mcsService;

  private static String keyStoreUrl =
    "/home/syb/resources/wechatCert/apiclient_cert.p12"; // 验证证书路径

  @GetMapping("/postageImg")
  public Result<Object> getPostageImg() {
    SystemConfig entity = new SystemConfig();
    entity.setPropertyKey("yunfei");

    SystemConfig result = systemConfigService.getOne(
      new QueryWrapper<>(entity)
    );

    return ResultGenerator.genSuccessResult(result);
  }

  @PostMapping("/getPageUser")
  @ApiOperation(
    tags = { "页面-员工", "页面-选择员工" },
    value = "获取全部",
    notes = "返回分页过后的数据",
    httpMethod = "POST"
  )
  public Result<Object> list(@RequestBody UserApp userApp) {
    MsgException.checkNull(userApp, "参数错误");

    MsgException.checkBlank(userApp.getUserType(), "没有员工类型参数！");

    // 返回参数
    Map<String, Object> result = new HashMap<>(16);
    Page<UserApp> page = userAppService.appPageStaff(userApp);
    PageInfo<UserApp> data = new PageInfo<>(
      page.getTotal(),
      page.getCurrent(),
      page.getPages(),
      page.getSize(),
      page.getRecords()
    );
    result.put("pager", data);
    return ResultGenerator.genSuccessResult(result);
  }

  @GetMapping("/deleteStaff")
  @ApiOperation(value = "删除员工", notes = "删除员工", httpMethod = "GET")
  public Result<Object> deleteStaff(@RequestParam String userId) {
    try {
      MsgException.checkBlank(userId, "请传入用户Id");

      UserApp userApp = new UserApp();
      userApp.setUserId(Long.valueOf(userId));
      List<UserApp> queryUserAppList = userAppService.queryUserAppList(userApp);
      MsgException.checkBlank(queryUserAppList, "无此用户");

      userApp = queryUserAppList.get(0);
      if (!"staff".equals(userApp.getUserType())) {
        return ResultGenerator.genFailResult("该用户不属于员工");
      }
      userAppService.removeById(userApp.getId());
      UserInfo userInfo = new UserInfo();
      userInfo.setId(Long.valueOf(userId));
      userInfoService.deleteUserInfo(userInfo);
      return ResultGenerator.genSuccessResult();
    } catch (NumberFormatException e) {
      e.printStackTrace();
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      return ResultGenerator.genFailResult("删除失败");
    }
  }

  @PostMapping("/saveStaffInfo")
  @ApiOperation(value = "添加员工", notes = "添加新的数据", httpMethod = "POST")
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "UserApp",
        value = "待添加的UserApp实例",
        paramType = "body",
        dataType = "UserApp",
        required = true
      ),
    }
  )
  public Result<Object> add(@RequestBody @Valid UserApp userApp) {
    userAppService.appSaveStaffInfo(userApp);
    return ResultGenerator.genSuccessResult();
  }

  @PostMapping("/saveAgentStaff")
  @ApiOperation(value = "添加员工", notes = "添加新的数据", httpMethod = "POST")
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "UserApp",
        value = "待添加的UserApp实例",
        paramType = "body",
        dataType = "UserApp",
        required = true
      ),
    }
  )
  public Result<Object> saveAgentStaff(@RequestBody @Valid UserApp userApp) {
    userAppService.appSaveStaffInfo(userApp);
    return ResultGenerator.genSuccessResult();
  }

  @DeleteMapping("/{id}")
  @ApiOperation(
    value = "删除数据",
    notes = "根据id删除数据",
    httpMethod = "DELETE"
  )
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "id",
        value = "查询的id实例",
        paramType = "path",
        dataType = "Integer",
        required = true
      ),
    }
  )
  public Result<Object> delete(@PathVariable Long id) {
    userAppService.removeById(id);
    return ResultGenerator.genSuccessResult();
  }

  @PostMapping("/realNameAudit")
  @ApiOperation(
    value = "实名认证",
    notes = "用户实名认证  将实名认证信息存在MerchantBankCard",
    httpMethod = "POST"
  )
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "UserApp",
        value = "认证UserApp实例",
        paramType = "body",
        dataType = "UserApp",
        required = true
      ),
    }
  )
  public Result<Object> realNameAudit(
    @RequestBody @Valid CertificationDTO certificationDTO
  ) {
    try {
      accountService.realNameAudit(certificationDTO);
      return ResultGenerator.genSuccessResult();
    } catch (NumberFormatException e) {
      e.printStackTrace();
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      return ResultGenerator.genFailResult("系统繁忙，请稍后再试");
    }
  }

  @PostMapping("/banCardAudit")
  @ApiOperation(
    value = "银行卡认证",
    notes = "用户银行卡认证",
    httpMethod = "POST"
  )
  public Result<Object> banCardAudit(
    @RequestBody @Valid BankInfoDTO bankInfoDTO
  ) {
    accountService.bankcardAudit(bankInfoDTO);
    return ResultGenerator.genSuccessResult("认证成功", null);
  }

  @PostMapping("/leshuajinjianQuery")
  @ApiOperation(
    value = "乐刷进件查询",
    notes = "乐刷进件查询",
    httpMethod = "POST"
  )
  public Result<Object> leshuajinjianQuery(String merchantId) {
    JSONObject data = new JSONObject();
    data.put("merchantId", merchantId);
    Result<Object> result = leshuaService.requestApi(
      LeshuaParam.getREGISTERURL() + "/merchant/info_qry",
      data
    );
    if ("000000".equals(result.getRespCode())) {
      JSONObject data2 = (JSONObject) result.getData();
      JSONObject data3 = data2.getJSONObject("auditInfo");
      log.info(data3.toJSONString());
    }
    return result;
  }

  // 修改用户头像
  @PostMapping("/updateLogo")
  @ApiOperation(
    value = "修改用户头像",
    notes = "修改用户头像",
    httpMethod = "POST"
  )
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "UserApp",
        value = "认证UserApp实例",
        paramType = "body",
        dataType = "UserApp",
        required = true
      ),
    }
  )
  public Result<Object> updateLogo(@RequestBody UserApp userApp) {
    // 验证参数是否完整
    if (StringUtil.isEmpty(userApp.getUserId())) {
      return ResultGenerator.genFailResult("userId参数不存在！");
    }
    // 查询当前用户是否存在
    UserApp queryUserApp = new UserApp();
    queryUserApp.setUserId(userApp.getUserId());
    List<UserApp> queryUserAppList = userAppService.queryUserAppList(
      queryUserApp
    );

    MsgException.checkBlank(queryUserAppList, "查无此人！");
    queryUserApp = queryUserAppList.get(0);
    // 修改用户头像
    UserApp updateUserApp = new UserApp();
    updateUserApp.setId(queryUserApp.getId());
    updateUserApp.setLogo(userApp.getLogo());
    userAppService.updateById(updateUserApp);
    return ResultGenerator.genSuccessResult();
  }

  @PostMapping("/queryUserAppByUserId")
  @ApiOperation(
    tags = { "页面-对账", "页面-我的" },
    value = "查询用户详情",
    notes = "通过UserId查询用户信息",
    httpMethod = "POST"
  )
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "UserApp",
        value = "查询的UserApp",
        paramType = "body",
        required = true,
        dataType = "UserApp"
      ),
    }
  )
  public Result<Object> queryUserAppByUserId() {
    UserApp result = userAppService.queryUserBaseInfoByToken();
    if (result.getLevelCode() != null) {
      result.setLevelCode(result.getLevelCode().replace("T", "VIP"));
    }
    //        MerchantChannelStatus mcs = mcsService.getValidData(result.getMerchantCode());
    //        mcsService.verifyWxAuthStatus(mcs);
    return ResultGenerator.genSuccessResult(result);
  }

  @PostMapping("/queryStaffDetailUserId")
  @ApiOperation(
    value = "查询员工详情",
    notes = "通过UserId查询员工信息",
    httpMethod = "POST"
  )
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "UserApp",
        value = "查询的UserApp",
        paramType = "body",
        required = true,
        dataType = "UserApp"
      ),
    }
  )
  public Result<Object> queryStaffDetailUserId(@RequestBody UserApp userApp) {
    UserApp tokenUserApp = userAppService.queryUserAppByToken();
    if (StringUtil.isEmpty(userApp.getUserId())) {
      return ResultGenerator.genFailResult("请传入userId");
    }
    UserApp queryUserApp = new UserApp();
    QueryWrapper<Object> qWrapper = new QueryWrapper<>()
      .eq("ua.userId", userApp.getUserId())
      .eq("msc.merchantCode", tokenUserApp.getMerchantCode());
    queryUserApp.setUserId(userApp.getUserId());
    // 根据用户的id查询当前的用户详情

    userApp = userAppService.appGetOne(qWrapper);
    MsgException.checkNull(userApp, "员工信息错误！");
    MerchantStore queryMerchantStore = new MerchantStore();
    // 查询当前用户所属的门店信息
    if (StringUtil.isNotEmpty(userApp.getStoreId())) {
      queryMerchantStore.setStoreId(userApp.getStoreId());
      List<MerchantStore> queryMerchantStoreList = merchantStoreService.queryMerchantStoreList(
        queryMerchantStore
      );

      if (queryMerchantStoreList != null && !queryMerchantStoreList.isEmpty()) {
        queryMerchantStore = queryMerchantStoreList.get(0);
      }
    }
    if (StringUtil.isEmpty(queryMerchantStore)) {
      return ResultGenerator.genFailResult("无门店信息！");
    }
    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("userApp", userApp);
    resultMap.put("merchantStore", queryMerchantStore);
    return ResultGenerator.genSuccessResult(resultMap);
  }

  /**
   * 商户推广分润数据统计
   */
  @GetMapping("/generaRhare")
  @ApiOperation(
    tags = { "页面-收益" },
    value = "商户推广分润数据统计",
    httpMethod = "GET"
  )
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "userId",
        value = "当前用户Id",
        paramType = "query",
        required = true,
        dataType = "Integer"
      ),
    }
  )
  public Result<Object> generaShare(@RequestParam Long userId) {
    // 获取当前用户信息
    UserApp queryUserApp = new UserApp();
    queryUserApp.setUserId(userId);
    List<UserApp> queryUserAppList = userAppService.queryUserAppList(
      queryUserApp
    );

    MsgException.checkBlank(queryUserAppList, "用户信息错误");
    queryUserApp = queryUserAppList.get(0);
    // 获取当前用户的推广等级
    Level currLevel = new Level();
    currLevel.setLevel(queryUserApp.getLevel());
    if (StringUtil.isNotEmpty(queryUserApp.getLevel())) {
      List<Level> queryLevelList = levelService.queryLevelList(currLevel);

      MsgException.checkBlank(queryLevelList, "推广信息错误！");
      currLevel = queryLevelList.get(0);
    } else {
      return ResultGenerator.genFailResult("您无权访问该界面");
    }
    Double currRate = currLevel.getRate();
    // 获取当前用户的下一推广等级
    Level nextLevel = new Level();
    nextLevel.setLevel(queryUserApp.getLevel() + 1);
    nextLevel = levelService.queryLevel(nextLevel);
    Double nextRate = 0.0d;
    if (nextLevel != null) {
      nextRate = nextLevel.getRate();
    }
    Double totalShareMoneyToday = 0d; // 今日分润总额
    Double totalAccumulateShareMoney = 0d; // 累计总分润
    Double merchantShareMoneyToday = 0d; // 推广商户今日分润
    Double merchantShareMoneyHistory = 0d; // 推广商户历史分润

    Double allowCashMoney = 0d; // 可提现分润
    Double noCashMoney = 0d; // 不可提现分润
    Double cashedMoney = 0d; // 已提现分润
    // 获取当前商户的所有的下级商户信息

    Map<String, Object> queryMap = new HashMap<>();
    if ("agent_staff".equals(queryUserApp.getUserType())) {
      queryMap.put("agentStaffId", userId);
    } else {
      queryMap.put("userId", userId);
    }

    queryMap.put("status", 1);

    // 累计总分润
    totalAccumulateShareMoney =
      merchantProfitService.queryMerchantProfitSumPrice(queryMap);
    if (totalAccumulateShareMoney == null) {
      totalAccumulateShareMoney = 0d;
    }
    queryMap.put("startTime", DateUtils.getDayBegin());
    totalShareMoneyToday =
      merchantProfitService.queryMerchantProfitSumPrice(queryMap);
    if (totalShareMoneyToday == null) {
      totalShareMoneyToday = 0d;
    }

    queryMap.put("retype", "1");
    // 商户今日分润
    merchantShareMoneyToday =
      merchantProfitService.queryMerchantProfitSumPrice(queryMap);
    if (merchantShareMoneyToday == null) {
      merchantShareMoneyToday = 0d;
    }
    // 商户历史分润
    queryMap.put("startTime", null);
    queryMap.put("endTime", DateUtils.getDayBegin());
    merchantShareMoneyHistory =
      merchantProfitService.queryMerchantProfitSumPrice(queryMap);
    if (merchantShareMoneyHistory == null) {
      merchantShareMoneyHistory = 0d;
    }

    // 今日总分润 = 今日商户分润
    // 已经提现与正在提现的分润 //+ cashService.sumFansAreadlyCash(map);
    cashedMoney = cashService.sumMerchantSuccessCash(userId);
    if (cashedMoney == null) {
      cashedMoney = 0d;
    }
    noCashMoney = totalShareMoneyToday;
    allowCashMoney = totalAccumulateShareMoney - cashedMoney - noCashMoney;

    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put(
      "totalShareMoneyToday",
      StringUtil.bigDecimal(totalShareMoneyToday)
    ); //今日总分润
    resultMap.put(
      "totalAccumulateShareMoney",
      StringUtil.bigDecimal(totalAccumulateShareMoney)
    ); //累计总分润
    resultMap.put(
      "merchantShareMoneyToday",
      StringUtil.bigDecimal(merchantShareMoneyToday)
    ); //今日推广分润
    resultMap.put(
      "merchantShareMoneyHistory",
      StringUtil.bigDecimal(merchantShareMoneyHistory)
    ); //历史推广分润
    resultMap.put(
      "nextMerchantShareMoneyToday",
      StringUtil.bigDecimal(totalShareMoneyToday - merchantShareMoneyToday)
    ); //今日升级分润
    resultMap.put(
      "nextMerchantShareMoneyHistory",
      StringUtil.bigDecimal(
        totalAccumulateShareMoney -
        merchantShareMoneyHistory -
        totalShareMoneyToday
      )
    ); //历史升级分润
    resultMap.put(
      "allowCashMoney",
      StringUtil.bigDecimal(allowCashMoney, RoundingMode.DOWN)
    );
    resultMap.put("noCashMoney", StringUtil.bigDecimal(noCashMoney));
    resultMap.put("cashedMoney", StringUtil.bigDecimal(cashedMoney));
    return ResultGenerator.genSuccessResult(resultMap);
  }

  // 修改员工信息
  @PostMapping("/updateStaffInfo")
  @ApiOperation(
    value = "修改员工信息",
    notes = "修改员工的数据",
    httpMethod = "POST"
  )
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "UserApp",
        value = "待修改的UserApp实例",
        paramType = "body",
        dataType = "UserApp",
        required = true
      ),
    }
  )
  public Result<Object> updateStaffInfo(@RequestBody @Valid UserApp userApp) {
    if (StringUtil.isEmpty(userApp.getUserId())) {
      return ResultGenerator.genFailResult("无用户Id");
    }
    UserApp queryUserApp = new UserApp();
    queryUserApp.setUserId(userApp.getUserId());
    List<UserApp> queryUserAppList = userAppService.queryUserAppList(
      queryUserApp
    );

    MsgException.checkBlank(queryUserAppList, "无用户信息！");
    queryUserApp = queryUserAppList.get(0);

    UserApp updateUserApp = new UserApp();
    updateUserApp.setId(queryUserApp.getId());
    updateUserApp.setLoginName(userApp.getLoginName());
    updateUserApp.setUserName(userApp.getUserName());
    updateUserApp.setPhone(userApp.getPhone());
    updateUserApp.setPassword(userApp.getPassword());
    updateUserApp.setStoreId(userApp.getStoreId());
    updateUserApp.setStoreName(userApp.getStoreName());
    UserInfo updateUserInfo = new UserInfo();
    updateUserInfo.setId(queryUserApp.getUserId());
    updateUserInfo.setLoginName(userApp.getLoginName());
    updateUserInfo.setPassword(
      MD5Util.MD5Encode(userApp.getPassword(), "utf-8")
    );
    updateUserInfo.setPhone(userApp.getPhone());
    // 更新用户登录表
    userInfoService.updateUserInfo(updateUserInfo);
    // 更新用户详情信息表
    userAppService.updateById(updateUserApp);
    return ResultGenerator.genSuccessResult();
  }

  @OpLog(
    opCode = "APP_AUDIT_REQ",
    opName = "商户请求进件",
    opDetail = "商户请求进件"
  )
  @PostMapping("/merchantAudit")
  @ApiOperation(value = "通用进件， 商户进件请求", notes = "通用进件", httpMethod = "POST")
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "paramJson",
        value = "进件数据",
        paramType = "body",
        dataType = "JSONObject",
        required = true
      ),
    }
  )
  public Result<Object> merchantAudit() {
    UserApp userApp = userAppService.queryUserAppByToken();
    if (StringUtil.isEmpty(userApp.getInviteNum())){
      return ResultGenerator.genSuccessResult("InviteNumNull");
    }
    userAppService.merchantAuditReq();
    return ResultGenerator.genSuccessResult("进件请求成功，等待后台审核");
  }

  @PostMapping("/editMerchantAudit")
  @ApiOperation(value = "通用进件，当前特指修改结算信息，只允许修改结算信息", notes = "通用进件", httpMethod = "POST")
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "paramJson",
        value = "进件数据",
        paramType = "body",
        dataType = "JSONObject",
        required = true
      ),
    }
  )
  public Result<Object> editMerchantAudit(String userId) throws Exception {
    userAppService.editMerchantAudit(userId);
    return ResultGenerator.genSuccessResult("进件请求成功");
  }

  @PostMapping("/leshuaMerchantAudit")
  @ApiOperation(value = "乐刷进件", notes = "乐刷进件", httpMethod = "POST")
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "LeshuaMerchantAuditDTO",
        value = "LeshuaMerchantAuditDTO",
        paramType = "LeshuaMerchantAuditDTO",
        dataType = "LeshuaMerchantAuditDTO",
        required = true
      ),
    }
  )
  public Result<Object> leshuaMerchantAudit(
    @RequestBody LeshuaMerchantAuditDTO leshuaMerchantAuditDTO
  )
    throws Exception {
    leshuaMerchantAuditService.merchantAudit(
      leshuaMerchantAuditDTO.getUserId(),
      true
    );
    return ResultGenerator.genSuccessResult("进件成功");
  }

  @PostMapping("/wechatMerchantAudit")
  @ApiOperation(value = "微信进件", notes = "微信进件", httpMethod = "POST")
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "AliMerchantAuditDTO",
        value = "AliMerchantAuditDTO实例",
        paramType = "AliMerchantAuditDTO",
        dataType = "AliMerchantAuditDTO",
        required = true
      ),
    }
  )
  public Result<Object> wechatMerchantAudit(
    @RequestBody WechatMerchantAuditDTO wechatMerchantAuditDTO
  ) {
    wechatService.wechatMerchantAudit(wechatMerchantAuditDTO);
    return ResultGenerator.genSuccessResult("微信进件成功");
  }

  @PostMapping("/aliMerchantAudit")
  @ApiOperation(value = "支付宝进件", notes = "支付宝进件", httpMethod = "POST")
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "AliMerchantAuditDTO",
        value = "AliMerchantAuditDTO实例",
        paramType = "AliMerchantAuditDTO",
        dataType = "AliMerchantAuditDTO",
        required = true
      ),
    }
  )
  public Result<?> aliMerchantAudit(
    @RequestBody AliMerchantAuditDTO aliMerchantAuditDTO
  ) {
    throw new MsgException("暂不支持该接口");
    //        if (StringUtil.isEmpty(aliMerchantAuditDTO.getUserId())) {
    //            return ResultGenerator.genFailResult("userId参数不存在！");
    //        }
    //        UserApp userApp = new UserApp();
    //        userApp.setUserId(aliMerchantAuditDTO.getUserId().longValue());
    //        List<UserApp> queryUserAppList = userAppService.queryUserAppList(userApp);
    //        if (queryUserAppList == null || queryUserAppList.isEmpty()) {
    //            return ResultGenerator.genFailResult("该用户不存在");
    //        }
    //
    //        userApp = queryUserAppList.get(0);// 获取当前用户的信息
    //        if (null != userApp.getAliStatus() && 0 != userApp.getAliStatus() && 2 != userApp.getAliStatus()) {
    //            return ResultGenerator.genFailResult("您已经进件或正在审核中");
    //        }
    //
    //        MerchantBaseInfo mBaseInfo = new MerchantBaseInfo();
    //        mBaseInfo.setUserId(aliMerchantAuditDTO.getUserId() + "");
    //        List<MerchantBaseInfo> queryMerchantBaseInfoList = merchantBaseInfoService
    //                .queryMerchantBaseInfoList(mBaseInfo);
    //        if (queryMerchantBaseInfoList == null || queryMerchantBaseInfoList.isEmpty()) {
    //            return ResultGenerator.genFailResult("请先完善商户基本信息");
    //        }
    //
    //        mBaseInfo = queryMerchantBaseInfoList.get(0);
    //        Result<MerchantBaseInfo> convertMerchantBaseInfo = aliMerchantAuditDTO
    //                .convertMerchantBaseInfo(mBaseInfo);
    //        if (400 == convertMerchantBaseInfo.getCode()) {
    //            return convertMerchantBaseInfo;
    //        }
    //        mBaseInfo = convertMerchantBaseInfo.getData();
    //        MerchantImage merchantImage = new MerchantImage();
    //        merchantImage.setMerchantCode(mBaseInfo.getMerchantCode());
    //        List<MerchantImage> queryMerchantImageList = merchantImageMapper
    //                .queryMerchantImageList(merchantImage);// 当前商户所有的照片信息
    //        Result<String> isOpenTrue = aliService.getBatchNo(mBaseInfo);
    //        if (400 == isOpenTrue.getCode()) {
    //            return isOpenTrue;
    //        }
    //        String batchNo = isOpenTrue.getData();// 开启事务成功
    //        Result<BatchInfoDTO> convertBatchInfoDTO = aliMerchantAuditDTO
    //                .convertBatchInfoDTO(queryMerchantImageList, mBaseInfo);
    //        if (400 == convertBatchInfoDTO.getCode()) {
    //            return convertBatchInfoDTO;
    //        }
    //        BatchInfoDTO batch = convertBatchInfoDTO.getData();
    //        if (StringUtil.isEmpty(batchNo)) {
    //            userApp.setAliStatus(2);
    //        } else {
    //            batch.setBatchNo(batchNo);
    //        }
    //        try {
    //            if (aliService.facetofaceSign(batch)) {// 代签约当面付
    //                if (aliService.agentConfirm(batchNo)) {// 提交事务
    //                    mBaseInfo.setAlipaySource(batchNo);
    //                    userApp.setAliStatus(1);
    //                    if (StringUtil.isNotEmpty(userApp.getParentId())) {// 更新上级推广人的认证商户数量
    //                        UserApp parentApp = new UserApp();
    //                        parentApp.setUserId(userApp.getParentId());
    //                        List<UserApp> queryUserAppList2 = userAppService.queryUserAppList(parentApp);
    //                        if (StringUtil.isNotEmpty(userApp.getParentId()) && queryUserAppList2 != null
    //                                && queryUserAppList2.size() > 0) {
    //                            parentApp = queryUserAppList2.get(0);
    //                            UserApp updateParentApp = new UserApp();
    //                            updateParentApp.setId(parentApp.getId());
    //                            updateParentApp.setAuthCount(
    //                                    parentApp.getAuthCount() == null ? 1 : parentApp.getAuthCount() + 1);
    //                            userAppService.updateUserApp(updateParentApp);
    //                        }
    //                    }
    //                    return ResultGenerator.genSuccessResult("进件成功");
    //                } else {
    //                    userApp.setAliStatus(2);
    //                    return ResultGenerator.genFailResult("进件失败");
    //                }
    //            } else {
    //                userApp.setAliStatus(2);
    //                return ResultGenerator.genFailResult("进件失败");
    //            }
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //            userApp.setAliStatus(2);
    //            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    //            return ResultGenerator.genFailResult("系统繁忙,请稍后再试");
    //        } finally {
    //            userAppService.updateUserApp(userApp);
    //            mBaseInfo.setAliRate(ParametersUtil.ALI_RATE);
    //            merchantBaseInfoService.updateMerchantBaseInfo(mBaseInfo);
    //        }
  }

  @GetMapping(value = "/idCardOCR")
  @ApiOperation(
    value = "OCR识别身份证信息",
    notes = "OCR识别身份证信息",
    httpMethod = "GET"
  )
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "imgUrl",
        value = "图片URL",
        paramType = "imgUrl",
        dataType = "imgUrl",
        required = true
      ),
      @ApiImplicitParam(
        name = "idCardSide",
        value = "front/back front：身份证含照片的一面；back：身份证带国徽的一面",
        paramType = "idCardSide",
        dataType = "idCardSide",
        required = true
      ),
    }
  )
  public Result getIdCardInfo(
    @RequestParam String imgUrl,
    @RequestParam String idCardSide
  ) {
    if (!"front".equals(idCardSide) && !"back".equals(idCardSide)) {
      return ResultGenerator.genFailResult("上传错误 ,请稍后再试");
    }
    String accessToken = baiduOCRService.getAuth();
    String idCardOCRUrl = ParametersUtil.idCardOCRUrl;

    try {
      String imgStr = ImageUtils.image2Base64(imgUrl);
      String imgParam = URLEncoder.encode(imgStr, "UTF-8");
      String params = "id_card_side=" + idCardSide + "&image=" + imgParam;
      String info = baiduOCRService.getInfo(idCardOCRUrl, accessToken, params);
      JSONObject parseObject = JSONObject.parseObject(info);
      String imageStatus = parseObject.getString("image_status");
      if ("reversed_side".equals(imageStatus)) {
        return ResultGenerator.genFailResult("身份证正反面颠倒");
      }
      if ("non_idcard".equals(imageStatus)) {
        return ResultGenerator.genFailResult("上传的图片中不包含身份证");
      }
      if ("blurred".equals(imageStatus)) {
        return ResultGenerator.genFailResult("身份证模糊");
      }
      if ("other_type_card".equals(imageStatus)) {
        return ResultGenerator.genFailResult("其他类型证照");
      }
      if ("over_exposure".equals(imageStatus)) {
        return ResultGenerator.genFailResult("身份证关键字段反光或过曝");
      }
      if ("over_dark".equals(imageStatus)) {
        return ResultGenerator.genFailResult("身份证欠曝（亮度过低）");
      }
      if ("unknown".equals(imageStatus)) {
        return ResultGenerator.genFailResult("未知状态");
      }

      final JSONObject jsonObject = JSON
        .parseObject(info)
        .getJSONObject("words_result");
      if (jsonObject.getJSONObject("姓名") != null) {
        IdCardCache idCardCache = new IdCardCache();
        idCardCache.setCertNo(
          jsonObject.getJSONObject("公民身份号码").getString("words")
        );
        IdCardCache existData = idCardCacheService.getOne(
          new QueryWrapper<>(idCardCache)
        );
        if (existData == null) {
          idCardCache.setName(
            jsonObject.getJSONObject("姓名").getString("words")
          );
          idCardCache.setAddress(
            jsonObject.getJSONObject("住址").getString("words")
          );
          idCardCache.setImgPositive(imgUrl);
          idCardCacheService.save(idCardCache);
        }
      }

      return ResultGenerator.genSuccessResult(info);
    } catch (Exception e) {
      e.printStackTrace();
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      return ResultGenerator.genFailResult("识别错误，请稍后再试");
    }
  }

  /**
   * 营业执照OCR识别
   *
   * @param imgUrl
   * @return
   */
  @GetMapping(value = "/licenseOCR")
  @ApiOperation(
    tags = { "页面-营业执照" },
    value = "OCR识别营业执照信息",
    notes = "OCR识别营业执照信息",
    httpMethod = "GET"
  )
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "imgUrl",
        value = "图片URL",
        paramType = "imgUrl",
        dataType = "imgUrl",
        required = true
      ),
    }
  )
  public Result getBusinessLicenseInfo(@RequestParam String imgUrl) {
    String accessToken = baiduOCRService.getAuth();
    String blCardOCRUrl = ParametersUtil.blCardOCRUrl;

    try {
      String imgStr = ImageUtils.image2Base64(imgUrl);
      String imgParam = URLEncoder.encode(imgStr, "UTF-8");
      String params = "image=" + imgParam;
      String info = baiduOCRService.getInfo(blCardOCRUrl, accessToken, params);
      return ResultGenerator.genSuccessResult(JSONObject.parseObject(info));
    } catch (Exception e) {
      e.printStackTrace();
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      return ResultGenerator.genFailResult("识别错误，请稍后再试");
    }
  }

  @GetMapping(value = "/bankCardOCR")
  @ApiOperation(
    tags = { "页面-绑定银行卡" },
    value = "OCR识别银行卡信息",
    notes = "OCR识别银行卡信息",
    httpMethod = "GET"
  )
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "imgUrl",
        value = "图片URL",
        paramType = "imgUrl",
        dataType = "imgUrl",
        required = true
      ),
    }
  )
  public Result getIdCardInfo(@RequestParam String imgUrl) {
    String accessToken = baiduOCRService.getAuth();
    String idCardOCRUrl = ParametersUtil.bankCardOCRUrl;

    Map<String, Object> result;
    try {
      String imgStr = ImageUtils.image2Base64(imgUrl);
      String imgParam = URLEncoder.encode(imgStr, "UTF-8");
      String params = "image=" + imgParam;
      String info = baiduOCRService.getInfo(idCardOCRUrl, accessToken, params);
      result =
        JSON.parseObject(
          info,
          new TypeToken<Map<String, Object>>() {}.getType()
        );
    } catch (Exception e) {
      e.printStackTrace();
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      return ResultGenerator.genFailResult("识别错误，请稍后再试");
    }

    if (result != null && result.get("result") != null) {
      String result1 = result.get("result").toString();
      BankCardInfoVO bankCardInfoVO = JSON.parseObject(
        result1,
        BankCardInfoVO.class
      );
      if (bankCardInfoVO != null) {
        String bankName = bankCardInfoVO.getBank_name();
        bankCardInfoVO.setBank_name(FixedData.getBankName(bankName));
        result.put("result", bankCardInfoVO);
      }
    }

    return ResultGenerator.genSuccessResult(result);
  }

  @GetMapping(value = "/bankCardDetail")
  @ApiOperation(
    value = "银行卡信息回显",
    notes = "银行卡信息回显",
    httpMethod = "GET"
  )
  public Result<Object> bankCardDetail(@RequestParam String userId) {
    BankCardVO bankCardVO = accountService.bankcardDetail(userId);
    return ResultGenerator.genSuccessResult(bankCardVO);
  }

  @GetMapping(value = "/idCardDetail")
  @ApiOperation(
    value = "身份证信息回显",
    notes = "身份证信息回显",
    httpMethod = "GET"
  )
  public Result<Object> idCardDetail(
    @RequestParam(required = true) String userId
  ) {
    IdCardVO idCardVO = accountService.idCardDetail(userId);
    return ResultGenerator.genSuccessResult(idCardVO);
  }

  @PostMapping(value = "/expandMerchantList")
  @ApiOperation(
    value = "商户拓展列表接口",
    notes = "商户拓展列表接口",
    httpMethod = "POST"
  )
  public Result<Map<String, Object>> expandMerchantList(
    @RequestBody ExpandDto dto
  ) {
    Map<String, Object> result = userAppService.expandMerchantList(dto);
    return ResultGenerator.genSuccessResult(result);
  }

  @GetMapping("/queryJunior")
  @ApiOperation(
    value = "查询下级的流水，分润贡献(只查当前下级是商户的流水)",
    httpMethod = "GET"
  )
  @ApiImplicitParams(
    {
      @ApiImplicitParam(
        name = "userId",
        value = "当前点击的用户userId",
        paramType = "query",
        dataType = "String"
      ),
    }
  )
  public Result<Map<String, Object>> queryUser(
    @ApiParam(name = "userId", value = "用户id") @RequestParam String userId,
    @ApiParam(
      name = "merchantUserId",
      value = "商户的userId"
    ) @RequestParam String merchantUserId
  ) {
    Map<String, Object> resultMap = userAppService.queryAllMerchantFee(
      userId,
      merchantUserId
    );
    return ResultGenerator.genSuccessResult(resultMap);
  }

  /**
   * 商户推广-商户列表
   */
  @PostMapping("/merChantList")
  @ApiOperation(
    value = "商户推广-商户列表",
    notes = "返回分页过后的数据",
    httpMethod = "POST"
  )
  public Result merChantList(@RequestBody ExpandDto dto) {
    if (StringUtil.isEmpty(dto.getUserId())) {
      return ResultGenerator.genFailResult("请先登录账号");
    }

    //间推集合
    List<String> userList2 = new ArrayList<>();
    //间推集合
    List<String> userList3 = new ArrayList<>();

    List<String> parentIdList = new ArrayList<>();
    if (StringUtil.isEmpty(dto.getRecommend())) {
      //查询全部
      parentIdList.add(dto.getUserId());
      //查询出直推的集合
      UserApp userApp1 = new UserApp();
      userApp1.setParentId(Long.parseLong(dto.getUserId()));
      List<UserApp> userAppList = userAppService.queryUserAppListByPhone(
        userApp1
      );
      for (UserApp u : userAppList) {
        parentIdList.add(u.getUserId() + "");
        userList2.add(u.getUserId() + "");
      }
      if (!userList2.isEmpty()) {
        UserApp userApp3 = new UserApp();
        userApp3.setParentIdList(userList2);
        List<UserApp> userAppList3 = userAppService.queryUserAppListByPhone(
          userApp3
        ); //间推的集合
        for (UserApp u : userAppList3) {
          parentIdList.add(u.getUserId() + "");
          userList3.add(u.getUserId() + "");
        }
      }
    }

    if (StringUtil.isNotEmpty(dto.getRecommend())) {
      if ("1".equals(dto.getRecommend())) {
        parentIdList.add(dto.getUserId());
      }
      if ("2".equals(dto.getRecommend())) {
        //查询出直推的集合
        UserApp userApp1 = new UserApp();
        userApp1.setParentId(Long.parseLong(dto.getUserId()));
        List<UserApp> userAppList = userAppService.queryUserAppListByPhone(
          userApp1
        );
        for (UserApp u : userAppList) {
          parentIdList.add(u.getUserId() + "");
          userList2.add(u.getUserId() + "");
        }
      }

      if ("3".equals(dto.getRecommend())) {
        //查询出直推的集合
        List<String> parentIdList2 = new ArrayList<>();
        UserApp userApp1 = new UserApp();
        userApp1.setParentId(Long.parseLong(dto.getUserId()));
        List<UserApp> userAppList = userAppService.queryUserAppListByPhone(
          userApp1
        );
        for (UserApp u : userAppList) {
          parentIdList2.add(u.getUserId() + "");
        }
        if (!parentIdList2.isEmpty()) {
          UserApp userApp2 = new UserApp();
          userApp2.setParentIdList(parentIdList2);
          List<UserApp> userAppList2 = userAppService.queryUserAppListByPhone(
            userApp2
          ); //间推的集合
          for (UserApp u : userAppList2) {
            parentIdList.add(u.getUserId() + "");
            userList3.add(u.getUserId() + "");
          }
        }
      }
    }

    Map<String, Object> map = new HashMap<>();
    if (StringUtil.isNotEmpty(dto.getLevel())) {
      map.put("level", dto.getLevel());
    }
    if (parentIdList.isEmpty()) {
      parentIdList.add("999999999999999999999999");
    }
    map.put("parentIdList", parentIdList);
    map.put("pageSize", dto.getSize());
    map.put("offset", (dto.getPage() - 1) * dto.getSize());
    map.put("leshuaStatus", "3");
    if (StringUtil.isNotEmpty(dto.getStartTime())) {
      map.put("startTime", dto.getStartTime());
    }
    if (StringUtil.isNotEmpty(dto.getEndTime())) {
      map.put("endTime", dto.getEndTime());
    }
    if (StringUtil.isNotEmpty(dto.getMerchantName())) {
      map.put("merchantName", dto.getMerchantName());
    }

    List<UserApp> userAppList = userAppService.queryUserAppPageByPhone(map);

    List<UserApp> appList = new ArrayList<UserApp>();

    for (UserApp u : userAppList) {
      MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
      merchantBaseInfo.setUserId(u.getUserId() + "");
      List<MerchantBaseInfo> merchantList = merchantBaseInfoService.queryMerchantBaseInfoList(
        merchantBaseInfo
      );
      if (merchantList != null && !merchantList.isEmpty()) {
        u.setAlias(merchantList.get(0).getAlias());
        u.setMerchantCode(merchantList.get(0).getMerchantCode());
        Map<String, Object> map2 = new HashMap<>();
        map2.put("merchantCode", merchantList.get(0).getMerchantCode());
        map2.put("status", "1");
        Double totalMoney = merchantOrderService.queryMerchantOrderFeeByTime(
          map2
        ); //总流水

        if (totalMoney == null) {
          totalMoney = 0d;
        }
        u.setTotalMoney(totalMoney);
        if (StringUtil.isEmpty(u.getUserName())) {
          u.setUserName(merchantList.get(0).getContactName());
        }
        if (StringUtil.isEmpty(u.getLoginName())) {
          u.setLoginName(merchantList.get(0).getContactName());
        }
      }

      if ((u.getParentId() + "").equals(dto.getUserId())) {
        u.setType("直接推荐");
      }

      for (String s : userList2) {
        if (s.equals(u.getParentId() + "")) {
          u.setType("间接推荐");
        }
      }
      for (String s : userList3) {
        if (s.equals(u.getParentId() + "")) {
          u.setType("二级间接推荐");
        }
      }
      if (StringUtil.isNotEmpty(dto.getLevel())) {
        UserApp parentUserApp = new UserApp();
        parentUserApp.setUserId(u.getParentId());
        parentUserApp = userAppService.queryUserApp(parentUserApp);
        if (
          parentUserApp != null &&
          dto.getLevel().equals(parentUserApp.getLevel() + "")
        ) {
          appList.add(u);
        }
      } else {
        appList.add(u);
      }
    }

    Integer count = userAppService.queryUserAppPageCountByPhone(map);
    // 返回参数
    Map<String, Object> result = new HashMap<>(16);
    PageInfo<UserApp> pager = new PageInfo<>(
      count.longValue(),
      (long) StringUtil.getPageCount(count, dto.getSize()),
      dto.getPage().longValue(),
      dto.getSize().longValue(),
      appList
    );
    result.put("pager", pager);

    return ResultGenerator.genSuccessResult(result);
  }

  /**
   * 商户推广-商户列表  商户详情
   */
  @PostMapping("/extendMerchantDetail")
  @ApiOperation(
    tags = { "页面-商户详情" },
    value = "商户推广-商户详情",
    notes = "返回分页过后的数据",
    httpMethod = "POST"
  )
  public Result<Object> extendMerchantDetail(@RequestBody MerchantDTO dto) {
    Map<String, Object> resMap = new HashMap<>();

    if (StringUtil.isEmpty(dto.getMerchantCode())) {
      return ResultGenerator.genFailResult("请传商户编码");
    }

    if (StringUtil.isEmpty(dto.getUserId())) {
      return ResultGenerator.genFailResult("请登录");
    }

    UserApp tokenUserApp = userAppService.queryUserAppByToken();

    MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
    merchantBaseInfo.setMerchantCode(dto.getMerchantCode());
    merchantBaseInfo =
      merchantBaseInfoService.queryMerchantBaseInfo(merchantBaseInfo);
    if ("1".equals(merchantBaseInfo.getMerchantType())) {
      resMap.put("merchantType", "小微商户");
    } else if ("2".equals(merchantBaseInfo.getMerchantType())) {
      resMap.put("merchantType", "个体商户");
    } else if ("3".equals(merchantBaseInfo.getMerchantType())) {
      resMap.put("merchantType", "企业商户");
    }

    UserApp userApp = new UserApp();
    userApp.setUserId(Long.parseLong(merchantBaseInfo.getUserId()));
    userApp = userAppService.queryUserApp(userApp);

    UserApp userApp2 = new UserApp();
    if (userApp.getAgentStaffId() == null) {
      userApp2.setUserId(userApp.getParentId());
    } else {
      userApp2.setUserId(userApp.getAgentStaffId());
    }

    userApp2 = userAppService.queryUserApp(userApp2);

    UserInfo userInfo = new UserInfo();
    userInfo.setId(userApp.getUserId());
    userInfo = userInfoService.queryUserInfo(userInfo);

    UserInfo userInfo2 = new UserInfo();
    userInfo2.setId(userApp2.getUserId());
    userInfo2 = userInfoService.queryUserInfo(userInfo2);
    resMap.put("extentManName", userApp2.getUserName());
    resMap.put("extentMan", userInfo2.getPhone());
    resMap.put("extentManLevel", userApp2.getLevel());

    MerchantRate merchantRate = new MerchantRate()
    .setUserId(merchantBaseInfo.getUserId() + "");
    merchantRate =
      merchantRateMapper.selectOne(new QueryWrapper<>(merchantRate));
    if (merchantRate != null) {
      resMap.put("rate", "0." + merchantRate.getRate() + "%");
    } else {
      resMap.put("rate", "0.38%");
    }

    Map<String, Object> map = new HashMap<>();
    map.put("merchantCode", dto.getMerchantCode());

    map.put("userId", dto.getUserId());
    Double totalProfit = merchantProfitService.queryMerchantProfitSumPrice(map); //所有产生分润的总分润
    if (totalProfit == null) {
      totalProfit = 0d;
    }
    resMap.put("totalProfit", totalProfit + "");
    map.put("startTime", DateUtils.getDayBegin());
    map.put("endTime", DateUtils.getDayEnd());

    Double todayProfit = merchantProfitService.queryMerchantProfitSumPrice(map); //今日分润
    if (todayProfit == null) {
      todayProfit = 0d;
    }

    Map<String, Object> orderMap = new HashMap<String, Object>();
    orderMap.put("merchantCode", dto.getMerchantCode());
    orderMap.put("status", "1");

    Double totalMoney = merchantOrderService.queryMerchantOrderFeeByTime(
      orderMap
    ); //总流水
    if (totalMoney == null) {
      totalMoney = 0d;
    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    orderMap.put("startTime", sdf.format(DateUtils.getBeginDayOfMonth()) + "");
    orderMap.put("endTime", sdf.format(DateUtils.getEndDayOfMonth()) + "");
    Double monthMoney = merchantOrderService.queryMerchantOrderFeeByTime(
      orderMap
    ); //本月流水
    if (monthMoney == null) {
      monthMoney = 0d;
    }

    orderMap.put("startTime", sdf.format(DateUtils.getDayBegin()) + "");
    orderMap.put("endTime", sdf.format(DateUtils.getDayEnd()) + "");
    Double todayMoney = merchantOrderService.queryMerchantOrderFeeByTime(
      orderMap
    ); //今日流水
    if (todayMoney == null) {
      todayMoney = 0d;
    }

    resMap.put("todayProfit", todayProfit + "");
    resMap.put("todayMoney", todayMoney + "");
    resMap.put("totalMoney", totalMoney + "");
    resMap.put("monthMoney", monthMoney + "");

    resMap.put("userName", DesensitizedUtil.chineseName(userApp.getUserName()));
    resMap.put(
      "phone",
      DesensitizedUtil.mobilePhone(userInfo.getPhone().substring(0, 11))
    );
    resMap.put("createTime", userApp.getCreateDt());

    resMap.put("alias", merchantBaseInfo.getAlias());
    resMap.put("address", merchantBaseInfo.getAddress());

    return ResultGenerator.genSuccessResult(resMap);
  }

  /**
   * 商户推广-商户列表
   */
  @PostMapping("/merChantListByTime")
  @ApiOperation(
    tags = {
      "页面-新增商户_今日新增", "页面-新增商户_所有商户", "页面-商户列表",
    },
    value = "新增商户-商户列表",
    notes = "返回分页过后的数据",
    httpMethod = "POST"
  )
  public Result<Map<String, Object>> merChantListByTime(
    @RequestBody ExpandDto dto
  ) {
    Map<String, Object> result = userAppService.getMerchantListByCondition(dto);
    return ResultGenerator.genSuccessResult(result);
  }

  /**
   * 商户推广-商户列表
   */
  @GetMapping("/merChantListV2")
  @ApiOperation(
    tags = {
      "页面-新增商户_今日新增", "页面-新增商户_所有商户", "页面-商户列表",
    },
    value = "新增商户-商户列表",
    notes = "返回分页过后的数据",
    httpMethod = "POST"
  )
  public Result<Map<String, Object>> merChantListV2(
    Page<MerchSummaryVO> page,
    MerchSearchDTO merchSearchDTO,
    OrderItem orderItem
  ) {
    page.getOrders().clear();
    // 如果排序列是1, 那么就按总金额排序, 排序列是2, 那么就按笔数排序
    if ("1".equals(orderItem.getColumn())) {
      orderItem.setColumn("mos.totalFee");
    } else if ("2".equals(orderItem.getColumn())) {
      orderItem.setColumn("mos.count");
    } else {
      orderItem.setColumn("ua.createDt");
    }
    page.getOrders().add(orderItem);

    UserApp tokenUa = userAppService.queryUserAppByToken();
    if (
      !"agent".equals(tokenUa.getUserType()) &&
      merchSearchDTO.getAgentStaffIds() != null
    ) {
      merchSearchDTO.getAgentStaffIds().clear();
    }
    if (
      "2".equals(merchSearchDTO.getType()) &&
      merchSearchDTO.getAgentStaffIds() != null
    ) {
      merchSearchDTO.getAgentStaffIds().clear();
    }

    merchSearchDTO.setUserId(tokenUa.getUserId() + "");
    Map<String, Object> result = userAppService.getMerchantListByConditionV2(
      page,
      merchSearchDTO
    );
    return ResultGenerator.genSuccessResult(result);
  }

  @GetMapping("/agentLevelInfo")
  public Result<Map<String, Object>> agentLevelInfo() {
    UserApp userApp = userAppService.queryUserAppByToken();
    Double curMonthTotalConsume = merchantOrderMapper.querySubMerchantTransMonthAmount(
      userApp.getUserId().toString()
    );
    Double lastMonthTotalConsume = merchantOrderMapper.querySubMerchantTransLastMonthAmount(
      userApp.getUserId().toString()
    );

    Map<String, Object> map = new HashMap<>();
    map.put(
      "curMonthTotalConsume",
      curMonthTotalConsume == null ? 0d : curMonthTotalConsume
    );
    map.put("curMonthTotalConsumeMax", 10000000);
    map.put(
      "lastMonthTotalConsume",
      lastMonthTotalConsume == null ? 0d : lastMonthTotalConsume
    );
    map.put("lastMonthTotalConsumeMax", 10000000);

    QueryWrapper<MerchantRate> merchantRateQueryWrapper = new QueryWrapper<MerchantRate>()
    .eq("userId", userApp.getUserId());
    MerchantRate merchantRate = merchantRateMapper.selectOne(
      merchantRateQueryWrapper
    );

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(merchantRate.getUpdateTime());
    Calendar calendarNow = Calendar.getInstance();
    if (calendar.get(Calendar.MONTH) == calendarNow.get(Calendar.MONTH)) {
      map.put("rate", merchantRate.getPreviousRate());
    } else {
      // 获取新的费率
      map.put("rate", merchantRate.getRate());
      // 保存新的费率
      merchantRate.setPreviousRate(merchantRate.getRate());
      merchantRate.setUpdateTime(new Date());
      merchantRateMapper.updateById(merchantRate);
    }

    return ResultGenerator.genSuccessResult(map);
  }

  @GetMapping("/agent/agentShare")
  public Result<Map<String, Object>> agentShareInfo() {
    UserApp userApp = userAppService.queryUserAppByToken();
    Map<String, Object> map = new HashMap<>();

    if ("agent_staff".equals(userApp.getUserType())) {
      map.put("userId", userApp.getParentId());
      map.put("agentStaffId", userApp.getUserId());
    } else {
      map.put("userId", userApp.getUserId());
    }

    Double consumeFeeTotal = merchantProfitService.queryMerchantProfitSumConsumeFee(
      map
    );
    Double priceTotal = merchantProfitService.queryMerchantProfitSumPrice(map);

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    map.put("stTime", calendar.getTime());

    Double consumeFeeCurrentMonth = merchantProfitService.queryMerchantProfitSumConsumeFee(
      map
    );
    Double priceCurrentMonth = merchantProfitService.queryMerchantProfitSumPrice(
      map
    );

    Map<String, Object> result = new HashMap<>();
    result.put(
      "consumeFeeTotal",
      consumeFeeTotal == null ? 0d : consumeFeeTotal
    );
    result.put("priceTotal", priceTotal == null ? 0d : priceTotal);
    result.put(
      "consumeFeeCurrentMonth",
      consumeFeeCurrentMonth == null ? 0d : consumeFeeCurrentMonth
    );
    result.put(
      "priceCurrentMonth",
      priceCurrentMonth == null ? 0d : priceCurrentMonth
    );

    Double totalShareMoneyToday; // 今日分润总额
    Double totalAccumulateShareMoney; // 累计总分润

    double allowCashMoney; // 可提现分润
    double noCashMoney; // 不可提现分润
    Double cashedMoney; // 已提现分润
    // 获取当前商户的所有的下级商户信息

    Map<String, Object> queryMap = new HashMap<>();
    if ("agent_staff".equals(userApp.getUserType())) {
      queryMap.put("agentStaffId", userApp.getUserId());
    } else {
      queryMap.put("userId", userApp.getUserId());
    }

    queryMap.put("status", 1);

    // 累计总分润
    totalAccumulateShareMoney =
      merchantProfitService.queryMerchantProfitSumPrice(queryMap);
    if (totalAccumulateShareMoney == null) {
      totalAccumulateShareMoney = 0d;
    }
    queryMap.put("startTime", DateUtils.getDayBegin());
    totalShareMoneyToday =
      merchantProfitService.queryMerchantProfitSumPrice(queryMap);
    if (totalShareMoneyToday == null) {
      totalShareMoneyToday = 0d;
    }

    // 今日总分润 = 今日商户分润
    cashedMoney = cashService.sumMerchantSuccessCash(userApp.getUserId()); //已经提现与正在提现的分润 //+ cashService.sumFansAreadlyCash(map);
    if (cashedMoney == null) {
      cashedMoney = 0d;
    }
    noCashMoney = totalShareMoneyToday;
    allowCashMoney = totalAccumulateShareMoney - cashedMoney - noCashMoney;

    result.put(
      "totalShareMoneyToday",
      StringUtil.bigDecimal(totalShareMoneyToday)
    ); //今日总分润
    result.put(
      "totalAccumulateShareMoney",
      StringUtil.bigDecimal(totalAccumulateShareMoney)
    ); //累计总分润

    result.put(
      "allowCashMoney",
      StringUtil.bigDecimal(allowCashMoney, RoundingMode.DOWN)
    );
    result.put("noCashMoney", StringUtil.bigDecimal(noCashMoney));
    result.put("cashedMoney", StringUtil.bigDecimal(cashedMoney));

    return ResultGenerator.genSuccessResult(result);
  }

  @GetMapping("/agent/agentStaffShare")
  public Result<Map<String, Object>> agentStaffShareInfo() {
    Map<String, Object> objectMap = userAppService.agentStaffShareInfo();
    return ResultGenerator.genSuccessResult(objectMap);
  }

  @RequestMapping(
    value = "/rate",
    method = { RequestMethod.GET, RequestMethod.POST }
  )
  public Result<Integer> rateInfo() {
    UserApp userApp = userAppService.queryUserAppByToken();
    MerchantRate merchantRate = new MerchantRate()
    .setUserId(userApp.getUserId() + "");
    merchantRate =
      merchantRateMapper.selectOne(new QueryWrapper<>(merchantRate));

    if (merchantRate == null) {
      return ResultGenerator.genSuccessResult(38);
    } else {
      return ResultGenerator.genSuccessResult(merchantRate.getRate());
    }
  }

  @GetMapping(value = "/levelUpOrder")
  public Result<Object> levelUpOrder(String type) {
    throw new MsgException("系统升级中, 暂不支持该升级方式");
    // UserApp userApp = userAppService.queryUserAppByToken();
    //
    // Map<String, Object> result = userAppService.getLevelUpOrder(userApp, type);
    //
    // return ResultGenerator.genSuccessResult(result);
  }

  @GetMapping(value = "/levelUpOrderV2Info")
  public Result<Object> levelUpOrderInfo(String level) {
    UserApp userApp = userAppService.queryUserAppByToken();

    Map<String, Object> result = userAppService.getLevelUpOrderV2Info(
      userApp,
      level
    );

    return ResultGenerator.genSuccessResult(result);
  }

  @GetMapping(value = "/levelUpOrderV2")
  public Result<Object> levelUpOrderV2(String level, String type) {
    UserApp userApp = userAppService.queryUserAppByToken();

    Map<String, Object> result = userAppService.getLevelUpOrderV2(
      userApp,
      type,
      level
    );

    return ResultGenerator.genSuccessResult(result);
  }

  @GetMapping("/parentInfo")
  public Result<UserAppVO> getParentInfo() {
    UserApp userApp = userAppService.queryUserAppByToken();
    QueryWrapper<UserApp> qWrapper = new QueryWrapper<UserApp>()
    .eq("userId", userApp.getParentId());
    userApp = userAppService.getOne(qWrapper);
    if (userApp == null) {
      return ResultGenerator.genSuccessResult("无上级信息", null);
    }
    UserInfo ui = userInfoService.getById(userApp.getUserId());

    UserAppVO result = new UserAppVO();
    result.setUserName(DesensitizedUtil.chineseName(userApp.getUserName()));
    result.setPhone(ui.getPhone());
    result.setInviteNum(userApp.getInviteNum());
    result.setLogo(userApp.getLogo());

    return ResultGenerator.genSuccessResult(result);
  }

  @GetMapping("/pageSubTeamData")
  public Result<Page<UserAppVO>> pageSubTeamData(
    Page<UserAppVO> page,
    String userName
  ) {
    page.getOrders().clear();
    page.getOrders().add(OrderItem.desc("ua.createDt"));
    page = userProfitService.apiPageMonthSubTeamData(page, userName);

    for (UserAppVO record : page.getRecords()) {
      record.setUserName(DesensitizedUtil.chineseName(record.getUserName()));
      if ("LV10".equals(record.getLevelName())) {
        record.setLevelName("SVIP");
      } else {
        record.setLevelName(record.getLevelCode().replace("LV", "VIP"));
      }
    }

    return ResultGenerator.genSuccessResult("操作成功", page);
  }

  /**
   * 根据手机号获取划拨用户
   * @param phone
   * @return
   */
  @GetMapping("/get/phone/{phone}")
  public Result<Object> getUserAppByPhone(
    @PathVariable(value = "phone") String phone
  ) {
    UserApp userApp = userAppService.checkApiToken();
    UserApp info = userAppService.getUserAppByPhone(phone, userApp);
    return ResultGenerator.genSuccessResult("操作成功", info);
  }
}
