package com.chaozhanggui.admin.system.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chaozhanggui.common.system.config.MsgException;
import com.chaozhanggui.common.system.config.RespBody;
import com.chaozhanggui.dao.system.dao.*;
import com.chaozhanggui.dao.system.entity.*;
import com.chaozhanggui.dao.system.entity.DTO.AccountDTO;
import com.chaozhanggui.dao.system.entity.VO.AccountVO;
import com.chaozhanggui.dao.system.entity.VO.MerchantBaseVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import static com.chaozhanggui.dao.system.entity.TbPlussAccount.CHANNEL_TYPE_D0;
import static com.chaozhanggui.dao.system.entity.TbPlussAccount.CHANNEL_TYPE_D1;
import static com.chaozhanggui.dao.system.entity.TbPlussBankCard.ACCOUNT_TYPE_CERT;
import static com.chaozhanggui.dao.system.entity.TbPlussIdCard.TYPE_CERT;

/**
 * @author lyf
 */
@Service
@Transactional
public class MerchantInfoService {
    @Resource
    private TbPlussIdCardMapper idCardMapper;
    @Resource
    private TbPlussBankCardMapper bankCardMapper;
    @Resource
    private TbPlussMerchantBaseInfoMapper merchantBaseInfoMapper;
    @Resource
    private TbPlussMerchantImageMapper merchantImageMapper;
    @Resource
    private TbPlussAccountMapper accountMapper;
    @Resource
    private TbPlussMerchantChannelMapper merchantChannelMapper;
    @Resource
    private TbPlussUserInfoMapper userInfoMapper;
    @Resource
    private TbPlussUserAppMapper userAppMapper;
    @Resource
    private AccountService accountService;
    @Resource
    private TbPlussAreaCityMapper areaCityMapper;
    @Resource
    private TbPlussBankCodeSxfMapper bankCodeSxfMapper;



    public RespBody merchantReal(Integer userId){
        HashMap<String, Object> map = new HashMap<>();
        //身份证
        TbPlussIdCard idCard = idCardMapper.selectCertByUserId(userId,TYPE_CERT);
        //银行卡
        TbPlussBankCard bankCard = bankCardMapper.selectByUserIdCert(userId, ACCOUNT_TYPE_CERT);
        TbPlussUserApp tbPlussUserApp = userAppMapper.selectByUserId(userId);
        map.put("status",tbPlussUserApp.getStatus());
        map.put("id",tbPlussUserApp.getId());
        map.put("idCard",idCard);
        map.put("bankCard",bankCard);
        return new RespBody("000000",map);
    }

    public RespBody merchantBaseInfo(Integer userId){
        MerchantBaseVO merchantBaseVO = new MerchantBaseVO();
        //商户基础信息相关
        TbPlussMerchantBaseInfo merchantBaseInfo = merchantBaseInfoMapper.selectByUserId(userId.toString());
        if (merchantBaseInfo == null){
            return new RespBody("000000",merchantBaseVO);
        }
        merchantBaseVO.setMerchantBaseInfo(merchantBaseInfo);
        //图片
        List<TbPlussMerchantImage> merchantImages = merchantImageMapper.selectByMerchantCode(merchantBaseInfo.getMerchantcode());
        if (merchantImages == null){
            return new RespBody("000000",merchantBaseVO);
        }
        merchantBaseVO.setMerchantImagesList(merchantImages);

        return new RespBody("000000",merchantBaseVO);
    }

    public RespBody merchantAccount(Integer userId){
        HashMap<String, Object> realAccount = getRealAccount(userId);
        return new RespBody("000000",realAccount);
    }

