package com.huiju.estateagents.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.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.entity.TaPersonBuilding;
import com.huiju.estateagents.entity.TaPreselection;
import com.huiju.estateagents.entity.TaPreselectionRecord;
import com.huiju.estateagents.mapper.TaPreselectionMapper;
import com.huiju.estateagents.mapper.TaPreselectionRecordMapper;
import com.huiju.estateagents.service.ITaPreselectionService;
import org.apache.commons.collections.CollectionUtils;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 预选表  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2020-02-26
 */
@Service
public class TaPreselectionServiceImpl extends ServiceImpl<TaPreselectionMapper, TaPreselection> implements ITaPreselectionService {

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

    @Autowired
    private TaPreselectionMapper taPreselectionMapper;

    @Autowired
    private TaPreselectionRecordMapper taPreselectionRecordMapper;

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

        ResponseBean responseBean = new ResponseBean();
        IPage<TaPreselection> pg = new Page<>(pageNum, pageSize);
        IPage<TaPreselection> taPreselectionIPage = taPreselectionMapper.listPresecretByCondition(pg, salesBatchName, buildingId, orgId, status, taPersonBuildingListByUserId);
        taPreselectionIPage.getRecords().forEach(e -> {
            QueryWrapper<TaPreselectionRecord> taPreselectionRecordQueryWrapper = new QueryWrapper<>();
            taPreselectionRecordQueryWrapper.eq("sales_batch_id", e.getSalesBatchId());
            e.setPreNum(taPreselectionRecordMapper.selectCount(taPreselectionRecordQueryWrapper));
        });
        responseBean.addSuccess(taPreselectionIPage);
        return responseBean;
    }

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

        ResponseBean responseBean = new ResponseBean();

        for (TaPreselection tp : taPreselectionList) {
            // 校验是否有用户预选
            QueryWrapper<TaPreselectionRecord> preselectionRecordQueryWrapper = new QueryWrapper<>();
            preselectionRecordQueryWrapper.eq("org_id", orgId);
            preselectionRecordQueryWrapper.eq("sales_batch_id", tp.getSalesBatchId());
            preselectionRecordQueryWrapper.eq("status", 1);
            List<TaPreselectionRecord> tpList = taPreselectionRecordMapper.selectList(preselectionRecordQueryWrapper);
            if (CollectionUtils.isNotEmpty(tpList)) {
                responseBean.addError(String.format("销售批次%s已有用户预选，请先删除预选记录。", tp.getSalesBatchName()));
                return responseBean;
            }
        }

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

        // 更新数据库
        if (updateBatchById(taPreselectionList)) {
            responseBean.addSuccess("success");
        } else {
            responseBean.addError("fail");
        }
        return responseBean;
    }

    @Override
    public ResponseBean getPresecretById(Integer id, Integer orgId) {
        ResponseBean responseBean = new ResponseBean();
        responseBean.addSuccess(taPreselectionMapper.getPresecretById(id, orgId));
        return responseBean;
    }

    @Override
    public ResponseBean checkHavingRecordForSalesBatch(Integer salesBatchId, Integer orgId) {
        logger.info("checkHavingRecordForSalesBatch 接收参数：salesBatchId:{},orgId:{}", salesBatchId, orgId);

        ResponseBean responseBean = new ResponseBean();
        QueryWrapper<TaPreselection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sales_batch_id", salesBatchId);
        queryWrapper.eq("org_id", orgId);
        queryWrapper.eq("status", 1);
        TaPreselection taPreselection = getOne(queryWrapper);
        JSONObject jsonObject = new JSONObject();
        if (taPreselection != null) {
            jsonObject.put("havingRecord", true);
            responseBean.addSuccess(jsonObject);
        } else {
            jsonObject.put("havingRecord", false);
            responseBean.addSuccess(jsonObject);
        }
        return responseBean;
    }
}
