package cn.newfeifan.mall.module.product.service.spuapply;

import cn.newfeifan.mall.module.product.controller.admin.spu.vo.ProductSpuSaveReqVO;
import cn.newfeifan.mall.module.product.controller.admin.spu.vo.ProductSpuUpdateStatusReqVO;
import cn.newfeifan.mall.module.product.controller.admin.spuapplylog.vo.SpuApplyLogSaveReqVO;
import cn.newfeifan.mall.module.product.convert.spuapply.SpuApplyConvert;
import cn.newfeifan.mall.module.product.dal.dataobject.skuapply.SkuApplyDO;
import cn.newfeifan.mall.module.product.dal.dataobject.spu.ProductSpuDO;
import cn.newfeifan.mall.module.product.enums.spu.SpuApplyCheckStatusEnum;
import cn.newfeifan.mall.module.product.service.skuapply.SkuApplyService;
import cn.newfeifan.mall.module.product.service.spu.ProductSpuService;
import cn.newfeifan.mall.module.product.service.spuapplylog.SpuApplyLogService;
import cn.newfeifan.mall.module.system.api.sms.SmsCodeApi;
import cn.newfeifan.mall.module.system.api.sms.dto.code.SmsCodeSendReqDTO;
import cn.newfeifan.mall.module.system.dal.dataobject.user.AdminUserDO;
import cn.newfeifan.mall.module.system.enums.sms.SmsSceneEnum;
import cn.newfeifan.mall.module.system.service.user.AdminUserService;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

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

import java.time.LocalDateTime;
import java.util.*;

import cn.newfeifan.mall.module.product.controller.admin.spuapply.vo.*;
import cn.newfeifan.mall.module.product.dal.dataobject.spuapply.SpuApplyDO;
import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.util.object.BeanUtils;

import cn.newfeifan.mall.module.product.dal.mysql.spuapply.SpuApplyMapper;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.newfeifan.mall.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.newfeifan.mall.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.newfeifan.mall.module.product.enums.ErrorCodeConstants.*;

/**
 * 商品spu申请 Service 实现类
 *
 * @author 非繁人
 */
@Service
@Validated
public class SpuApplyServiceImpl implements SpuApplyService {

    @Resource
    private SpuApplyMapper spuApplyMapper;
    @Resource
    private SkuApplyService skuApplyService;
    @Resource
    private SpuApplyLogService spuApplyLogService;
    @Resource
    private ProductSpuService spuService;
    @Resource
    private AdminUserService adminUserService;
    @Resource
    private SmsCodeApi smsCodeApi;