    public HashMap<String,Object> getRealAccount(Integer userId) {
        HashMap<String, Object> map = new HashMap<>();
        //D1
        TbPlussAccount accountD1 = accountMapper.selectByUser(userId, CHANNEL_TYPE_D1);
        if (accountD1 == null){
            map.put("D1",new AccountVO());
        }else {
            AccountVO accountVO = new AccountVO();
            // 获取身份证信息
            TbPlussIdCard idCard = idCardMapper.selectByPrimaryKey(Integer.valueOf(accountD1.getIdcardid()));
            accountVO.setIdCard(idCard);
            // 获取银行卡信息
            TbPlussBankCard bankCard = bankCardMapper.selectByPrimaryKey(Integer.valueOf(accountD1.getBankcardid()));
            accountVO.setBankCard(bankCard);
            map.put("D1",accountVO);
        }
        //D0
        TbPlussAccount accountD0 = accountMapper.selectByUser(userId, CHANNEL_TYPE_D0);
        if (accountD0 == null){
            map.put("D0",new AccountVO());
        }else {
            AccountVO accountVO = new AccountVO();
            // 获取身份证信息
            TbPlussIdCard idCard = idCardMapper.selectByPrimaryKey(Integer.valueOf(accountD0.getIdcardid()));
            accountVO.setIdCard(idCard);
            // 获取银行卡信息
            TbPlussBankCard bankCard = bankCardMapper.selectByPrimaryKey(Integer.valueOf(accountD0.getBankcardid()));
            accountVO.setBankCard(bankCard);
            map.put("D0",accountVO);
        }
        return map;
    }
    @Transactional(rollbackFor = Exception.class)
    public RespBody updatePromoterInformation(TbPlussUserApp userApp){
        if (Objects.equals(userApp.getStatus(), 3)) {
            //保存实名认证的其他信息
            UpdateWrapper<TbPlussBankCard> bankCardUpdateWrapper = new UpdateWrapper<TbPlussBankCard>().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", TbPlussBankCard.ACCOUNT_TYPE_CERT);
            }
            if ("".equals(userApp.getBankCard().getImgurl())) {
                userApp.getBankCard().setImgurl(null);
            }
            QueryWrapper<TbPlussAreaCity> areaCityQueryWrapper = new QueryWrapper<TbPlussAreaCity>().
                    in("areaCode", userApp.getBankCard().getBranchprovince(),
                            userApp.getBankCard().getBranchcity(), userApp.getBankCard().getBrancharea());
            List<TbPlussAreaCity> areaCityList = areaCityMapper.selectList(areaCityQueryWrapper);
            for (TbPlussAreaCity 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<TbPlussBankCodeSxf> sxfQueryWrapper = new LambdaQueryWrapper<TbPlussBankCodeSxf>()
                    .eq(StringUtils.isNotEmpty(userApp.getBankCard().getContactline()), TbPlussBankCodeSxf::getCnapsCode, userApp.getBankCard().getContactline())
                    .eq(StringUtils.isNotEmpty(userApp.getBankCard().getBranchname()), TbPlussBankCodeSxf::getCnapsName, userApp.getBankCard().getBranchname())
                    .last("limit 1");
            TbPlussBankCodeSxf bankCodeSxf = bankCodeSxfMapper.selectOne(sxfQueryWrapper);
            if (bankCodeSxf == null) {
                return new RespBody("000072");
            }
            userApp.getBankCard().setContactline(bankCodeSxf.getCnapsCode());
            bankCardMapper.updateByPrimaryKeySelective(userApp.getBankCard());
            UpdateWrapper<TbPlussIdCard> idCardUpdateWrapper = new UpdateWrapper<TbPlussIdCard>().eq("userId", userApp.getUserid()).eq("userType", TbPlussIdCard.TYPE_CERT);
            if ("".equals(userApp.getIdCard().getImgpositive())) {
                userApp.getIdCard().setImgpositive(null);
            }
            if ("".equals(userApp.getIdCard().getImgnegative())) {
                userApp.getIdCard().setImgnegative(null);
            }
            userApp.getIdCard().setVirtypeflag("");
            idCardMapper.updateByPrimaryKeySelective(userApp.getIdCard());
        }
        //修改推广员名称和登录账号
        TbPlussUserApp appUser = userAppMapper.selectByUserId(userApp.getUserid());

        TbPlussUserInfo userInfo = userInfoMapper.selectByPrimaryKey(userApp.getUserid().longValue());
        if(ObjectUtil.isEmpty(appUser)||ObjectUtil.isEmpty(userInfo)){
            return new RespBody("000001");
        }

        userInfo.setLoginname(userApp.getLoginname());
        userInfo.setPhone(userApp.getLoginname());
        userInfo.setTruename(userApp.getUsername());
        userInfo.setId(Long.valueOf(userApp.getUserid()));
        appUser.setLoginname(userApp.getLoginname());
        appUser.setUsername(userApp.getUsername());
        appUser.setUserid(userApp.getUserid());
//        userAppMapper.updateByPrimaryKey(appUser);
//        userInfoMapper.updateByPrimaryKey(userInfo);
        return new RespBody("000000");
    }

