package com.qianhe.zqcz.jcrw.service.impl;

import com.github.pagehelper.PageInfo;
import com.qianhe.common.constant.HttpStatus;
import com.qianhe.common.constant.MtConstant;
import com.qianhe.common.core.page.TableDataInfo;
import com.qianhe.common.exception.BusinessException;
import com.qianhe.common.utils.MtUtils;
import com.qianhe.zqcz.jcdw.domain.ZqczJcdwQuery;
import com.qianhe.zqcz.jcdw.domain.ZqczJcdwVo;
import com.qianhe.zqcz.jcdw.mapper.ZqczJcdwMapper;
import com.qianhe.zqcz.jcrw.domain.*;
import com.qianhe.zqcz.jcrw.mapper.ZqczJcrwMapper;
import com.qianhe.zqcz.jcrw.service.ZqczJcrwService;
import com.qianhe.zqcz.zsrw.domain.ZqczZsrw;
import com.qianhe.zqcz.zsrw.domain.ZqczZsrwVo;
import com.qianhe.zqcz.zsrw.mapper.ZqczZsrwMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.qianhe.common.utils.PageUtils.startPage;

@Slf4j
@Service
public class ZqczJcrwServiceImpl implements ZqczJcrwService {
    @Autowired
    private ZqczJcrwMapper zqczJcrwMapper;
    @Autowired
    private ZqczZsrwMapper zqczZsrwMapper;
    @Autowired
    private ZqczJcdwMapper zqczJcdwMapper;

    /**
     * 条件查询
     */
    @Override
    public List<ZqczJcrwVo> list(ZqczJcrwQuery zqczJcrwQuery) {
        List<ZqczJcrwVo> dataList = zqczJcrwMapper.list(zqczJcrwQuery);
        return dataList;
    }

    /**
     * 查询详情
     */
    @Override
    public ZqczJcrwVo info(Long jcrwid) {
        ZqczJcrwVo info = zqczJcrwMapper.info(jcrwid);
        return info;
    }

    /**
     * 新增
     */
    @Override
    public int add(ZqczJcrw zqczJcrw, String username) {
        zqczJcrw.setCreateBy(username);
        zqczJcrw.setCreateTime(new Date());
        zqczJcrw.setUpdateBy(username);
        return zqczJcrwMapper.add(zqczJcrw);
    }

    /**
     * 修改
     */
    @Override
    public int edit(ZqczJcrw zqczJcrw, String username) {
        zqczJcrw.setUpdateBy(username);
        return zqczJcrwMapper.edit(zqczJcrw);
    }

    /**
     * 删除
     */
    @Override
    public int delete(Long[] ids) {
        return zqczJcrwMapper.delete(ids);
    }

    /**
     * 根据直属任务ID 删除
     */
    @Override
    public int deleteByZsrwid(Long zsrwid) {
        return zqczJcrwMapper.deleteByZsrwid(zsrwid);
    }

    /**
     * 基层抽检查询
     */
    @Override
    public ZqczJccjVo jcrwInfo(Long zsrwid) {
        // 1. 根据直属任务ID 查询直属任务
        ZqczZsrwVo zsrwInfo = zqczZsrwMapper.info(zsrwid);
        if (zsrwInfo == null) {
            log.warn("最强操作 --- 基层抽检查询 --- 直属任务ID：{} --- 暂无直属任务", zsrwid);
            return new ZqczJccjVo();
        }

        // 2. 根据直属任务ID 查询基层任务
        startPage();
        List<ZqczJcrwVo> dataList = zqczJcrwMapper.infoByZsrwId(zsrwid);

        // 构建分页结构
        TableDataInfo tableDataInfo = new TableDataInfo();
        PageInfo<ZqczJcrwVo> pageInfo = new PageInfo<>(dataList);
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setTotal(pageInfo.getTotal());
        tableDataInfo.setRows(dataList);

        // 3. 拼接数据
        ZqczJccjVo info = ZqczJccjVo.builder()
                .glqsl(zsrwInfo.getGlqsl())
                .cjglqsl(zsrwInfo.getCjglqsl())
                .dataList(tableDataInfo).build();
        return info;
    }

