package cn.pluss.platform.controller.promoter;

import cn.pluss.platform.BankCardService;
import cn.pluss.platform.IdCardService;
import cn.pluss.platform.SxfMccInfoService;
import cn.pluss.platform.agentInfo.AgentInfoService;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.common.CommonRemarkService;
import cn.pluss.platform.converter.Converter;
import cn.pluss.platform.dto.AccountDTO;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.inviteRate.InviteRateService;
import cn.pluss.platform.mapper.AccountMapper;
import cn.pluss.platform.mapper.AreaCityMapper;
import cn.pluss.platform.mapper.BankCodeSxfMapper;
import cn.pluss.platform.mapper.OperationRecordMapper;
import cn.pluss.platform.merchant.AccountService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchant.MerchantPluginService;
import cn.pluss.platform.merchantChannel.MerchantChannelService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.merchantImage.MerchantImageService;
import cn.pluss.platform.merchantRejectDesc.MerchantRejectDescService;
import cn.pluss.platform.merchantStore.MerchantStoreService;
import cn.pluss.platform.notice.NoticeService;
import cn.pluss.platform.officialActivity.OfficialActivityService;
import cn.pluss.platform.user.UserLevelService;
import cn.pluss.platform.user.impl.GeneralPushUtil;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.*;
import cn.pluss.platform.vo.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 推广员管理
 *
 * @author Administrator
 */
