package com.tofly.qualitycontrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.qualitycontrol.common.QualityControlConstant;
import com.tofly.qualitycontrol.dto.CollectionNumberDetailDTO;
import com.tofly.qualitycontrol.dto.CollectionNumberSummaryAPIBean;
import com.tofly.qualitycontrol.dto.CollectionNumberSummaryBean;
import com.tofly.qualitycontrol.entity.CollectionNumberDetail;
import com.tofly.qualitycontrol.exception.QualityControlBusinessException;
import com.tofly.qualitycontrol.mapper.CollectionNumberDetailMapper;
import com.tofly.qualitycontrol.service.ICollectionNumberDetailService;
import com.tofly.qualitycontrol.vo.CollectionNumberDetailVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.alibaba.fastjson.JSON.parseArray;
import static com.alibaba.fastjson.JSON.toJSONString;
import static com.google.common.collect.Lists.newArrayList;
import static com.tofly.qualitycontrol.util.CallAPIUtil.callAPIUtil;
import static com.tofly.qualitycontrol.util.QualityControlUtil.getIPage;
import static com.tofly.qualitycontrol.util.QualityControlUtil.isNotNull;
import static java.lang.String.valueOf;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.collections.CollectionUtils.isEmpty;

/**
 * @author B
 */
@Service
public class CollectionNumberDetailServiceImpl extends ServiceImpl<CollectionNumberDetailMapper, CollectionNumberDetail> implements ICollectionNumberDetailService, QualityControlConstant {

    private static final String REGEX = "(?:\\[|null|\\]| +)";
    @Value("${xrtyquality.swagger.ip}")
    private String IP;
    private static final String URL_CLIENT = "/api/Business/GetCustomerData";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addToCollectionNumberByBatch(CollectionNumberDetailDTO collectionNumberDetailDTO) {
        String collectionNumber = collectionNumberDetailDTO.getCollectionNumber();
        String collectionName = collectionNumberDetailDTO.getCollectionName();
        List<String> newClientNumberList = collectionNumberDetailDTO.getClientNumberList();
        String isAll = collectionNumberDetailDTO.getIsAll();
        Boolean flag1 = true;
        Long currentId = baseMapper.getCurrentId();
        //全部分配
        if ("1".equals(isAll)) {
            currentId = currentId - 1;
            String qybm = collectionNumberDetailDTO.getQybm();
            String qydbm = collectionNumberDetailDTO.getQydbm();
            String sbkj = collectionNumberDetailDTO.getSbkj();
            String cbb = collectionNumberDetailDTO.getCbb();
            String cbpq = collectionNumberDetailDTO.getCbpq();
            String ysxz = collectionNumberDetailDTO.getYsxz();
            String sfncys = collectionNumberDetailDTO.getSfncys();
            String jyz = collectionNumberDetailDTO.getJyz();
            List<String> cbqyList = null;
            List<String> cbqydList = null;
            List<String> sbkjList = null;
            List<String> cbbList = null;
            List<String> cbpqList = null;
            List<String> ysxzList = null;
            String inputcontent = collectionNumberDetailDTO.getInputcontent();
            if (StringUtil.isNotEmpty(qybm)) {
                cbqyList = Arrays.asList(qybm.split(","));
            }
            if (StringUtil.isNotEmpty(qydbm)) {
                cbqydList = Arrays.asList(qydbm.split(","));
            }
            if (StringUtil.isNotEmpty(sbkj)) {
                sbkjList = Arrays.asList(sbkj.split(","));
            }
            if (StringUtil.isNotEmpty(cbb)) {
                cbbList = Arrays.asList(cbb.split(","));
            }
            if (StringUtil.isNotEmpty(cbpq)) {
                cbpqList = Arrays.asList(cbpq.split(","));
            }
            if (StringUtil.isNotEmpty(ysxz)) {
                ysxzList = Arrays.asList(ysxz.split(","));
            }
            //根据条件全部分配
            baseMapper.allotAll(collectionNumber, collectionName, currentId, cbqyList, cbqydList, sbkjList, cbbList, cbpqList,
                    ysxzList, inputcontent, sfncys , jyz);
            return flag1;
        } else {
            if (CollectionUtils.isNotEmpty(newClientNumberList)) {
                List<String> originalClientNumberList = list(Wrappers.<CollectionNumberDetail>lambdaQuery().eq(CollectionNumberDetail::getCollectionNumber, collectionNumber)).stream().map(CollectionNumberDetail::getClientNumber).collect(toList());
                int size = 0;
                List<CollectionNumberDetail> collectionNumberDetailList;
                //新增客户列表中的用户和原归集中存在的用户比对去重
                if (CollectionUtils.isNotEmpty(originalClientNumberList)) {
                    List<String> finalList = newClientNumberList.stream().filter(newClientNumber -> !originalClientNumberList.contains(newClientNumber)).collect(toList());
                    size = finalList.size();
                    if (size == 0) {
                        return flag1;
                    } else {
                        collectionNumberDetailList = new ArrayList<>(size);
                        //设置插入数据
                        for (String clientNumber : finalList) {
                            CollectionNumberDetail collectionNumberDetail = CollectionNumberDetail.builder()
                                    .collectionName(collectionName)
                                    .collectionNumber(collectionNumber)
                                    .clientNumber(clientNumber)
                                    .id(currentId++).build();
                            collectionNumberDetailList.add(collectionNumberDetail);
                        }
                    }
                } else {
                    size = newClientNumberList.size();

                    collectionNumberDetailList = new ArrayList<>(size);
                    //设置插入数据
                    for (String clientNumber : newClientNumberList) {
                        CollectionNumberDetail collectionNumberDetail = CollectionNumberDetail.builder()
                                .collectionName(collectionName)
                                .collectionNumber(collectionNumber)
                                .clientNumber(clientNumber)
                                .id(currentId++).build();
                        collectionNumberDetailList.add(collectionNumberDetail);
                    }
                }
                if (size <= 500) {
                    flag1 = baseMapper.insertBatch(collectionNumberDetailList);
                } else {
                    int times = (int) Math.ceil(size / 500.0);
                    for (int i = 0; i < times; i++) {
                        Boolean flag2 = baseMapper.insertBatch(collectionNumberDetailList.subList(i * 500, Math.min((i + 1) * 500, size)));
                        if (!flag2) {
                            throw new QualityControlBusinessException("批量添加失败");
                        }
                    }
                }
            }
            return flag1;
        }

    }