    public RespBody updateIdCard(TbPlussIdCard idCard){
        int i = idCardMapper.updateByPrimaryKeySelective(idCard);
        if (i > 0) {
            return new RespBody("000000");
        }
        return new RespBody("999943");
    }
    public RespBody updateBankCard(TbPlussBankCard bankCard){
        int i = bankCardMapper.updateByPrimaryKeySelective(bankCard);
        if (i > 0) {
            return new RespBody("000000");
        }
        return new RespBody("999943");
    }
    @Transactional(rollbackFor = Exception.class)
    public RespBody updateMerchantInformation(TbPlussMerchantBaseInfo merchantBaseInfo){
        if (merchantBaseInfo != null) {
            QueryWrapper<TbPlussAreaCity> areaCityQueryWrapper = new QueryWrapper<TbPlussAreaCity>().
                    in("areaCode", merchantBaseInfo.getProvince(),
                            merchantBaseInfo.getCity(), merchantBaseInfo.getDistrict());
            List<TbPlussAreaCity> areaCityList = areaCityMapper.selectList(areaCityQueryWrapper);
            for (TbPlussAreaCity areaCity : areaCityList) {
                if ("1".equals(areaCity.getType())) {
                    merchantBaseInfo.setProvince(areaCity.getAreaname());
                } else if ("2".equals(areaCity.getType())) {
                    merchantBaseInfo.setCity(areaCity.getAreaname());
                } else if ("3".equals(areaCity.getType()) || "4".equals(areaCity.getType())) {
                    merchantBaseInfo.setDistrict(areaCity.getAreaname());
                }
            }
//            UpdateWrapper<TbPlussMerchantBaseInfo> merchantBaseInfoUpdateWrapper = new UpdateWrapper<TbPlussMerchantBaseInfo>()
//                    .eq("userId", userApp.getUserid());
//            merchantChannelMapper.update(userApp.getMerchantBaseInfo(), merchantBaseInfoUpdateWrapper);
            merchantBaseInfoMapper.updateByPrimaryKeySelective(merchantBaseInfo);
        }
        if (merchantBaseInfo.getMerchantcode() != null) {
            if (!"".equals(merchantBaseInfo.getPicUrl6())) {
                TbPlussMerchantImage merchantImage = new TbPlussMerchantImage();
                merchantImage.setPicurl(merchantBaseInfo.getPicUrl6());
                merchantImage.setPhotoType(TbPlussMerchantImage.SHOP_FRONT_DOOR);
                merchantImage.setMerchantcode(merchantBaseInfo.getMerchantcode());
                merchantImageMapper.updateByCodeAndType(merchantImage);
            }

            if (!"".equals(merchantBaseInfo.getPicUrl8())) {
                TbPlussMerchantImage merchantImage = new TbPlussMerchantImage();
                merchantImage.setPicurl(merchantBaseInfo.getPicUrl8());
                merchantImage.setPhotoType(TbPlussMerchantImage.CASH_DESK_PHOTO);
                merchantImage.setMerchantcode(merchantBaseInfo.getMerchantcode());
                merchantImageMapper.updateByCodeAndType(merchantImage);
            }
            if (!"".equals(merchantBaseInfo.getPicUrl9())) {
                TbPlussMerchantImage merchantImage = new TbPlussMerchantImage();
                merchantImage.setPicurl(merchantBaseInfo.getPicUrl9());
                merchantImage.setPhotoType(TbPlussMerchantImage.STORE_INTERIOR_PHOTO);
                merchantImage.setMerchantcode(merchantBaseInfo.getMerchantcode());
                merchantImageMapper.updateByCodeAndType(merchantImage);
            }

            if (!"".equals(merchantBaseInfo.getPicUrl101())) {
                TbPlussMerchantImage merchantImage = new TbPlussMerchantImage();
                merchantImage.setPicurl(merchantBaseInfo.getPicUrl101());
                merchantImage.setPhotoType(TbPlussMerchantImage.MERCHANT_PROTOCOL);
                merchantImage.setMerchantcode(merchantBaseInfo.getMerchantcode());
                merchantImageMapper.updateByCodeAndType(merchantImage);
            }

            if (!"".equals(merchantBaseInfo.getPicUrl102())) {
                TbPlussMerchantImage merchantImage = new TbPlussMerchantImage();
                merchantImage.setPicurl(merchantBaseInfo.getPicUrl102());
                merchantImage.setPhotoType(TbPlussMerchantImage.MERCHANT_SUB_PROTOCOL);
                merchantImage.setMerchantcode(merchantBaseInfo.getMerchantcode());
                merchantImageMapper.updateByCodeAndType(merchantImage);
            }
        }
        return new RespBody("000000");
    }

}