@Controller
@RequestMapping("promoter")
public class PromoterController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private AreaCityMapper areaCityMapper;

    @Autowired
    private UserAppService uaService;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private MerchantImageService merchantImageService;

    @Autowired
    private UserInfoService uiService;

    @Autowired
    private SxfMccInfoService sxfMccInfoService;

    @Autowired
    private MerchantBaseInfoService mbiService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private BankCardService bankCardService;

    @Autowired
    private IdCardService idCardService;

    @Autowired
    private InviteRateService inviteRateService;

    @Autowired
    private OfficialActivityService officialActivityService;

    @Resource
    private BankCodeSxfMapper bankCodeSxfMapper;

    @Autowired
    private MerchantRejectDescService merchantRejectDescService;

    @Autowired
    private MerchantChannelService merchantChannelService;

    @Autowired
    private MerchantStoreService msService;

    @Autowired
    private MerchantPluginService merchantPluginService;

    @Autowired
    private MerchantChannelStatusService merchantChannelStatusService;

    @Resource
    private OperationRecordMapper oprMapper;

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private UserLevelService userLevelService;

    @Autowired
    private AgentInfoService agentInfoService;

    @Autowired
    private CommonRemarkService crService;

    @Autowired
    private GeneralPushUtil generalPushUtil;

    @GetMapping("/permissionIndex")
    public String permissionIndex() {
        return "/promoter/permissionList";
    }

    @GetMapping("/remark")
    public String remark(HttpServletRequest request, Integer userId) {
        if (userId != null) {
            CommonRemark cr = new CommonRemark();
            cr.setUserId(userId);
            cr.setCode("USER");
            CommonRemark exist = crService.getOne(new QueryWrapper<>(cr));
            if (exist != null) {
                cr.setRemark(exist.getRemark());
            }
            request.setAttribute("entity", cr);
        }
        return "/promoter/remark";
    }

    @GetMapping("/permissionPage")
    @ResponseBody
    public Result<Object> permissionPage(Page<AgentInfo> page, AgentInfo agentInfo) {
        Page<AgentInfo> pageData = agentInfoService.pagePermissionData(page, agentInfo);
        return ResultGenerator.genSuccessResult(PageUtils.page(pageData));
    }

    @PostMapping("/openAll")
    @ResponseBody
    public Result<Object> openAll(Long userId) {
        UserApp ua = new UserApp().setUserId(userId);
        ua = uaService.getOne(new QueryWrapper<>(ua));
        ua.setAutoAudit("1");
        ua.setIsMarket("1");
        ua.setIsUnionPay("1");
        ua.setPayEcdemicSwitch("1");

        uaService.updateById(ua);

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

    @PostMapping("/userRemark")
    @ResponseBody
    public Result<Object> saveRemark(String remark, Integer userId) {
        CommonRemark commonRemark = new CommonRemark();
        commonRemark.setCode("USER");
        commonRemark.setUserId(userId);
        commonRemark.setRemark(remark);
        CommonRemark exist = crService.getOne(new QueryWrapper<>(commonRemark));
        if (exist != null) {
            commonRemark.setId(exist.getId());
            commonRemark.setUpdateTime(new Date());
        } else {
            commonRemark.setCreateTime(new Date());
        }
        crService.saveOrUpdate(commonRemark);

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

    /**
     * 引导页
     *
     */
    @GetMapping(value = "/index")
    public String index() {
        String userType = request.getParameter("userType");
        request.setAttribute("userType", userType);
        return "promoter/userAppList";
    }

    @GetMapping(value = "/actIndex")
    public String actIndex() {
        String userType = request.getParameter("userType");
        request.setAttribute("userType", userType);
        return "promoter/actUserList";
    }

    @RequestMapping(value = "/queryActPage")
    @ResponseBody
    public Result<Page<UserInfoVO>> queryActPage(Page<UserInfoVO> page, UserInfoVO userInfoVO) {
        String startDate = "2020-12-01";
        String endDate = "2021-02-01";
        List<InviteRate> inviteRateList = inviteRateService.list(new QueryWrapper<InviteRate>().orderByAsc("number").eq("type", "merchant"));
        if (!inviteRateList.isEmpty()) {
            InviteRate rate = inviteRateList.get(0);
            OfficialActivity act = officialActivityService.getById(rate.getActId());
            if (act != null) {
                startDate = DateUtils.formatDateDefault(act.getStartTime(), "yyyy-MM-dd");
                endDate = DateUtils.formatDateDefault(act.getEndTime(), "yyyy-MM-dd");
            }
        }
        Date startTime = DateUtils.parse(startDate + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
        Date endTime = DateUtils.parse(endDate + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
        userInfoVO.setStartTime(startTime);
        userInfoVO.setEndTime(endTime);
        page = uaService.queryActPage(page, userInfoVO);
        return ResultGenerator.genSuccessResult("查询成功！", page);
    }

    /**
     * 分页查询
     */
    @GetMapping("/queryUserAppByPage")
    @ResponseBody
    public Map<String, Object> queryUserAppByPage(@RequestParam(defaultValue = "1") Integer currPage, Integer size,
                                                  UserInfoVO userInfoVO) {

        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", size);
        map.put("offset", (currPage - 1) * size);
        // 筛选出推广员
        if (StringUtils.isNotEmpty(userInfoVO.getUserName())) {
            map.put("userName", userInfoVO.getUserName());
        }
        if (userInfoVO.getUserId() != null) {
            map.put("userId", userInfoVO.getUserId());
        } else {
            userInfoVO.setSameIp(null);
        }

        if (userInfoVO.getSameIp() != null) {
            map.put("sameIp", "1");
        }

        if (StringUtils.isNotEmpty(userInfoVO.getPhone())) {
            map.put("phone", userInfoVO.getPhone());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getMerchantCode())) {
            map.put("merchantCode", userInfoVO.getMerchantCode());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getParentPhone())) {
            map.put("parentPhone", userInfoVO.getParentPhone());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getMerchantType())) {
            map.put("merchantType", userInfoVO.getMerchantType());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getMerchantId())) {
            map.put("merchantId", userInfoVO.getMerchantId());
        }
        if (userInfoVO.getStatus() != null) {
            map.put("status", userInfoVO.getStatus());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getUserType())) {
            map.put("userType", userInfoVO.getUserType());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getParentUserType())) {
            map.put("parentUserType", userInfoVO.getParentUserType());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getInviteNum())) {
            map.put("inviteNum", userInfoVO.getInviteNum());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getAlias())) {
            map.put("alias", userInfoVO.getAlias());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getWxMercNo())) {
            map.put("wxMercNo", userInfoVO.getWxMercNo());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getZfbMercNo())) {
            map.put("zfbMercNo", userInfoVO.getZfbMercNo());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getMcsStatus())) {
            if ("0".equals(userInfoVO.getMcsStatus())) {
                userInfoVO.setMcsStatus("1");
                userInfoVO.setThirdStatus(MerchantChannelStatus.AUDIT_THIRD_STATUS_WAITING);
                map.put("thirdStatus", userInfoVO.getThirdStatus());
            } else if ("1".equals(userInfoVO.getMcsStatus())) {
                userInfoVO.setThirdStatus("100");
                map.put("thirdStatus", userInfoVO.getThirdStatus());
            }
            map.put("mcsStatus", userInfoVO.getMcsStatus());
        }

        if (StringUtils.isNotEmpty(userInfoVO.getPpStatus())) {
            if ("0".equals(userInfoVO.getPpStatus())) {
                userInfoVO.setPpStatus("1");
                userInfoVO.setPpThirdStatus(MerchantChannelStatus.AUDIT_THIRD_STATUS_WAITING);
                map.put("ppThirdStatus", userInfoVO.getPpThirdStatus());
            } else if ("1".equals(userInfoVO.getPpStatus())) {
                userInfoVO.setPpThirdStatus("100");
                map.put("ppThirdStatus", userInfoVO.getPpThirdStatus());
            }
            map.put("ppStatus", userInfoVO.getPpStatus());
        }

        Page<UserInfoVO> pageData = uaService.queryUserInfoVOPage(map);
        if (!pageData.getRecords().isEmpty()) {
            for (UserInfoVO infoVO : pageData.getRecords()) {
                if ("agent".equals(infoVO.getUserType()) && infoVO.getParentUserId() != null) {
                    infoVO.setUserType("agent_agency");
                }
                if (infoVO.getParentUserType() != null && "agent".equals(infoVO.getParentUserType())) {
                    Integer parentUserId = uaService.getParentUserId(infoVO.getParentUserId());
                    if (parentUserId > 0) {
                        infoVO.setParentUserType("agent_agency");
                    }
                }
            }
        }
        Long count = pageData.getTotal();
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("userAppList", pageData.getRecords());
        result.put("count", count);
        result.put("pageCount", StringUtil.getPageCount(count.intValue(), size));
        result.put("currPage", currPage);
        return result;
    }

    @GetMapping("/detail/{userId}")
    public String detail(@PathVariable("userId") String userId) {
        request.setAttribute("userId", userId);
        return "promoter/detail";
    }

    @GetMapping("/getLevelConfig/{id}")
    @ResponseBody
    public Result<Object> getLevelConfig(@PathVariable("id") Long id) {
        UserApp userApp = uaService.getById(id);
        if(userApp == null || StringUtil.isEmpty(userApp.getRoleCode())){
            return ResultGenerator.genFailResult("用户ID有误或用户角色未配置！");
        }
        String roleCode = userApp.getRoleCode();
        List<UserLevelVO> levelInfoByRole = userLevelService.getLevelInfoByRole(roleCode, 0);
        return ResultGenerator.genSuccessResult("获取成功",levelInfoByRole);
    }

    @GetMapping("/detail/audit/{userId}")
    public String auditInfo(@PathVariable("userId") Long userId) {
        UserApp ua = new UserApp();
        ua.setUserId(userId);
        ua = uaService.getOne(new QueryWrapper<>(ua));

        UserInfo ui = uiService.getById(userId);
        ua.setLoginName(ui.getLoginName());

        request.setAttribute("userAppInfo", ua);

        IdCard auditIdCard = idCardService.getCertIdCard(userId.toString());
        request.setAttribute("idCard", auditIdCard);

        BankCard bankCard = new BankCard();
        bankCard.setAccountType(BankCard.ACCOUNT_TYPE_CERT);
        bankCard.setUserId(userId.toString());
        bankCard = bankCardService.getOne(new QueryWrapper<>(bankCard));
        request.setAttribute("bankCard", bankCard);

        getProvince();

        return "promoter/audit";
    }

    @GetMapping("/detail/merchBaseInfo/{userId}")
    public String merchBaseInfo(@PathVariable("userId") Long userId) {
        MerchantBaseInfo mbi = mbiService.getMerchantBaseInfoByUserId(userId + "");
        request.setAttribute("merchantBaseInfo", mbi);

        List<SxfMccInfo> mccList = sxfMccInfoService.list();
        for (SxfMccInfo c : mccList) {
            if (c.getFMccCode().equals(mbi.getMcc())) {
                request.setAttribute("checkMcc", JSONObject.parseObject(JSON.toJSONString(c)));
                break;
            }
        }
        request.setAttribute("mccList", JSONArray.parseArray(JSON.toJSONString(mccList)));

        LambdaQueryWrapper<MerchantImage> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(MerchantImage::getMerchantCode, mbi.getMerchantCode());
        qWrapper.in(MerchantImage::getPhotoType
                , MerchantImage.ImageType.SHOP_FRONT_DOOR
                , MerchantImage.ImageType.CASH_DESK_PHOTO
                , MerchantImage.ImageType.STORE_INTERIOR_PHOTO
                , MerchantImage.ImageType.MERCHANT_PROTOCOL
                , MerchantImage.ImageType.MERCHANT_SUB_PROTOCOL);

        List<MerchantImage> list = merchantImageService.list(qWrapper);

        if (list == null || list.isEmpty()) {
            getProvince();
            return "promoter/merchBaseInfo";
        }

        for (MerchantImage mi : list) {
            switch (mi.getPhotoType()) {
                case MerchantImage.ImageType.SHOP_FRONT_DOOR:
                    request.setAttribute("merchantImage6", mi.getPicUrl());
                    break;
                case MerchantImage.ImageType.CASH_DESK_PHOTO:
                    request.setAttribute("merchantImage8", mi.getPicUrl());
                    break;
                case MerchantImage.ImageType.STORE_INTERIOR_PHOTO:
                    request.setAttribute("merchantImage9", mi.getPicUrl());
                    break;
                case MerchantImage.ImageType.MERCHANT_PROTOCOL:
                    request.setAttribute("merchantImage101", mi.getPicUrl());
                    break;
                case MerchantImage.ImageType.MERCHANT_SUB_PROTOCOL:
                    request.setAttribute("merchantImage102", mi.getPicUrl());
                    break;
                default:
                    break;
            }
        }

        getProvince();
        return "promoter/merchBaseInfo";
    }

    @GetMapping("/detail/merchLicense/{userId}")
    public String merchLicense(@PathVariable("userId") Long userId) {
        MerchantBaseInfo mbi = mbiService.getMerchantBaseInfoByUserId(userId + "");
        request.setAttribute("merchantBaseInfo", mbi);

        IdCard idCard = idCardService.getLegalIdCard(userId + "");
        request.setAttribute("priceIdCard", idCard);

        if (idCard != null) {
            request.setAttribute("merchantImage1", idCard.getImgPositive());
            request.setAttribute("merchantImage2", idCard.getImgNegative());
        }

        LambdaQueryWrapper<MerchantImage> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(MerchantImage::getMerchantCode, mbi.getMerchantCode());
        qWrapper.in(MerchantImage::getPhotoType
                , MerchantImage.ImageType.BUSINESS_LICENSE
                , MerchantImage.ImageType.IDCARD_FRONT
                , MerchantImage.ImageType.IDCARD_BACK);

        List<MerchantImage> list = merchantImageService.list(qWrapper);

        if (list == null || list.isEmpty()) {
            getProvince();
            return "promoter/merchLicense";
        }

        for (MerchantImage mi : list) {
            switch (mi.getPhotoType()) {
                case MerchantImage.ImageType.BUSINESS_LICENSE:
                    request.setAttribute("merchantImage3", mi.getPicUrl());
                    break;
                default:
                    break;
            }
        }

        return "promoter/merchLicense";
    }

    @GetMapping("/detail/settlement/{userId}")
    public String settlementInfo(@PathVariable("userId") Long userId) {
        AccountDTO accountDTO = accountService.getRealAccount(userId + "");
        if (accountDTO != null) {
            switch (accountDTO.getSettleType()) {
                case "011":
                    request.setAttribute("settleTypeName", "对私法人");
                    break;
                case "012":
                    request.setAttribute("settleTypeName", "非法人对私法人");
                    break;
                case "021":
                    request.setAttribute("settleTypeName", "法人对私非法人");
                    break;
                case "022":
                    request.setAttribute("settleTypeName", "非法人对私非法人");
                    break;
                case "03":
                    request.setAttribute("settleTypeName", "对公");
                    break;
                case "00":
                    request.setAttribute("settleTypeName", "小微");
                    break;
                default:
                    break;
            }

            request.setAttribute("bankCard", accountDTO.getBankCard());
            request.setAttribute("idCard", accountDTO.getIdcard());
        }

        MerchantBaseInfo mbi = mbiService.getMerchantBaseInfoByUserId(userId + "");
        request.setAttribute("merchantCode", mbi.getMerchantCode());

        LambdaQueryWrapper<MerchantImage> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(MerchantImage::getMerchantCode, mbi.getMerchantCode());
        qWrapper.in(MerchantImage::getPhotoType
                , MerchantImage.ImageType.HAND_IDCARD_PHOTO
                , MerchantImage.ImageType.CASH_DESK_WITH_PERSON
                , MerchantImage.ImageType.NON_LEG_SETTLE_AUTH);

        List<MerchantImage> list = merchantImageService.list(qWrapper);

        for (MerchantImage mi : list) {
            switch (mi.getPhotoType()) {
                case MerchantImage.ImageType.HAND_IDCARD_PHOTO:
                    request.setAttribute("merchantImage11", mi.getPicUrl());
                    break;
                case MerchantImage.ImageType.NON_LEG_SETTLE_AUTH:
                    request.setAttribute("merchantImage7", mi.getPicUrl());
                    break;
                case MerchantImage.ImageType.CASH_DESK_WITH_PERSON:
                    request.setAttribute("merchantImage999", mi.getPicUrl());
                    break;
                default:
                    break;
            }
        }

        getProvince();

        return "promoter/settlementInfo";
    }

    @GetMapping("/detail/settlementV2/{userId}")
    public String settlementInfoV2(@PathVariable("userId") Long userId) {
        AccountDTO accountDTO = accountService.getRealAccount(userId + "", Account.CHANNEL_TYPE_D1);
        if (accountDTO != null) {
            AccountVO dataD1 = Converter.INSTANCE.toVO(accountDTO);
            String settleTypeNameD1 = AccountVO.getSettleTypeName(accountDTO.getSettleType());
            dataD1.setSettleTypeName(settleTypeNameD1);
            request.setAttribute("d1", dataD1);
        }

        accountDTO = accountService.getRealAccount(userId + "", Account.CHANNEL_TYPE_D0);
        if (accountDTO != null) {
            AccountVO dataD0 = Converter.INSTANCE.toVO(accountDTO);
            String settleTypeNameD0 = AccountVO.getSettleTypeName(accountDTO.getSettleType());
            dataD0.setSettleTypeName(settleTypeNameD0);
            request.setAttribute("d0", dataD0);
        }

        MerchantBaseInfo mbi = mbiService.getMerchantBaseInfoByUserId(userId + "");
        request.setAttribute("merchantCode", mbi.getMerchantCode());

        LambdaQueryWrapper<MerchantImage> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(MerchantImage::getMerchantCode, mbi.getMerchantCode());
        qWrapper.in(MerchantImage::getPhotoType
                , MerchantImage.ImageType.HAND_IDCARD_PHOTO
                , MerchantImage.ImageType.CASH_DESK_WITH_PERSON
                , MerchantImage.ImageType.NON_LEG_SETTLE_AUTH);

        List<MerchantImage> list = merchantImageService.list(qWrapper);

        for (MerchantImage mi : list) {
            switch (mi.getPhotoType()) {
                case MerchantImage.ImageType.HAND_IDCARD_PHOTO:
                    request.setAttribute("merchantImage11", mi.getPicUrl());
                    break;
                case MerchantImage.ImageType.NON_LEG_SETTLE_AUTH:
                    request.setAttribute("merchantImage7", mi.getPicUrl());
                    break;
                case MerchantImage.ImageType.CASH_DESK_WITH_PERSON:
                    request.setAttribute("merchantImage999", mi.getPicUrl());
                    break;
                default:
                    break;
            }
        }

        getProvince();

        return "promoter/settlementInfoV2";
    }

    @GetMapping("/detail/channelAuditInfo/{userId}")
    public String channelAuditInfo(@PathVariable("userId") Long userId) {
        MerchantBaseInfo mbi = mbiService.getMerchantBaseInfoByUserId(userId + "");
        if (mbi != null) {
            QueryWrapper<MerchantChannelStatus> qWrapper = new QueryWrapper<MerchantChannelStatus>()
                    .eq("merchantCode", mbi.getMerchantCode());
            List<MerchantChannelStatus> channelStatusList = merchantChannelStatusService.list(qWrapper);
            request.setAttribute("channelStatusList", channelStatusList);

            List<MerchantChannel> channelList = merchantChannelService.list(new LambdaQueryWrapper<MerchantChannel>().eq(MerchantChannel::getStatus, "1"));
            request.setAttribute("channel", channelList);
        }

        List<MerchantRejectDesc> listMerchantRejectDesc = merchantRejectDescService.list();
        request.setAttribute("listMerchantRejectDesc", listMerchantRejectDesc);

        UserApp appInfo = uaService.queryUserAppJoinById(userId);
        request.setAttribute("ppStatus", appInfo.getPpStatus());
        request.setAttribute("ppThirdStatus", appInfo.getPpThirdStatus());
        request.setAttribute("userId", userId);
        request.setAttribute("mbi", mbi);

        return "promoter/channelAuditInfo";
    }

    /**
     * 查询详情
     */
    @GetMapping(value = {"/queryUserAppBaseInfo/{userId}"})
    public ModelAndView queryUserAppBaseInfo(@PathVariable(value = "userId", required = false) Long userId) {
        ModelAndView view = new ModelAndView();
        view.setViewName("promoter/userAppBaseInfo");
        Map<String, String> uploadParam = OssOperatUtil.getUploadParam();
        view.addObject("uploadParam", uploadParam);
        if (userId != null) {
            /*
             * 获取推广员基本信息，商户信息，营业执照信息
             */
            UserApp appInfo = uaService.queryUserAppJoinById(userId);
            if (appInfo != null) {
                QueryWrapper<MerchantChannelStatus> qWrapper = new QueryWrapper<MerchantChannelStatus>().eq("merchantCode", appInfo.getMerchantCode());
                List<MerchantChannelStatus> channelStatusList = merchantChannelStatusService.list(qWrapper);
                appInfo.setChannelStatusList(channelStatusList);
            }

            List<MerchantChannel> channelList = merchantChannelService.list(new LambdaQueryWrapper<MerchantChannel>().eq(MerchantChannel::getStatus, "1"));
            view.addObject("channel", channelList);
            if (appInfo != null && appInfo.getMerchantBaseInfo() != null) {
                switch (appInfo.getMerchantBaseInfo().getProvince()) {
                    case "北京":
                        appInfo.getMerchantBaseInfo().setProvince("北京市");
                        break;
                    case "天津":
                        appInfo.getMerchantBaseInfo().setProvince("天津市");
                        break;
                    case "重庆":
                        appInfo.getMerchantBaseInfo().setProvince("重庆市");
                        break;
                    case "上海":
                        appInfo.getMerchantBaseInfo().setProvince("上海市");
                        break;
                    default:
                        break;
                }
                List<MerchantRejectDesc> listMerchantRejectDesc = merchantRejectDescService.list();
                view.addObject("listMerchantRejectDesc", listMerchantRejectDesc);
                //获取法人身份证号
                QueryWrapper<IdCard> idCardQueryWrapper = new QueryWrapper<IdCard>()
                        .eq("userId", userId).eq("userType", IdCard.TYPE_LEGAL);
                IdCard priceIdCard = idCardService.getOne(idCardQueryWrapper);
                view.addObject("priceIdCard", priceIdCard);
                //获取结算信息
                if (appInfo.getUserId() != null) {
                    try {
                        AccountDTO account = accountService.getRealAccount(appInfo.getUserId().toString());
                        if (account != null) {
                            switch (account.getSettleType()) {
                                case "011":
                                    view.addObject("settleTypeName", "对私法人");
                                    break;
                                case "012":
                                    view.addObject("settleTypeName", "非法人对私法人");
                                    break;
                                case "021":
                                    view.addObject("settleTypeName", "法人对私非法人");
                                    break;
                                case "022":
                                    view.addObject("settleTypeName", "非法人对私非法人");
                                    break;
                                case "03":
                                    view.addObject("settleTypeName", "对公");
                                    break;
                                case "00":
                                    view.addObject("settleTypeName", "小微");
                                    break;
                                default:
                                    break;
                            }
                            view.addObject("settleTypeCode", account.getSettleType());
                            BankCard bankCard = account.getBankCard();
                            IdCard idCard = account.getIdcard();
                            view.addObject("bankCard", bankCard);
                            view.addObject("idCard", idCard);
                        }
                    } catch (Exception ignored) {
                    }
                }
                if (StringUtils.isNotEmpty(appInfo.getMerchantCode())) {
                    //获取图片信息
                    MerchantImage image = new MerchantImage();
                    image.setMerchantCode(appInfo.getMerchantCode());
                    //获取经营类目信息
                    if (appInfo.getMerchantBaseInfo() != null) {
                        List<SxfMccInfo> list = sxfMccInfoService.list();
                        for (SxfMccInfo c : list) {
                            if (c.getFMccCode().equals(appInfo.getMerchantBaseInfo().getMcc())) {
                                view.addObject("checkMcc", JSON.parseObject(JSON.toJSONString(c)));
                                break;
                            }
                        }
                        request.setAttribute("mccList", JSON.parseArray(JSON.toJSONString(list)));
                    }
                    List<MerchantImage> imageList = merchantImageService.queryMerchantImageList(image);
                    String merchantImage1 = null;
                    String merchantImage2 = null;
                    String merchantImage3 = null;
                    String merchantImage6 = null;
                    String merchantImage7 = null;
                    String merchantImage8 = null;
                    String merchantImage9 = null;
                    String merchantImage98 = null;
                    String merchantImage999 = null;
                    String merchantImage101 = null;
                    String merchantImage102 = null;
                    String merchantImage11 = null;
                    if (imageList != null && !imageList.isEmpty()) {
                        for (MerchantImage m : imageList) {
                            switch (m.getPhotoType()) {
                                case MerchantImage.ImageType.IDCARD_FRONT:
                                    merchantImage1 = m.getPicUrl();
                                    break;
                                case MerchantImage.ImageType.IDCARD_BACK:
                                    merchantImage2 = m.getPicUrl();
                                    break;
                                case MerchantImage.ImageType.BUSINESS_LICENSE:
                                    merchantImage3 = m.getPicUrl();
                                    break;
                                case MerchantImage.ImageType.SHOP_FRONT_DOOR:
                                    merchantImage6 = m.getPicUrl();
                                    break;
                                case MerchantImage.ImageType.NON_LEG_SETTLE_AUTH:
                                    merchantImage7 = m.getPicUrl();
                                    break;
                                case MerchantImage.ImageType.CASH_DESK_PHOTO:
                                    merchantImage8 = m.getPicUrl();
                                    break;
                                case MerchantImage.ImageType.STORE_INTERIOR_PHOTO:
                                    merchantImage9 = m.getPicUrl();
                                    break;
                                case MerchantImage.ImageType.BANK_CARD_FRONT:
                                    merchantImage98 = m.getPicUrl();
                                    break;
                                case MerchantImage.ImageType.CASH_DESK_WITH_PERSON:
                                    merchantImage999 = m.getPicUrl();
                                    break;
                                case MerchantImage.ImageType.MERCHANT_PROTOCOL:
                                    merchantImage101 = m.getPicUrl();
                                    break;
                                case MerchantImage.ImageType.MERCHANT_SUB_PROTOCOL:
                                    merchantImage102 = m.getPicUrl();
                                    break;
                                case MerchantImage.ImageType.HAND_IDCARD_PHOTO:
                                    merchantImage11 = m.getPicUrl();
                                    break;
                                default:
                                    break;
                            }
                        }
                        view.addObject("merchantImage1", merchantImage1);
                        view.addObject("merchantImage2", merchantImage2);
                        view.addObject("merchantImage3", merchantImage3);
                        view.addObject("merchantImage6", merchantImage6);
                        view.addObject("merchantImage7", merchantImage7);
                        view.addObject("merchantImage8", merchantImage8);
                        view.addObject("merchantImage9", merchantImage9);
                        view.addObject("merchantImage98", merchantImage98);
                        view.addObject("merchantImage999", merchantImage999);
                        view.addObject("merchantImage101", merchantImage101);
                        view.addObject("merchantImage102", merchantImage102);
                        view.addObject("merchantImage11", merchantImage11);
                    }
                }
            } else {
                appInfo = new UserApp();
                appInfo.setUserId(userId);
            }
            view.addObject("userAppInfo", appInfo);
            QueryWrapper<MerchantPlugin> queryWrapper = new QueryWrapper<MerchantPlugin>().eq("userId", userId);
            int count = merchantPluginService.count(queryWrapper);
            view.addObject("count", count);
        } else {
            view.addObject("userAppInfo", new UserApp());
        }
        getProvince();
        return view;
    }

    /**
     * 获取所有省
     */
    private void getProvince() {
        QueryWrapper<AreaCity> queryWrapper = new QueryWrapper<AreaCity>().eq("type", "1");
        List<AreaCity> areaCitiesList = areaCityMapper.selectList(queryWrapper);
        for (AreaCity areaCity : areaCitiesList) {
            switch (areaCity.getAreaName()) {
                case "北京":
                    areaCity.setAreaName("北京市");
                    break;
                case "天津":
                    areaCity.setAreaName("天津市");
                    break;
                case "重庆":
                    areaCity.setAreaName("重庆市");
                    break;
                case "上海":
                    areaCity.setAreaName("上海市");
                    break;
                default:
                    break;
            }
        }

        request.setAttribute("areaCitiesList", areaCitiesList);
    }

    /**
     * 获取所在省的所有市/获取所在市的所有区
     */
    @GetMapping(value = "/getDowntownByCode/{areaCode}")
    @ResponseBody
    public Map<String, Object> getDowntown(@PathVariable(value = "areaCode") String areaCode) {
        QueryWrapper<AreaCity> queryWrapper = new QueryWrapper<AreaCity>().eq("parentAreaCode", areaCode);
        List<AreaCity> areaCityList = areaCityMapper.selectList(queryWrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("areaCityList", areaCityList);
        result.put("code", 200);
        return result;
    }

    /**
     * 获取所在省的所有市/获取所在市的所有区
     */
    @GetMapping(value = "/getDowntownByName/city/{areaName}")
    @ResponseBody
    public Map<String, Object> getDowntown2(@PathVariable(value = "areaName") String areaName) {
        LambdaQueryWrapper<AreaCity> qWrapper = new LambdaQueryWrapper<AreaCity>().eq(AreaCity::getAreaName, areaName);
        AreaCity entity = areaCityMapper.selectOne(qWrapper);

        if (areaName.equals("北京市") || areaName.equals("上海市") || areaName.equals("天津市") || areaName.equals("重庆市")) {
            Map<String, Object> result = new HashMap<>();
            result.put("areaCityList", Arrays.asList(entity));
            result.put("code", 200);
            return result;
        }
        
        QueryWrapper<AreaCity> queryWrapper = new QueryWrapper<AreaCity>().eq("parentAreaCode", entity.getAreaCode());
        List<AreaCity> areaCityList = areaCityMapper.selectList(queryWrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("areaCityList", areaCityList);
        result.put("code", 200);
        return result;
    }

    /**
     * 获取所在省的所有市/获取所在市的所有区
     */
    @GetMapping(value = "/getDowntownByName/area/{areaName}")
    @ResponseBody
    public Map<String, Object> getDowntown3(@PathVariable(value = "areaName") String areaName) {
        LambdaQueryWrapper<AreaCity> qWrapper = new LambdaQueryWrapper<AreaCity>().eq(AreaCity::getAreaName, areaName);
        AreaCity entity = areaCityMapper.selectOne(qWrapper);
        QueryWrapper<AreaCity> queryWrapper = new QueryWrapper<AreaCity>().eq("parentAreaCode", entity.getAreaCode());
        List<AreaCity> areaCityList = areaCityMapper.selectList(queryWrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("areaCityList", areaCityList);
        result.put("code", 200);
        return result;
    }

    /**
     * 获取对应的银行
     */
    @GetMapping(value = "/getBranchList")
    @ResponseBody
    public Map<String, Object> getBranchList(String bankName, String cityName) {
        if ("浦发银行".equals(bankName)) {
            bankName = "上海浦东发展银行";
        }
        QueryWrapper<BankCodeSxf> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("city_name", cityName);
        if (!"其他银行".equals(bankName)) {
            queryWrapper.likeLeft("bank_name", bankName);
        }

        List<BankCodeSxf> data = bankCodeSxfMapper.selectList(queryWrapper);

        Map<String, Object> result = new HashMap<>(8);
        result.put("branchList", data);
        result.put("code", 200);
        return result;
    }

    /**
     * 保存对象
     */
    @PostMapping("/saveUserApp")
    @ResponseBody
    public Map<String, Object> saveUserApp(UserApp userApp) {
        uaService.saveOrUpdate(userApp);
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "1");
        result.put("resultMessage", "保存成功!");
        return result;
    }

    /**
     * 修改推广员基本信息
     */
    @PostMapping("/updatePromoterInformation")
    @Transactional
    @ResponseBody
    public Result<UserApp> updatePromoterInformation(UserApp userApp) {
        if (userApp == null) {
            return ResultGenerator.genFailResult("缺少参数", null);
        }
        //修改推广员名称和登录账号
        UserApp appUser = new UserApp();
        UserInfo userInfo = new UserInfo();
        userInfo.setLoginName(userApp.getLoginName());
        userInfo.setPhone(userApp.getLoginName());
        userInfo.setTrueName(userApp.getUserName());
        appUser.setLoginName(userApp.getLoginName());
        appUser.setUserName(userApp.getUserName());
        UpdateWrapper<UserApp> userAppUpdateWrapper = new UpdateWrapper<UserApp>().eq("userId", userApp.getUserId());
        uaService.update(appUser, userAppUpdateWrapper);
        UpdateWrapper<UserInfo> userInfoUpdateWrapper = new UpdateWrapper<UserInfo>().eq("id", userApp.getUserId());
        uiService.update(userInfo, userInfoUpdateWrapper);


        if (Objects.equals(userApp.getStatus(), 3)) {
            //保存实名认证的其他信息
            UpdateWrapper<BankCard> bankCardUpdateWrapper = new UpdateWrapper<BankCard>().eq("userId", userApp.getUserId());
            //判断实名人与结算人是否为同一人
            AccountDTO accountDTO = accountService.getRealAccount(userApp.getBankCard().getUserId());
            if (accountDTO == null || accountDTO.getIdcard() == null || !userApp.getIdCard().getCertNo().equals(accountDTO.getIdcard().getCertNo())) {
                bankCardUpdateWrapper.eq("accountType", BankCard.ACCOUNT_TYPE_CERT);
            }
            if ("".equals(userApp.getBankCard().getImgUrl())) {
                userApp.getBankCard().setImgUrl(null);
            }
            QueryWrapper<AreaCity> areaCityQueryWrapper = new QueryWrapper<AreaCity>().
                    in("areaCode", userApp.getBankCard().getBranchProvince(),
                            userApp.getBankCard().getBranchCity(), userApp.getBankCard().getBranchArea());
            List<AreaCity> areaCityList = areaCityMapper.selectList(areaCityQueryWrapper);
            for (AreaCity areaCity : areaCityList) {
                if ("1".equals(areaCity.getType())) {
                    userApp.getBankCard().setBranchProvince(areaCity.getAreaName());
                } else if ("2".equals(areaCity.getType())) {
                    userApp.getBankCard().setBranchCity(areaCity.getAreaName());
                } else if ("3".equals(areaCity.getType()) || "4".equals(areaCity.getType())) {
                    userApp.getBankCard().setBranchArea(areaCity.getAreaName());
                }
            }
            LambdaQueryWrapper<BankCodeSxf> sxfQueryWrapper = new LambdaQueryWrapper<BankCodeSxf>()
                    .eq(StringUtils.isNotEmpty(userApp.getBankCard().getContactLine()), BankCodeSxf::getCnapsCode, userApp.getBankCard().getContactLine())
                    .eq(StringUtils.isNotEmpty(userApp.getBankCard().getBranchName()), BankCodeSxf::getCnapsName, userApp.getBankCard().getBranchName())
                    .last("limit 1");
            BankCodeSxf bankCodeSxf = bankCodeSxfMapper.selectOne(sxfQueryWrapper);
            if (bankCodeSxf == null) {
                throw new MsgException("未找到支行信息");
            }
            userApp.getBankCard().setContactLine(bankCodeSxf.getCnapsCode());
            bankCardService.update(userApp.getBankCard(), bankCardUpdateWrapper);
            UpdateWrapper<IdCard> idCardUpdateWrapper = new UpdateWrapper<IdCard>().eq("userId", userApp.getUserId()).eq("userType", IdCard.TYPE_CERT);
            if ("".equals(userApp.getIdCard().getImgPositive())) {
                userApp.getIdCard().setImgPositive(null);
            }
            if ("".equals(userApp.getIdCard().getImgNegative())) {
                userApp.getIdCard().setImgNegative(null);
            }
            idCardService.update(userApp.getIdCard(), idCardUpdateWrapper);
        }
        return ResultGenerator.genSuccessResult("保存成功！", null);
    }

    /**
     * 修改商户信息
     */
    @PostMapping("/updateMerchantInformation")
    @ResponseBody
    public Result<UserApp> updateMerchantInformation(UserApp userApp, MerchantImage merchantImage) {
        if (userApp.getMerchantBaseInfo() != null) {
            QueryWrapper<AreaCity> areaCityQueryWrapper = new QueryWrapper<AreaCity>().
                    in("areaCode", userApp.getMerchantBaseInfo().getProvince(),
                            userApp.getMerchantBaseInfo().getCity(), userApp.getMerchantBaseInfo().getDistrict());
            List<AreaCity> areaCityList = areaCityMapper.selectList(areaCityQueryWrapper);
            for (AreaCity areaCity : areaCityList) {
                if ("1".equals(areaCity.getType())) {
                    userApp.getMerchantBaseInfo().setProvince(areaCity.getAreaName());
                } else if ("2".equals(areaCity.getType())) {
                    userApp.getMerchantBaseInfo().setCity(areaCity.getAreaName());
                } else if ("3".equals(areaCity.getType()) || "4".equals(areaCity.getType())) {
                    userApp.getMerchantBaseInfo().setDistrict(areaCity.getAreaName());
                }
            }
            UpdateWrapper<MerchantBaseInfo> merchantBaseInfoUpdateWrapper = new UpdateWrapper<MerchantBaseInfo>().eq("userId", userApp.getUserId());
            mbiService.update(userApp.getMerchantBaseInfo(), merchantBaseInfoUpdateWrapper);
        }


        if (userApp.getMerchantCode() != null) {
            UpdateWrapper<MerchantImage> merchantImageUpdateWrapper;
            if (!"".equals(merchantImage.getPicUrl6())) {
                merchantImage.setPicUrl(merchantImage.getPicUrl6());
                merchantImage.setPhotoType(MerchantImage.ImageType.SHOP_FRONT_DOOR);
                merchantImageUpdateWrapper = new UpdateWrapper<MerchantImage>()
                        .eq("merchantCode", userApp.getMerchantCode()).eq("photoType", merchantImage.getPhotoType());
                merchantImageService.saveOrUpdate(merchantImage, merchantImageUpdateWrapper);
            }

            if (!"".equals(merchantImage.getPicUrl8())) {
                merchantImage.setPicUrl(merchantImage.getPicUrl8());
                merchantImage.setPhotoType(MerchantImage.ImageType.CASH_DESK_PHOTO);
                merchantImageUpdateWrapper = new UpdateWrapper<MerchantImage>()
                        .eq("merchantCode", userApp.getMerchantCode()).eq("photoType", merchantImage.getPhotoType());
                merchantImageService.saveOrUpdate(merchantImage, merchantImageUpdateWrapper);
            }
            if (!"".equals(merchantImage.getPicUrl9())) {
                merchantImage.setPicUrl(merchantImage.getPicUrl9());
                merchantImage.setPhotoType(MerchantImage.ImageType.STORE_INTERIOR_PHOTO);
                merchantImageUpdateWrapper = new UpdateWrapper<MerchantImage>()
                        .eq("merchantCode", userApp.getMerchantCode()).eq("photoType", merchantImage.getPhotoType());
                merchantImageService.saveOrUpdate(merchantImage, merchantImageUpdateWrapper);
            }

            if (!"".equals(merchantImage.getPicUrl101())) {
                merchantImage.setPicUrl(merchantImage.getPicUrl101());
                merchantImage.setPhotoType(MerchantImage.ImageType.MERCHANT_PROTOCOL);
                merchantImageUpdateWrapper = new UpdateWrapper<MerchantImage>()
                        .eq("merchantCode", userApp.getMerchantCode()).eq("photoType", merchantImage.getPhotoType());
                merchantImageService.saveOrUpdate(merchantImage, merchantImageUpdateWrapper);
            }

            if (!"".equals(merchantImage.getPicUrl102())) {
                merchantImage.setPicUrl(merchantImage.getPicUrl102());
                merchantImage.setPhotoType(MerchantImage.ImageType.MERCHANT_SUB_PROTOCOL);
                merchantImageUpdateWrapper = new UpdateWrapper<MerchantImage>()
                        .eq("merchantCode", userApp.getMerchantCode()).eq("photoType", merchantImage.getPhotoType());
                merchantImageService.saveOrUpdate(merchantImage, merchantImageUpdateWrapper);
            }
        }
        return ResultGenerator.genSuccessResult("保存成功！", null);
    }

    /**
     * 修改营业执照信息
     */
    @PostMapping("/updateMerchantLicense")
    @Transactional
    @ResponseBody
    public Result<UserApp> updateMerchantLicense(UserApp userApp, MerchantImage merchantImage, String certNo,
                                                 String certName, String certStartTime, String certEndTime) {
        if (userApp.getMerchantBaseInfo() != null) {
            UpdateWrapper<MerchantBaseInfo> merchantBaseInfoUpdateWrapper = new UpdateWrapper<MerchantBaseInfo>().eq("userId", userApp.getUserId());
            mbiService.update(userApp.getMerchantBaseInfo(), merchantBaseInfoUpdateWrapper);
        }
        //更改法人身份证号
        if (StringUtils.isNotEmpty(certNo) && StringUtils.isNotEmpty(certName)) {
            IdCard idCard = new IdCard();
            idCard.setCertNo(certNo);
            idCard.setImgPositive(merchantImage.getPicUrl1());
            idCard.setImgNegative(merchantImage.getPicUrl2());
            idCard.setCertStartTime(certStartTime);
            idCard.setCertEndTime(certEndTime);
            UpdateWrapper<IdCard> cardUpdateWrapper = new UpdateWrapper<IdCard>()
                    .eq("certName", certName).eq("userId", userApp.getUserId()).eq("userType", IdCard.TYPE_LEGAL);
            boolean update = idCardService.update(idCard, cardUpdateWrapper);
            if (!update) {
                idCard.setUserType(IdCard.TYPE_LEGAL);
                idCard.setUserId(userApp.getUserId() + "");
                idCard.setCertType("00");
                idCard.setCertName(certName);
                idCardService.save(idCard);
            }
        }
        if (userApp.getMerchantCode() != null) {
            if (!"".equals(merchantImage.getPicUrl3())) {
                merchantImage.setPicUrl(merchantImage.getPicUrl3());
                merchantImage.setPhotoType(MerchantImage.ImageType.BUSINESS_LICENSE);

                UpdateWrapper<MerchantImage> merchantImageUpdateWrapper = new UpdateWrapper<MerchantImage>()
                        .eq("merchantCode", userApp.getMerchantCode()).eq("photoType", merchantImage.getPhotoType());
                merchantImageService.update(merchantImage, merchantImageUpdateWrapper);
            }

            if (!"".equals(merchantImage.getPicUrl1())) {
                merchantImage.setPicUrl(merchantImage.getPicUrl1());
                merchantImage.setPhotoType(MerchantImage.ImageType.IDCARD_FRONT);

                UpdateWrapper<MerchantImage> merchantImageUpdateWrapper = new UpdateWrapper<MerchantImage>()
                        .eq("merchantCode", userApp.getMerchantCode()).eq("photoType", merchantImage.getPhotoType());
                merchantImageService.update(merchantImage, merchantImageUpdateWrapper);
            }

            if (!"".equals(merchantImage.getPicUrl2())) {
                merchantImage.setPicUrl(merchantImage.getPicUrl2());
                merchantImage.setPhotoType(MerchantImage.ImageType.IDCARD_BACK);

                UpdateWrapper<MerchantImage> merchantImageUpdateWrapper = new UpdateWrapper<MerchantImage>()
                        .eq("merchantCode", userApp.getMerchantCode()).eq("photoType", merchantImage.getPhotoType());
                merchantImageService.update(merchantImage, merchantImageUpdateWrapper);
            }
        }
        return ResultGenerator.genSuccessResult("保存成功！", null);
    }

    /**
     * 修改结算信息
     */
    @PostMapping("/updateMerchantSettlement")
    @Transactional
    @ResponseBody
    public Result<UserApp> updateMerchantSettlement(UserApp userApp, MerchantImage merchantImage) {
        if (userApp.getBankCard() != null) {
            LambdaQueryWrapper<BankCodeSxf> qWrapper = new LambdaQueryWrapper<BankCodeSxf>()
                    .eq(BankCodeSxf::getCnapsCode, userApp.getBankCard().getContactLine());
            BankCodeSxf bankCodeSxf = bankCodeSxfMapper.selectOne(qWrapper);
            userApp.getBankCard().setBranchName(bankCodeSxf.getCnapsName());
            // 这里获取结算账户的类型
            AccountDTO realAccount = accountService.getRealAccount(userApp.getIdCard().getUserId());
            BankCard existBankCard = realAccount.getBankCard();
            BankCard editBankCard = userApp.getBankCard();
            editBankCard.setAccountType(existBankCard.getAccountType());
            bankCardService.saveOrUpdate(editBankCard);
        }
        if (userApp.getIdCard() != null) {
            idCardService.saveOrUpdate(userApp.getIdCard());
        }
        if (userApp.getMerchantCode() != null) {
            //修改结算人与收银台合照
            if (!"".equals(merchantImage.getPicUrl999())) {
                merchantImage.setPicUrl(merchantImage.getPicUrl999());
                merchantImage.setPhotoType(MerchantImage.ImageType.CASH_DESK_WITH_PERSON);

                UpdateWrapper<MerchantImage> merchantImageUpdateWrapper = new UpdateWrapper<MerchantImage>()
                        .eq("merchantCode", userApp.getMerchantCode()).eq("photoType", merchantImage.getPhotoType());
                boolean update = merchantImageService.update(merchantImage, merchantImageUpdateWrapper);
                if (!update) {
                    merchantImage.setMerchantCode(userApp.getMerchantCode());
                    merchantImageService.save(merchantImage);
                }
            }
            //修改结算人手持身份证照
            if (!"".equals(merchantImage.getPicUrl11())) {
                merchantImage.setPicUrl(merchantImage.getPicUrl11());
                merchantImage.setPhotoType(MerchantImage.ImageType.HAND_IDCARD_PHOTO);


                UpdateWrapper<MerchantImage> merchantImageUpdateWrapper = new UpdateWrapper<MerchantImage>()
                        .eq("merchantCode", userApp.getMerchantCode()).eq("photoType", merchantImage.getPhotoType());
                boolean update = merchantImageService.update(merchantImage, merchantImageUpdateWrapper);
                if (!update) {
                    merchantImage.setMerchantCode(userApp.getMerchantCode());
                    merchantImageService.save(merchantImage);
                }
            }
        }
        return ResultGenerator.genSuccessResult("保存成功！", null);
    }

    /**
     * 修改结算信息
     */
    @PostMapping("/updateMerchantSettlement2")
    @Transactional
    @ResponseBody
    public Result<UserApp> updateMerchantSettlement2(AccountDTO accountDTO, MerchantImage merchantImage) {
        if (accountDTO != null && accountDTO.getUserId() != null) {
            accountService.saveV4(accountDTO, false);
        }

        // System.out.println(JSON.toJSONString(accountDTO));
//        BankCard editBankCard = accountDTO.getBankCard();
//        if (editBankCard != null) {
//            MsgException.checkNull(editBankCard.getId(), "无结算银行卡信息，请先从通过app填写结算信息!");
//
//            LambdaQueryWrapper<BankCodeSxf> qWrapper = new LambdaQueryWrapper<BankCodeSxf>()
//                    .eq(BankCodeSxf::getCnapsCode, editBankCard.getContactLine());
//            BankCodeSxf bankCodeSxf = bankCodeSxfMapper.selectOne(qWrapper);
//            editBankCard.setBranchName(bankCodeSxf.getCnapsName());
//
//            bankCardService.updateById(editBankCard);
//        }
//
//        IdCard editIdCard = accountDTO.getIdcard();
//        if (editIdCard != null) {
//            MsgException.checkNull(editBankCard.getId(), "无结算身份证信息，请先从通过app填写结算信息!");
//
//            idCardService.updateById(editIdCard);
//        }

        if (merchantImage.getMerchantCode() != null) {
            //修改结算人与收银台合照
            if (!StringUtils.isEmpty(merchantImage.getPicUrl999())) {
                merchantImage.setPicUrl(merchantImage.getPicUrl999());
                merchantImage.setPhotoType(MerchantImage.ImageType.CASH_DESK_WITH_PERSON);

                UpdateWrapper<MerchantImage> merchantImageUpdateWrapper = new UpdateWrapper<MerchantImage>()
                        .eq("merchantCode", merchantImage.getMerchantCode()).eq("photoType", merchantImage.getPhotoType());
                boolean update = merchantImageService.update(merchantImage, merchantImageUpdateWrapper);
                if (!update) {
                    merchantImage.setMerchantCode(merchantImage.getMerchantCode());
                    merchantImageService.save(merchantImage);
                }
            }
            //修改结算人手持身份证照
            if (!StringUtils.isEmpty(merchantImage.getPicUrl11())) {
                merchantImage.setPicUrl(merchantImage.getPicUrl11());
                merchantImage.setPhotoType(MerchantImage.ImageType.HAND_IDCARD_PHOTO);

                UpdateWrapper<MerchantImage> merchantImageUpdateWrapper = new UpdateWrapper<MerchantImage>()
                        .eq("merchantCode", merchantImage.getMerchantCode()).eq("photoType", merchantImage.getPhotoType());
                boolean update = merchantImageService.update(merchantImage, merchantImageUpdateWrapper);
                if (!update) {
                    merchantImage.setMerchantCode(merchantImage.getMerchantCode());
                    merchantImageService.save(merchantImage);
                }
            }
        }

        // throw new MsgException("终止操作");
        return ResultGenerator.genSuccessResult("保存成功！", null);
    }

    /**
     * 删除对象
     */
    @PostMapping("/deleteUserApp")
    @ResponseBody
    public Map<String, Object> deleteUserApp(Long id) {
        uaService.removeById(id);
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "1");
        result.put("resultMessage", "保存成功!");
        return result;
    }

    /**
     * 审核对象
     */
    @PostMapping("/toExamine")
    @ResponseBody
    public Map<String, Object> toExamine(Long id, Integer status, String certReason) {
        UserApp userApp = new UserApp();
        userApp.setId(id);
        userApp = uaService.queryUserApp(userApp);
        userApp.setStatus(status);
        userApp.setCertReason(certReason);
        uaService.updateById(userApp);
        String statusZh = "审核通过";
        if (status == 2) {
            statusZh = "很遗憾，您的实名认证未通过，" + certReason + "，请您核对信息。";
        }
        List<String> alias = new ArrayList<>();
        alias.add(userApp.getUserId().toString());
        generalPushUtil.sendAllPlatByAlias(alias, "实名认证通知", statusZh, "1");

        Notice notice = new Notice();
        notice.setUserId(userApp.getUserId().toString());
        notice.setUserName(userApp.getUserName());
        notice.setTypeFirst(1);
        notice.setTypeSecond(0);
        notice.setIsDeal(0);
        notice.setConrtent(statusZh);
        notice.setCreateDt(new Date());
        notice.setNoticeCode(UUID.randomUUID().toString().replace("-", ""));
        noticeService.saveNotice(notice);
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "1");
        result.put("resultMessage", "审核成功!");
        return result;
    }

    /**
     * goLevel:(修改等级). <br/>
     *
     * @since JDK 1.8
     */