    /**
     * 基层任务抽取
     */
    @Transactional
    @Override
    public int spotCheckAdd(ZqczJccjQuery zqczJccjQuery) {
        Long zsrwid = zqczJccjQuery.getZsrwid();  // 直属任务ID
        if (zsrwid == null) {
            log.warn("最强操作 --- 基层任务抽取 --- 直属任务ID不能为空");
            throw new BusinessException("直属任务ID不能为空");
        }

        Integer cjglqsl = zqczJccjQuery.getCjglqsl();  // 抽检数量（采油）
        if (cjglqsl == null) {
            log.warn("最强操作 --- 基层任务抽取 --- 抽检数量不能为空");
            throw new BusinessException("抽检数量不能为空");
        }

        // 1. 根据直属任务ID 获取基层单位
        List<ZqczJcdwVo> jcdwList = zqczJcdwMapper.list(ZqczJcdwQuery.builder().zsrwid(zsrwid).build());
        if (Optional.ofNullable(jcdwList).orElse(Collections.emptyList()).isEmpty()) {
            log.warn("最强操作 --- 基层任务抽取 --- 基层单位未上传");
            throw new BusinessException("基层单位未上传");
        }

        // 2. 根据基层单位类型进行分组
        Map<String, List<ZqczJcdwVo>> jcdwGroupMap = jcdwList.stream().collect(Collectors.groupingBy(ZqczJcdwVo::getJczzlx));

        List<ZqczJcdwVo> mergeList = new ArrayList<>();

        // 3. 处理采油数据
        List<ZqczJcdwVo> cyJcdwList = jcdwGroupMap.get(MtConstant.ZQCZ_JCDWLX_CY_CODE);
        if (!Optional.ofNullable(cyJcdwList).orElse(Collections.emptyList()).isEmpty()) {
            if (cjglqsl > cyJcdwList.size()) {
                log.warn("最强操作 --- 基层任务抽取 --- 抽取数量不能大于管理区基层单位数量");
                throw new BusinessException("抽取数量不能大于管理区基层单位数量");
            }
            List<ZqczJcdwVo> cjcyRandomList = MtUtils.getRandomList(cyJcdwList, cjglqsl);  // 抽检的采油列表
            mergeList.addAll(cjcyRandomList);
        }

        // 4. 处理集输数据
        List<ZqczJcdwVo> jsJcdwList = jcdwGroupMap.get(MtConstant.ZQCZ_JCDWLX_JS_CODE);  // 必检的集输列表
        if (!Optional.ofNullable(jsJcdwList).orElse(Collections.emptyList()).isEmpty()) {
            mergeList.addAll(jsJcdwList);
        }

        // 修改直属任务的抽检数量
        zqczZsrwMapper.edit(ZqczZsrw.builder().zsrwid(zsrwid).cjglqsl(cjglqsl).build());

        // 7. 抽检之前先删除历史数据
        zqczJcrwMapper.deleteByZsrwid(zsrwid);

        int batchSize = 0;

        if (!Optional.ofNullable(mergeList).orElse(Collections.emptyList()).isEmpty()) {
            // 6. 类型转换
            List<ZqczJcrw> zqczJcrwList = new ArrayList<>();
            for (ZqczJcdwVo zqczJcdwVo : mergeList) {
                zqczJcrwList.add(ZqczJcrw.builder()
                        .zsrwid(zsrwid)
                        .jcdwid(zqczJcdwVo.getJcdwid())
                        .cjlx(zqczJcdwVo.getJczzlx())
                        .jcrwzt(MtConstant.ZQCZ_JCCJZT_PWTB)
                        .build());
            }

            // 8. 执行插入
            batchSize = zqczJcrwMapper.batchAdd(zqczJcrwList);
        }
        return batchSize;
    }
}
