package cn.newfeifan.mall.sale.service.merchantapply;

import cn.newfeifan.mall.module.enums.MerchantApplyCheckStatusEnum;
import cn.newfeifan.mall.module.enums.MerchantStatusEnum;
import cn.newfeifan.mall.module.member.dal.dataobject.user.MemberUserDO;
import cn.newfeifan.mall.module.member.service.user.MemberUserService;
import cn.newfeifan.mall.sale.controller.admin.merchant.vo.MerchantSaveReqVO;
import cn.newfeifan.mall.sale.controller.admin.merchantapply.vo.MerchantApplyPageReqVO;
import cn.newfeifan.mall.sale.controller.admin.merchantapply.vo.MerchantApplySaveReqVO;
import cn.newfeifan.mall.sale.controller.admin.merchantapplylog.vo.MerchantApplyLogSaveReqVO;
import cn.newfeifan.mall.sale.controller.admin.shop.vo.ShopRespVO;
import cn.newfeifan.mall.sale.controller.admin.shop.vo.ShopSaveReqVO;
import cn.newfeifan.mall.sale.dal.dataobject.merchant.MerchantDO;
import cn.newfeifan.mall.sale.service.merchant.MerchantService;
import cn.newfeifan.mall.sale.service.merchantapplylog.MerchantApplyLogService;
import cn.newfeifan.mall.sale.service.shop.ShopService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import cn.newfeifan.mall.sale.dal.dataobject.merchantapply.MerchantApplyDO;
import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.util.object.BeanUtils;

import cn.newfeifan.mall.sale.dal.mysql.merchantapply.MerchantApplyMapper;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.newfeifan.mall.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.newfeifan.mall.module.enums.ErrorCodeConstants.MERCHANT_APPLY_NOT_EXISTS;

/**
 * 商户申请 Service 实现类
 *
 * @author 非繁人
 */
@Service
@Validated
public class MerchantApplyServiceImpl implements MerchantApplyService {

    @Resource
    private MerchantApplyMapper merchantApplyMapper;

    @Resource
    @Lazy
    private MerchantApplyLogService merchantApplyLogService;

    @Resource
    private MerchantService merchantService;

    @Resource
    private ShopService shopService;

    @Resource
    private MemberUserService memberUserService;

    @Override
    public Long createMerchantApply(MerchantApplySaveReqVO createReqVO) {
        // 插入
        MerchantApplyDO merchantApply = BeanUtils.toBean(createReqVO, MerchantApplyDO.class);
        merchantApplyMapper.insert(merchantApply);
        // 返回
        return merchantApply.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMerchantApply(MerchantApplySaveReqVO updateReqVO) {
        // 校验存在
        validateMerchantApplyExists(updateReqVO.getId());
        // 更新
        MerchantApplyDO updateObj = BeanUtils.toBean(updateReqVO, MerchantApplyDO.class);
        updateObj.setCheckTime(LocalDateTime.now());
        updateObj.setCheckSystemUserId(getLoginUserId());
        merchantApplyMapper.updateById(updateObj);

        MerchantApplyLogSaveReqVO build = MerchantApplyLogSaveReqVO.builder()
                .status(updateObj.getCheckStatus())
                .merchantApplyId(updateObj.getId())
                .checkComment(updateObj.getCheckComment())
                .build();
        merchantApplyLogService.createMerchantApplyLog(build);

        MerchantSaveReqVO bean = BeanUtils.toBean(updateReqVO, MerchantSaveReqVO.class);
        MerchantDO merchantDO = merchantService.selectByApplyId(updateObj.getId());
        // 如果审核通过
        if (Objects.equals(updateObj.getCheckStatus(), MerchantApplyCheckStatusEnum.AUDIT_PASS.getType())) {
            bean.setStatus(MerchantStatusEnum.USING.getType());

            // 创建
            if (merchantDO == null) {

                MemberUserDO user = memberUserService.getUser(updateReqVO.getApplyMemberUserId());

                bean.setId(null);
                bean.setMerchantApplyId(updateObj.getId());
                bean.setContactNumber(user.getMobile());
                merchantService.createMerchant(bean, !user.getMobile().equals(updateReqVO.getContactNumber()) ? updateReqVO.getContactNumber() : null);
            } else {
                // 修改
                bean.setId(merchantDO.getId());
                merchantService.updateMerchant(bean);

                // 修改商户下的店铺
                List<ShopRespVO> merchantAllShop = shopService.getMerchantAllShop(merchantDO.getId());
                for (ShopRespVO shopRespVO : merchantAllShop) {
                    shopRespVO.setAccountName(updateReqVO.getAccountName());
                    shopRespVO.setAccountNumber(updateReqVO.getAccountNumber());
                    shopRespVO.setBankName(updateReqVO.getBankName());
                    shopService.updateShop(BeanUtils.toBean(shopRespVO, ShopSaveReqVO.class));
                }
            }
        } else if (Objects.equals(updateObj.getCheckStatus(), MerchantApplyCheckStatusEnum.AUDIT_FAIL.getType())) {
            if(merchantDO != null){
                merchantDO.setStatus(MerchantStatusEnum.STOP.getType());
                merchantService.updateMerchant(merchantDO);
            }
        }
    }

    @Override
    public void deleteMerchantApply(Long id) {
        // 校验存在
        validateMerchantApplyExists(id);
        // 删除
        merchantApplyMapper.deleteById(id);
    }

    private void validateMerchantApplyExists(Long id) {
        if (merchantApplyMapper.selectById(id) == null) {
            throw exception(MERCHANT_APPLY_NOT_EXISTS);
        }
    }

    @Override
    public MerchantApplyDO getMerchantApply(Long id) {
        return merchantApplyMapper.selectById(id);
    }

    @Override
    public PageResult<MerchantApplyDO> getMerchantApplyPage(MerchantApplyPageReqVO pageReqVO) {
        return merchantApplyMapper.selectPage(pageReqVO);
    }

}