//    @PostMapping(value = "/goLevel")
//    @ResponseBody
//    public Map<String, Object> goLevel(Long id, Integer level) {
//        Map<String, Object> result = new HashMap<>(16);
//        try {
//            System.out.println("等级：" + level);
//            UserApp userApp = new UserApp();
//            userApp.setLevel(level);
//            userApp.setId(id);
//            uaService.updateById(userApp);
//            result.put("code", "1");
//            result.put("msg", "修改成功");
//            return result;
//        } catch (Exception e) {
//            result.put("code", "0");
//            result.put("msg", "修改失败");
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            e.printStackTrace();
//            return result;
//        }
//    }


    /**
     * goLevel:(修改等级). <br/>
     * @since JDK 1.8
     */
    @PostMapping(value = "/goLevelV2")
    @ResponseBody
    public Result<Object> goLevelV2(Long id, String levelCode) {
        try {
            UserApp userApp = new UserApp();
            userApp.setLevelCode(levelCode);
            userApp.setId(id);
            uaService.updateById(userApp);
            return ResultGenerator.genSuccessResult("操作成功！",null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultGenerator.genFailResult("操作失败！");
        }
    }

    /**
     * 修改图片
     */
    @RequestMapping(value = "/updateImage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateImage(@RequestParam(value = "file") MultipartFile file, String imageType, String merchantCode, String type, String dataId) throws IOException {
        Map<String, Object> result = new HashMap<>(2);
        if (file.getSize() == 0) {
            result.put("code", "0");
            result.put("msg", "上传图片不能为空！");
            return result;
        }
        if (StringUtil.isEmpty(imageType)) {
            result.put("code", "0");
            result.put("msg", "上传图片类型不能为空！");
            return result;
        }
        if (StringUtil.isEmpty(merchantCode)) {
            result.put("code", "0");
            result.put("msg", "商户编号不能为空！");
            return result;
        }

        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        // 保存文件名称
        String fileName = StringUtil.getBillno() + "." + suffix;
        String uploadPath = ParametersUtil.upload_save_path;
        String visitPath = ParametersUtil.upload_visit_path;
        Properties prop = System.getProperties();
        String os = prop.getProperty("os.name");
        if (os.startsWith("win") || os.startsWith("Win")) {
            //D:\work\workspace_java\syb\pluss-manage-page
            uploadPath = "D:/Pictures/";// 测试 // windows目录
        }
        FileInputStream fis = null;
        FileOutputStream fos = null;
        String path = uploadPath + "/" + fileName;
        String code = "1";
        try {
            InputStream ins = file.getInputStream();
            File f = new File(file.getOriginalFilename());
            inputStreamToFile(ins, f);
            fis = new FileInputStream(f);
            fos = new FileOutputStream(path);
            byte[] strByte = new byte[(int) f.length()];
            // 生成文件
            while (fis.read(strByte) != -1) {
                fos.write(strByte);
            }
            fos.flush();
            path = visitPath + "/" + fileName;// 测试
            // 访问路劲
            if (os.startsWith("win") || os.startsWith("Win")) {
                path = "http://192.168.0.184:7004/api/Pictures" + "/" + fileName;// 测试 // windows目录
            } else {
                Runtime.getRuntime().exec("chmod -R 777 /home/syb/resources/");
            }


            if (StringUtils.isNotEmpty(dataId)) {
                MerchantImage image = new MerchantImage();
                image.setMerchantCode(merchantCode);
                if ("settle".equals(type)) {
                    Integer id = Integer.valueOf(dataId);
                    String imgType = null;
                    if ("01".equals(imageType) || "02".equals(imageType)) {
                        IdCard idCard = new IdCard();
                        idCard.setId(id);
                        idCard.setUserType(IdCard.TYPE_ACCOUNT);
                        if ("01".equals(imageType)) {
                            imgType = MerchantImage.ImageType.SETTLE_IDCARD_FRONT;
                            image.setPhotoType(MerchantImage.ImageType.SETTLE_IDCARD_FRONT);
                            idCard.setImgPositive(path);
                        }
                        if ("02".equals(imageType)) {
                            imgType = MerchantImage.ImageType.SETTLE_IDCARD_BACK;
                            image.setPhotoType(MerchantImage.ImageType.SETTLE_IDCARD_BACK);
                            idCard.setImgNegative(path);
                        }
                        idCardService.updateById(idCard);
                    } else if ("03".equals(imageType)) {
                        imgType = MerchantImage.ImageType.BANK_CARD_FRONT;
                        BankCard bankCard = new BankCard().setId(id);
                        bankCard.setImgUrl(path);
                        image.setPhotoType(MerchantImage.ImageType.BANK_CARD_FRONT);
                        bankCardService.updateById(bankCard);
                    }
                    merchantImageService.saveMerchantImageUpload(merchantCode, path, imgType);
                } else if ("auth".equals(type)) {
                    Integer id = Integer.valueOf(dataId);
                    if ("01".equals(imageType) || "02".equals(imageType)) {
                        IdCard idCard = new IdCard();
                        idCard.setId(id);
                        if ("01".equals(imageType)) {
                            image.setPhotoType(MerchantImage.ImageType.IDCARD_FRONT);
                            idCard.setImgPositive(path);
                        }
                        if ("02".equals(imageType)) {
                            image.setPhotoType(MerchantImage.ImageType.IDCARD_BACK);
                            idCard.setImgNegative(path);
                        }
                        idCardService.updateById(idCard);
                    } else if ("04".equals(imageType)) {
                        image.setPhotoType(MerchantImage.ImageType.BANK_CARD_FRONT);
                        BankCard bank = new BankCard().setId(id);
                        bank.setImgUrl(path);
                        bankCardService.updateById(bank);
                    }
                }
                List<MerchantImage> imageList = merchantImageService.queryMerchantImageList(image);
                if (!imageList.isEmpty()) {
                    MerchantImage img = imageList.get(0);
                    img.setPicUrl(path);
                    merchantImageService.updateById(img);
                }
            } else {
                MerchantImage image = new MerchantImage();
                image.setPhotoType(imageType);
                image.setMerchantCode(merchantCode);
                List<MerchantImage> merchantImages = merchantImageService.queryMerchantImageList(image);
                if (merchantImages.isEmpty()) {
                    image.setPicUrl(path);
                    image.setCreateDt(new Date());
                    merchantImageService.save(image);
                } else {
                    MerchantImage imageInfo = merchantImages.get(0);
                    imageInfo.setPicUrl(path);
                    merchantImageService.updateById(imageInfo);
                    merchantImageService.saveMerchantImageUpload(merchantCode, path, imageType);
                }
            }
            code = "1";
        } catch (Exception e) {
            code = "2";
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ignored) {
                }
            }
            if (fis != null) {
                fis.close();
            }
        }
        // 返回保存结果
        result.put("code", code);
        result.put("url", path);
        result.put("fileName", fileName);
        return result;
    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 实名认证信息页面
     *
     * @param userId
     * @return
     */
    @GetMapping("/connectInfo")
    public String connectInfo(HttpServletRequest request, String userId) {
        request.setAttribute("userId", userId);

        // 实名身份证相关的结算信息条数
        IdCard certIdCard = idCardService.getCertIdCard(userId);
        if (certIdCard != null) {
            int countCert = accountMapper.selectAccountNum(Collections.singletonList(certIdCard.getCertNo()));
            request.setAttribute("countCert", countCert);
        } else {
            request.setAttribute("countCert", 0);
        }

        // 结算身份证相关的结算信息条数
        List<IdCard> accountIdCardList = idCardService.getAccountIdCard(userId);
        if (!accountIdCardList.isEmpty()) {
            List<String> certNoList = accountIdCardList.stream().map(IdCard::getCertNo)
                    .distinct().collect(Collectors.toList());
            int countAccount = accountMapper.selectAccountNum(certNoList);
            request.setAttribute("countAccount", countAccount);
        } else {
            request.setAttribute("countAccount", 0);
        }

        MerchantBaseInfo mbi = mbiService.getMerchantBaseInfoByUserId(userId);

        if (mbi == null) {
            request.setAttribute("countMbiName", 0);
        } else {
            LambdaQueryWrapper<MerchantBaseInfo> qWrapper = Wrappers.lambdaQuery();
            qWrapper.eq(MerchantBaseInfo::getAlias, mbi.getAlias())
                    .or()
                    .eq(MerchantBaseInfo::getMerchantName, mbi.getMerchantName());
            int countMbiName = mbiService.count(qWrapper);
            request.setAttribute("countMbiName", countMbiName);
        }

        return "promoter/userAppConnectInfo";
    }

    @GetMapping("/userIpPage")
    @ResponseBody
    public Result<Object> userIpPageInfo(Page<OperationRecordVO> page, String userId) {
        page = oprMapper.selectUserSameIpCountPage(page, userId);
        return ResultGenerator.genSuccessResult(page);
    }
}