    @Override
    public IPage<CollectionNumberDetailVO> getList(String collectionNumber, String clientNumber, Page<CollectionNumberDetail> page) {
        Boolean flag1 = isNotNull(collectionNumber);
        Boolean flag2 = isNotNull(clientNumber);

        LambdaQueryWrapper<CollectionNumberDetail> queryWrapper = Wrappers.<CollectionNumberDetail>lambdaQuery()
                .eq(flag1, CollectionNumberDetail::getCollectionNumber, collectionNumber)
                .like(flag2, CollectionNumberDetail::getClientNumber, clientNumber)
                .orderByAsc(CollectionNumberDetail::getCollectionNumber);

        List<CollectionNumberDetail> collectionNumberDetailList = page(page, queryWrapper).getRecords();

        List<String> clientNumberList = collectionNumberDetailList.stream().map(CollectionNumberDetail::getClientNumber).collect(toList());

        if (isEmpty(clientNumberList)) {
            new Page<>(page.getCurrent(), page.getSize(), 0);
        }

        CollectionNumberSummaryAPIBean collectionNumberSummaryAPIBean = CollectionNumberSummaryAPIBean.builder()
                .ACTION("query")
                .YHBH(clientNumberList.toString().replaceAll(REGEX, "")).build();
        List<CollectionNumberDetailVO> voList = newArrayList();

        try {
            Map<String, Object> map = callAPIUtil(collectionNumberSummaryAPIBean, IP, URL_CLIENT);
            Object data = map.get("data");
            String jsonString = toJSONString(data);
            List<CollectionNumberSummaryBean> beanList = parseArray(jsonString, CollectionNumberSummaryBean.class);

            collectionNumberDetailList.forEach(collectionNumberDetail -> {
                String clientNum = collectionNumberDetail.getClientNumber();

                //获取最新用户信息
                CollectionNumberSummaryBean bean = beanList.stream().filter(b -> clientNum.equals(b.getYHBH())).collect(toList()).get(0);

                CollectionNumberDetailVO vo = CollectionNumberDetailVO.builder()
                        .id(collectionNumberDetail.getId())
                        .collectionNumber(collectionNumberDetail.getCollectionNumber())
                        .collectionName(collectionNumberDetail.getCollectionName())
                        .clientNumber(clientNum)
                        .clientName(bean.getYHXM())
                        .waterCategory(bean.getYSXZ())
                        .clientAddress(bean.getYHDZ())
                        .clientPhone(bean.getLXDH())
                        .meterNumber(bean.getSBBH())
                        .meterType(bean.getSBLX())
                        .meterCaliber(valueOf(bean.getSBKJ())).build();

                voList.add(vo);
            });
        } catch (Exception e) {
            throw new QualityControlBusinessException("第三方数据库异常,请联系管理员");
        }

        return getIPage(page, voList, count(queryWrapper));
    }

    @Override
    public Boolean deleteCollectionNumberDetailByBatch(List<String> ids) {
        return removeByIds(ids);
    }

    @Override
    public boolean deleteCollectionNumber(String yhbhs, String collectionNumber, String isAll) {
        if (StringUtil.isEmpty(collectionNumber)){
            throw new ToflyDeniedException("请选择归集");
        }
        if ("1".equals(isAll)){
            this.remove(Wrappers.<CollectionNumberDetail>lambdaQuery().eq(CollectionNumberDetail::getCollectionNumber , collectionNumber));
            return true;
        }else {
            if (StringUtil.isEmpty(yhbhs)){
                throw new ToflyDeniedException("请选择用户");
            }
            List<String> yhbhList = Arrays.asList(yhbhs.split(","));
            this.remove(Wrappers.<CollectionNumberDetail>lambdaQuery()
                    .eq(CollectionNumberDetail::getCollectionNumber , collectionNumber).in(CollectionNumberDetail::getClientNumber , yhbhList));
            return true;
        }
    }

}
