package com.iformall.service.invest.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.iformall.common.TableLog;
import com.iformall.domain.po.invest.InvestTaskEntity;
import com.iformall.enums.EnumFollowType;
import com.iformall.enums.EnumInvestMessageType;
import com.iformall.mapper.InvestTaskDao;
import com.iformall.service.MallUserInfoService;
import com.iformall.service.WxShopService;
import com.iformall.service.invest.InvestTaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class InvestTaskServiceImpl extends InvestBaseServiceImpl<InvestTaskDao, InvestTaskEntity> implements InvestTaskService {

    @Autowired
    private WxShopService shopService;
    @Autowired
    private MallUserInfoService userInfoService;

    @TableLog
    @Override
    public boolean save(InvestTaskEntity entity) {
        super.saveAction(entity, this::checkBeforeSaveOrUpdate);
        saveMessage(entity);
        //TODO 同步一下签约状态
        return true;
    }

    @TableLog
    @Override
    public boolean update(InvestTaskEntity entity, Wrapper<InvestTaskEntity> updateWrapper) {
        super.updateActon(entity, updateWrapper, this::checkBeforeSaveOrUpdate);
        saveMessage(entity);
        //TODO 同步一下签约状态
        return true;
    }

    @TableLog
    @Override
    public boolean updateById(InvestTaskEntity entity) {
        super.updateByIdAction(entity, this::checkBeforeSaveOrUpdate);
        saveMessage(entity);
        return true;
    }

    private void saveMessage(InvestTaskEntity entity) {
        String owner = entity.getOwner();
        if (StringUtils.isNotEmpty(owner)) {
            List<Long> ownerArray = JSONArray.parseArray(owner, Long.class);
            this.saveBatchMessage(ownerArray, EnumInvestMessageType.TASK_CREATE, EnumFollowType.TASK, entity.getId());
        }
    }

    private void checkBeforeSaveOrUpdate(InvestTaskEntity entity) {
        // 1 check shop 状态
        checkShop(shopService, entity);
        // 2 check user
        checkUserExit(userInfoService, entity.getOwner());
        if (Objects.nonNull(entity.getOwner())) {
            entity.setOwner(stringToJson(entity.getOwner()));
        }
        if (Objects.nonNull(entity.getContent())) {
            entity.setContent(stringToJson(entity.getContent()));
        }
    }

    @Deprecated
    @Override
    public boolean saveOrUpdate(InvestTaskEntity entity) {
        notSupport();
        return false ;
    }

    @Deprecated
    @Override
    public boolean update(Wrapper<InvestTaskEntity> updateWrapper) {
        notSupport();
        return false ;
    }
}
