package com.yunzhi.marketing.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.common.CommConstant;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.mapper.TaRaiseHouseMapper;
import com.yunzhi.marketing.mapper.TaRaiseMapper;
import com.yunzhi.marketing.mapper.TaRaiseRecordMapper;
import com.yunzhi.marketing.service.ITaHousingResourcesService;
import com.yunzhi.marketing.service.ITaRaiseInviteService;
import com.yunzhi.marketing.service.ITaRaiseService;
import com.yunzhi.marketing.entity.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 认筹表  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2020-02-26
 */
@Service
public class TaRaiseServiceImpl extends ServiceImpl<TaRaiseMapper, TaRaise> implements ITaRaiseService {

    private Logger logger = LoggerFactory.getLogger(TaRaiseServiceImpl.class);

    @Autowired
    private TaRaiseRecordMapper taRaiseRecordMapper;

    @Autowired
    private TaRaiseMapper taRaiseMapper;

    @Autowired
    private TaRaiseHouseMapper taRaiseHouseMapper;

    @Autowired
    private ITaHousingResourcesService taHousingResourcesService;

    @Autowired
    private ITaRaiseInviteService taRaiseInviteService;

    @Override
    public ResponseBean listRaiseByCondition(Integer pageSize, Integer pageNum, String salesBatchName, String buildingId, Integer orgId, Integer status, List<TaPersonBuilding> taPersonBuildingListByUserId) {
        logger.info("listSalesBatchForRaise 接收参数：pageSize:{},pageNum:{},salesBatchName:{},buildilgId:{},orgId:{},status:{},taPersonBuildingListByUserId:{}",
                pageSize, pageNum, salesBatchName, buildingId, orgId, status, JSONObject.toJSONString(taPersonBuildingListByUserId));

        ResponseBean responseBean = new ResponseBean();

        IPage<TaRaise> pg = new Page<>(pageNum, pageSize);
        responseBean.addSuccess(taRaiseMapper.listRaiseByCondition(pg, salesBatchName, buildingId, orgId, status, taPersonBuildingListByUserId));
        return responseBean;
    }

    @Override
    public ResponseBean batchDelete(List<TaRaise> taRaiseList, Integer orgId) {
        logger.info("TaRaiseServiceImpl.batchDelete 接收参数：list:{},orgId:{}", JSONObject.toJSONString(taRaiseList), orgId);

        ResponseBean responseBean = new ResponseBean();
        // 校验参数
        if (CollectionUtils.isEmpty(taRaiseList)) {
            responseBean.addError("参数错误");
            return responseBean;
        }

        for (TaRaise tr : taRaiseList) {
            // 校验销售批次下是否有认筹记录
            QueryWrapper<TaRaiseRecord> taRaiseRecordQueryWrapper = new QueryWrapper<>();
            taRaiseRecordQueryWrapper.eq("org_id", orgId);
//            taRaiseRecordQueryWrapper.eq("raise_id", tr.getRaiseId());
            taRaiseRecordQueryWrapper.eq("sales_batch_id", tr.getSalesBatchId());
            taRaiseRecordQueryWrapper.eq("status", 1);
            List<TaRaiseRecord> list = taRaiseRecordMapper.selectList(taRaiseRecordQueryWrapper);
            if (CollectionUtils.isNotEmpty(list)) {
                responseBean.addError(String.format("销售批次%s下已有认筹记录，不可删除", tr.getSalesBatchName()));
                return responseBean;
            }
        }

        taRaiseList.stream().forEach(record -> {
            record.setStatus(-1);
        });

        if (updateBatchById(taRaiseList)) {
            responseBean.addSuccess("操作成功");
        } else {
            responseBean.addError("fail");
        }
        return responseBean;
    }