    @Override
    public Long createSpuApply(SpuApplySaveReqVO createReqVO) {
        // 插入
        SpuApplyDO spuApply = BeanUtils.toBean(createReqVO, SpuApplyDO.class);
        spuApplyMapper.insert(spuApply);
        // 返回
        return spuApply.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSpuApplyByCheckStatus(SpuApplySaveReqVO updateReqVO) {
        // 校验存在
        SpuApplyRespVO spuApplyDetail = getSpuApplyDetail(updateReqVO.getId());
        if (spuApplyDetail == null) {
            throw exception(SPU_APPLY_NOT_EXISTS);
        }

        // 更新
        SpuApplyDO updateObj = BeanUtils.toBean(updateReqVO, SpuApplyDO.class);
        Long loginUserId = getLoginUserId();
        updateObj.setCheckSystemUserId(loginUserId);
        updateObj.setCheckTime(LocalDateTime.now());
        spuApplyMapper.updateById(updateObj);

        //如果审核通过 同步修改商品
        if (updateReqVO.getCheckStatus().equals(SpuApplyCheckStatusEnum.CHECK_PASS.getStatus())) {

            ProductSpuDO spu = spuService.getSpuByApplyId(updateReqVO.getId());

            if (spu != null) {
                spuService.updateSpu(BeanUtils.toBean(spuApplyDetail, ProductSpuSaveReqVO.class));
            } else {
                ProductSpuSaveReqVO bean = BeanUtils.toBean(spuApplyDetail, ProductSpuSaveReqVO.class);
                bean.setSpuApplyId(updateReqVO.getId());
                spuService.createSpu(bean);
            }

        }

        // 记录审核
        spuApplyLogService.createSpuApplyLog(SpuApplyLogSaveReqVO.builder()
                .status(updateReqVO.getCheckStatus())
                .productSpuApplyId(updateReqVO.getId())
                .checkComment(updateReqVO.getCheckComment())
                .checkSystemUserId(loginUserId)
                .changeJsonObject(JSON.toJSONString(spuApplyDetail))
                .build());

        AdminUserDO user = adminUserService.getUser(updateReqVO.getApplyMemberUserId());
        SmsCodeSendReqDTO smsCodeSendReqDTO = SmsCodeSendReqDTO.builder()
                .mobile(user.getMobile())
                .createIp(getClientIP())
                .name(spuApplyDetail.getName())
                .build();
        if (updateReqVO.getCheckStatus().equals(SpuApplyCheckStatusEnum.CHECK_PASS.getStatus())) {
            smsCodeSendReqDTO.setScene(SmsSceneEnum.SPU_APPLY_SUCCESS.getScene());
        } else {
            smsCodeSendReqDTO.setScene(SmsSceneEnum.SPU_APPLY_ERROR.getScene());
        }
        // 发送短信
        smsCodeApi.sendSmsCode(smsCodeSendReqDTO);
    }

    @Override
    public void deleteSpuApply(Long id) {
        // 校验存在
        validateSpuApplyExists(id);
        // 删除
        spuApplyMapper.deleteById(id);

        ProductSpuDO spu = spuService.getSpuByApplyId(id);
        spuService.deleteSpu(spu.getId());
    }

    private void validateSpuApplyExists(Long id) {
        if (spuApplyMapper.selectById(id) == null) {
            throw exception(SPU_APPLY_NOT_EXISTS);
        }
    }

    @Override
    public SpuApplyDO getSpuApply(Long id) {
        return spuApplyMapper.selectById(id);
    }

    @Override
    public PageResult<SpuApplyDO> getSpuApplyPage(SpuApplyPageReqVO pageReqVO) {
        return spuApplyMapper.selectPage(pageReqVO);
    }

    @Override
    public SpuApplyDO getSpu(Long id) {
        return spuApplyMapper.selectById(id);
    }

    @Override
    public SpuApplyRespVO getSpuApplyDetail(Long id) {
        // 获得商品 SPU 申请
        SpuApplyDO spu = getSpu(id);
        if (spu == null) {
            return null;
        }
        // 查询商品 SKU
        List<SkuApplyDO> skus = skuApplyService.getSkuListBySpuId(spu.getId());

        String shopName = spuApplyMapper.selectShopNameById(spu.getShopId());

        SpuApplyRespVO convert = SpuApplyConvert.INSTANCE.convert(spu, skus);
        convert.setShopName(shopName);
        return convert;
    }

    @Override
    public Long getSpuApplyTotal() {
        return spuApplyMapper.selectCount(SpuApplyDO::getCheckStatus, SpuApplyCheckStatusEnum.WAIT_CHECK.getStatus());
    }

    @Override
    public void updateSpuStatus(ProductSpuUpdateStatusReqVO updateReqVO) {

        // 校验存在
        validateSpuApplyExists(updateReqVO.getId());
        // TODO 非繁人：【可选】参与活动中的商品，不允许下架？？？

        // 更新状态
        SpuApplyDO productSpuDO = spuApplyMapper.selectById(updateReqVO.getId()).setStatus(updateReqVO.getStatus());
        spuApplyMapper.updateById(productSpuDO);

        ProductSpuDO spu = spuService.getSpuByApplyId(updateReqVO.getId()).setStatus(updateReqVO.getStatus());
        spuService.updateById(spu);
    }

    @Override
    public List<SpuApplyDO> selectListByMerId(Long merId) {
        return spuApplyMapper.selectList(SpuApplyDO::getMerchantId,merId);
    }

}