    @Override
    public ResponseBean getRaiseById(Integer id, Integer orgId) {
        ResponseBean responseBean = new ResponseBean();
        TaRaise taRaise = taRaiseMapper.getRaiseById(id, orgId);
        if (taRaise == null) {
            responseBean.addSuccess(null);
            return responseBean;
        }

        if (taRaise.getInvite() != null && CommConstant.STATUS_NORMAL == taRaise.getInvite()) {
            // 获取邀请人数据
            QueryWrapper<TaRaiseInvite> taRaiseInviteQueryWrapper = new QueryWrapper<>();
            taRaiseInviteQueryWrapper.eq("org_id", orgId);
            taRaiseInviteQueryWrapper.eq("raise_id", taRaise.getRaiseId());
            taRaiseInviteQueryWrapper.orderByAsc("create_date");
            List<TaRaiseInvite> taRaiseInviteList = taRaiseInviteService.list(taRaiseInviteQueryWrapper);
            StringBuilder inviteTelSb = new StringBuilder();
            taRaiseInviteList.stream().forEach(record -> {
                inviteTelSb.append(record.getInviteTel() + "\n");
            });
            taRaise.setInviteTel(inviteTelSb.toString());
        }

        taRaise.setRaisePrice(taRaise.getRaisePrice() == null ? null : taRaise.getRaisePrice());
        responseBean.addSuccess(taRaise);
        return responseBean;
    }

    @Override
    public TaRaise getRaiseProfile(Integer raiseId, Integer raiseRecordId, Integer salesBatchId) {
        if (raiseId == null && salesBatchId == null && raiseRecordId == null) return null;

        TaRaise taRaise = null;
        TaRaiseRecord taRaiseRecord = null;

        // 通过认筹记录ID 或者 批次ID 查询
        if (raiseId != null || salesBatchId != null) {
            QueryWrapper<TaRaise> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(raiseId != null, "raise_id", raiseId);
            queryWrapper.eq(salesBatchId != null, "sales_batch_id", salesBatchId);
            queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
            queryWrapper.last(" limit 1");
            taRaise = this.getOne(queryWrapper);
        }

        // 通过认筹单记录ID
        if (raiseRecordId != null) {
            QueryWrapper<TaRaiseRecord> wrapper = new QueryWrapper<>();
            wrapper.eq("raise_record_id", raiseRecordId);
            wrapper.eq("status", CommConstant.STATUS_NORMAL);
            wrapper.last("limit 1");
            taRaiseRecord = taRaiseRecordMapper.selectOne(wrapper);

            //加入房源信息
            if (null != taRaiseRecord) {
                //房源与认筹单关系图
                List<TaRaiseHouse> taRaiseHouseList = taRaiseHouseMapper.selectList(new QueryWrapper<TaRaiseHouse>().eq("raise_record_id", taRaiseRecord.getRaiseRecordId()));
                if (taRaiseHouseList.size() > 0) {
                    //房源信息
                    List<TaHousingResources> houseList = (List<TaHousingResources>) taHousingResourcesService.listByIds(taRaiseHouseList.stream().map(TaRaiseHouse::getHouseId).collect(Collectors.toList()));
                    taRaiseRecord.setTaHousingResourcesList(houseList);
                }
            }
            if (taRaise == null && taRaiseRecord != null) {
                taRaise = this.getById(taRaiseRecord.getRaiseId());
            }
        }

        if (taRaise != null && taRaiseRecord != null) {
            taRaise.setRecord(taRaiseRecord);
        }

        return taRaise;
    }

    @Override
    public Boolean saveOrUpdateInvite(TaRaise taRaise, Integer orgId, Boolean isAdd) {
        List<TaRaiseInvite> taRaiseInviteList = new ArrayList<>();
        String[] inviteTelArr = StringUtils.isEmpty(taRaise.getInviteTel()) ?
                new String[]{} : taRaise.getInviteTel().split("\n");

        QueryWrapper<TaRaiseInvite> taRaiseInviteQueryWrapper = new QueryWrapper<>();
        taRaiseInviteQueryWrapper.eq("org_id", orgId);
        taRaiseInviteQueryWrapper.eq("raise_id", taRaise.getRaiseId());
        taRaiseInviteService.remove(taRaiseInviteQueryWrapper);

        Arrays.asList(inviteTelArr).stream().distinct().forEach(record -> {
            TaRaiseInvite taRaiseInvite = new TaRaiseInvite();
            taRaiseInvite.setOrgId(orgId);
            taRaiseInvite.setRaiseId(taRaise.getRaiseId());
            taRaiseInvite.setBuildingId(taRaise.getBuildingId());
            taRaiseInvite.setSalesBatchId(taRaise.getSalesBatchId());
            taRaiseInvite.setCreateDate(LocalDateTime.now());
            taRaiseInvite.setInviteTel(record);
            taRaiseInviteList.add(taRaiseInvite);
        });
        return taRaiseInviteService.saveBatch(taRaiseInviteList);
    }
}
