package com.tofly.watermeter.custom.service.meterBusiness.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.api.UserClent;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.watermeter.custom.entity.dto.SyncCommonDto;
import com.tofly.watermeter.custom.entity.marketing.CommonParam;
import com.tofly.watermeter.custom.entity.meterBusiness.dto.BatchInstallTableDto;
import com.tofly.watermeter.custom.entity.meterBusiness.dto.InstallConditionDto;
import com.tofly.watermeter.custom.entity.meterBusiness.dto.InstallTableDto;
import com.tofly.watermeter.custom.entity.meterBusiness.dto.ParamDto;
import com.tofly.watermeter.custom.mapper.meterBusiness.TableInstallMapper;
import com.tofly.watermeter.custom.service.meterBusiness.TableInstallService;
import com.tofly.watermeter.custom.service.meterBusiness.export.ExportCommonCodeService;
import com.tofly.watermeter.custom.vo.StationVo;
import com.tofly.watermeter.em.ApiCallEnum;
import com.tofly.watermeter.entity.Bwrksbdatail;
import com.tofly.watermeter.entity.Qfkhjbxx;
import com.tofly.watermeter.service.BwrksbdatailService;
import com.tofly.watermeter.service.QfkhjbxxService;
import com.tofly.watermeter.util.CallAPIUtil;
import com.tofly.watermeter.util.service.CallAPIService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@AllArgsConstructor
@Service
@Slf4j
public class TableInstallServiceImpl implements TableInstallService {

    private final TableInstallMapper tableInstallMapper;
    private final BwrksbdatailService bwrksbdatailService;
    private final ExportCommonCodeService exportCommonCodeService;
    private final QfkhjbxxService qfkhjbxxService;
    private final UserClent userClent;
    private final CallAPIService callAPIService;

    /**
     * 获取未安装水表客户信息
     *
     * @param dto 客户姓名、地址、电话、编号
     * @return list
     */
    @Override
    public Page<Map> getCustomerInfo(Page page, String dto) {
        return tableInstallMapper.getCustomerInfo(page, dto);
    }

    /**
     * 获取水表信息
     */
    @Override
    public Page<Map> getTableInfo(Page page, String dto, Long sbcj, Long sblx, Long sbkj) {
        return tableInstallMapper.getTableInfo(page, dto, sbcj, sblx, sbkj);
    }

    /**
     * 水表安装
     *
     * @param ids 暂存id
     * @return boolean
     * @throws Exception
     */
    @Override
    public boolean tableInstall(String ids) {

        if (StringUtils.isEmpty(ids)) {
            throw new ToflyDeniedException("暂存信息为空");
        }

        List<String> idList = Arrays.asList(ids.split(","));

        List<Bwrksbdatail> bwrksbdatailList = bwrksbdatailService.list(Wrappers.<Bwrksbdatail>lambdaQuery()
                .in(Bwrksbdatail::getId, idList));

        List<InstallTableDto> dtoList = new ArrayList<>();

        InstallTableDto dto;

        for (Bwrksbdatail rk : bwrksbdatailList) {
            dto = new InstallTableDto();

            dto.setACTION("query")
                    .setYHDZ(rk.getBwKhdz())
                    .setYHXM(rk.getBwKhxm())
                    .setYHBH(rk.getBwKhbh())
                    .setSBQD(rk.getBwSbqd().toString())
                    .setSBLX(rk.getBwSblx().toString())
                    .setSBKJ(rk.getBwSbkj().toString())
                    .setSBCJ(rk.getBwSbcj().toString())
                    .setLXDH(rk.getBwKhdh())
                    .setSFNCYS(rk.getSfncys())
                    .setJYZ(rk.getJyzBm())
                    .setBZBH(rk.getBzbh())
                    .setGDDH(rk.getGddh())
                    .setSBBH(rk.getBwSbbh())
                    .setAZRQ(DateUtil.getDateFormat(rk.getBwAzrq() == null ? new Date() : rk.getBwAzrq(), "yyyyMMdd"))
                    .setAZRY(rk.getBwAzry().toString())
                    .setAZFS(rk.getAzfs())
                    .setSBYT(rk.getSbyt())
                    .setYSXZ(rk.getYsxz())
                    .setSBAZDZ(rk.getBwKhdz());

            log.info("同步数据为：" + JSONObject.toJSONString(dto));

            dtoList.add(dto);
        }


        Map map = null;
        for (InstallTableDto itDto : dtoList) {
            try {
                map = CallAPIUtil.callAPIUtil(itDto, "/api/Business/newWater");
            } catch (Exception e) {
                e.printStackTrace();
            }
            String isSyc = "1";
            String msg = "";


            if (map != null && !map.isEmpty()) {
                if (!"0000".equals(map.get("Code"))) {
                    isSyc = "2";
                    msg = map.get("message").toString();
                } else {
                    msg = map.get("data").toString();
                }
            } else {
                isSyc = "2";
                msg = "调用同步接口失败";
            }
            bwrksbdatailService.update(Wrappers.<Bwrksbdatail>lambdaUpdate()
                    .set(Bwrksbdatail::getIssyc, isSyc)
                    .set(Bwrksbdatail::getMsg, msg)
                    .set(Bwrksbdatail::getSynTime, new Date())
                    .eq(Bwrksbdatail::getBwSbbh, itDto.getSBBH()));
        }
        return true;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public boolean tableInstall(InstallTableDto dto) throws Exception {
//        if (dto == null) {
//            throw new ToflyDeniedException("传入数据为空");
//        }
//        dto.setACTION("QUERY");
//        Map map = CallAPIUtil.callAPIUtil(dto, "/api/Business/newWater");
//        if ("0000".equals(map.get("code"))) {
//
//            User result = userClent.getById(Long.valueOf(dto.getAZRY())).getResult();
//
//            assert result != null;
//            bwrksbdatailService.update(Wrappers.<Bwrksbdatail>lambdaUpdate().eq(Bwrksbdatail::getBwSbbh, dto.getSBBH())
//                    .set(!StringUtils.isEmpty(dto.getYHBH()), Bwrksbdatail::getBwKhbh, dto.getYHBH())
//                    .set(Bwrksbdatail::getBwKhdz, dto.getYHDZ())
//                    .set(Bwrksbdatail::getAzfs, dto.getAZFS())
//                    .set(Bwrksbdatail::getBwKhxm, dto.getYHXM())
//                    .set(!StringUtils.isEmpty(dto.getLXDH()), Bwrksbdatail::getBwKhdh, dto.getLXDH())
//                    .set(Bwrksbdatail::getBwSbzt, 3)
//                    .set(Bwrksbdatail::getBwAzry, dto.getAZRY())
//                    .set(Bwrksbdatail::getBwSbqd, Long.valueOf(dto.getSBQD()))
//                    .set(!StringUtils.isEmpty(dto.getGDDH()), Bwrksbdatail::getGddh, dto.getGDDH())
//                    .set(Bwrksbdatail::getBwAzrq, new Date())
//                    .set(Bwrksbdatail::getAzbm, result.getDepartmentId()));
//
//            qfkhjbxxService.update(Wrappers.<Qfkhjbxx>lambdaUpdate().eq(Qfkhjbxx::getYhbh, dto.getYHBH())
//                    .set(Qfkhjbxx::getZbry, dto.getAZRY())
//                    .set(Qfkhjbxx::getSfncys, dto.getSFNCYS())
//                    .set(Qfkhjbxx::getJyz, dto.getJYZ())
//                    .set(Qfkhjbxx::getSbbh, dto.getSBBH())
//                    .set(Qfkhjbxx::getSbcj, dto.getSBCJ())
//                    .set(Qfkhjbxx::getSbkj, dto.getSBKJ())
//                    .set(Qfkhjbxx::getSblx, dto.getSBLX())
//                    .set(Qfkhjbxx::getAzfs, dto.getAZFS())
//                    .set(Qfkhjbxx::getZhXgrq, new Date()));
//        } else {
//            throw new ToflyDeniedException(map.get("message").toString());
//        }
//        return true;
//    }

    @Override
    public List<Map> installCount(HttpServletResponse response, InstallConditionDto dto) {

        List<Map> maps = tableInstallMapper.installCount(dto);

        if (dto.getExport() == 1) {
            exportCommonCodeService.exportCode(response, "tableInstallCountService", maps);
        }
        return maps;
    }

    @Override
    public Page<Map> countByType(HttpServletResponse response, Page page, InstallConditionDto dto) {
        if (dto.getExport() == 1) {
            exportCommonCodeService.exportCode(response, "queryByNewTableService", tableInstallMapper.countByNewTable(dto));
        }
        return tableInstallMapper.countByNewTable(page, dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object theStagingAbout(HttpServletResponse response, Page page, InstallTableDto dto) {

        if (dto == null) {
            throw new ToflyDeniedException("参数列表不允许为空");
        }


        if (StringUtils.isEmpty(dto.getState())) {
            throw new ToflyDeniedException("state必传");
        }
        //查询
        if ("0".equals(dto.getState())) {
            return tableInstallMapper.theStagingQuery(dto);
            //分页
        } else if ("3".equals(dto.getState())) {
            if (dto.getIsExport() != null && dto.getIsExport() == 1) {
                exportCommonCodeService.exportCode(response, "theStagingExportService", tableInstallMapper.theStagingQuery(dto));
            }
            return tableInstallMapper.theStagingQuery(page, dto);
            //新增或修改
        } else if ("1".equals(dto.getState())) {
            if (StringUtils.isEmpty(dto.getSBBH())) {
                throw new ToflyDeniedException("水表编号不允许为空");
            }

            if (StringUtils.isEmpty(dto.getSBYT())) {
                throw new ToflyDeniedException("水表用途不允许为空");
            }

            if (StringUtils.isEmpty(dto.getYSXZ())) {
                throw new ToflyDeniedException("用水性质不允许为空");
            }

            List<Qfkhjbxx> khList = qfkhjbxxService.list(Wrappers.<Qfkhjbxx>lambdaQuery().eq(Qfkhjbxx::getSbbh, dto.getSBBH()));

            if (CollectionUtil.isNotEmpty(khList)) {
                throw new ToflyDeniedException("该水表已在营销新装，无需再次安装");
            }

            if (StringUtils.isEmpty(dto.getAZRQ())) {
                throw new ToflyDeniedException("未传入安装日期");
            }

            Long deptId = !StringUtils.isEmpty(dto.getAZRY()) ? userClent.getById(Long.valueOf(dto.getAZRY())).getResult().getDepartmentId() : null;
            Date date = DateUtil.formatDate(dto.getAZRQ(), "yyyy-MM-dd HH:mm:ss");

            bwrksbdatailService.update(Wrappers.<Bwrksbdatail>lambdaUpdate()
                    .set(!StringUtils.isEmpty(dto.getYHBH()), Bwrksbdatail::getBwKhbh, dto.getYHBH())
                    .set(!StringUtils.isEmpty(dto.getYHXM()), Bwrksbdatail::getBwKhxm, dto.getYHXM())
                    .set(!StringUtils.isEmpty(dto.getLXDH()), Bwrksbdatail::getBwKhdh, dto.getLXDH())
                    .set(!StringUtils.isEmpty(dto.getYHDZ()), Bwrksbdatail::getBwKhdz, dto.getYHDZ())
                    .set(!StringUtils.isEmpty(dto.getGDDH()), Bwrksbdatail::getGddh, dto.getGDDH())
                    .set(!StringUtils.isEmpty(dto.getAZRQ()), Bwrksbdatail::getBwAzrq, date)
                    .set(!StringUtils.isEmpty(dto.getAZRY()), Bwrksbdatail::getBwAzry, dto.getAZRY())
                    .set(!StringUtils.isEmpty(dto.getSBQD()), Bwrksbdatail::getBwSbqd, dto.getSBQD())
                    .set(!StringUtils.isEmpty(dto.getAZFS()), Bwrksbdatail::getAzfs, dto.getAZFS())
                    .set(!StringUtils.isEmpty(dto.getSFNCYS()), Bwrksbdatail::getSfncys, dto.getSFNCYS())
                    .set(!StringUtils.isEmpty(dto.getJYZ()), Bwrksbdatail::getJyz, dto.getJYZ())
                    .set(!StringUtils.isEmpty(dto.getJyzBm()), Bwrksbdatail::getJyzBm, dto.getJyzBm())
                    .set(!StringUtils.isEmpty(dto.getBZBH()), Bwrksbdatail::getBzbh, dto.getBZBH())
                    .set(!StringUtils.isEmpty(dto.getYHDZ()), Bwrksbdatail::getSbazdz, dto.getYHDZ())
                    .set(!StringUtils.isEmpty(dto.getSBYT()), Bwrksbdatail::getSbyt, dto.getSBYT())
                    .set(!StringUtils.isEmpty(dto.getSbytName()), Bwrksbdatail::getSbytName, dto.getSbytName())
                    .set(!StringUtils.isEmpty(dto.getYSXZ()), Bwrksbdatail::getYsxz, dto.getYSXZ())
                    .set(!StringUtils.isEmpty(dto.getYsxzName()), Bwrksbdatail::getYsxzName, dto.getYsxzName())
                    .set(!StringUtils.isEmpty(deptId), Bwrksbdatail::getAzbm, deptId)
                    .set(Bwrksbdatail::getIssyc, 0)
                    .set(Bwrksbdatail::getBwSbzt, 3)
                    .eq(Bwrksbdatail::getBwSbbh, dto.getSBBH()));

            return tableInstallMapper.theStagingQuery(null);
            //删除
        } else {
            bwrksbdatailService.update(Wrappers.<Bwrksbdatail>lambdaUpdate()
                    .set(Bwrksbdatail::getIssyc, "")
                    .set(Bwrksbdatail::getBwSbzt, 2)
                    .eq(Bwrksbdatail::getBwSbbh, dto.getSBBH()));

            return tableInstallMapper.theStagingQuery(null);
        }
    }

    @Override
    public List<StationVo> getStation() throws Exception {
        List<StationVo> result = null;
        ParamDto dto = new ParamDto();
        dto.setACTION("query");
        Map map = CallAPIUtil.callAPIUtil(dto, "/api/Business/BOOSTER_STATION");
        if ("0000".equals(map.get("Code"))) {
            result = JSONObject.parseArray(map.get("data").toString(), StationVo.class);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchTableInstall(BatchInstallTableDto dto) {
        if (dto == null) {
            throw new ToflyDeniedException("未传入水表信息");
        }
        List<InstallTableDto> batchDto = dto.getBatchDto();
        if (CollectionUtil.isEmpty(batchDto)) {
            throw new ToflyDeniedException("传入水表信息为空");
        }

        List<String> sbbhList = batchDto.stream().map(InstallTableDto::getSBBH).collect(Collectors.toList());

        List<Qfkhjbxx> khList = tableInstallMapper.queryClientInfo(sbbhList);
//        List<Qfkhjbxx> khList = qfkhjbxxService.list(Wrappers.<Qfkhjbxx>lambdaQuery().in(Qfkhjbxx::getSbbh, sbbhList));

        if (CollectionUtil.isNotEmpty(khList)) {
            String result = khList.stream().map(Qfkhjbxx::getSbbh).collect(Collectors.joining(","));
            throw new ToflyDeniedException("水表编号：" + result + "已在营销新装，无需再次安装");
        }
        List<String> sbbhs = tableInstallMapper.queryInstallTable(sbbhList);
        /*List<String> sbbhs = bwrksbdatailService.list(Wrappers.<Bwrksbdatail>lambdaQuery()
                .in(Bwrksbdatail::getBwSbbh,sbbhList).eq(Bwrksbdatail::getBwSbzt, "2"))
                .stream()
                .filter(Objects::nonNull).map(Bwrksbdatail::getBwSbbh).collect(Collectors.toList());*/

        sbbhList.removeAll(sbbhs);

        if (CollectionUtil.isNotEmpty(sbbhList)){
            throw new ToflyDeniedException("水表编号:" + String.join(",", sbbhList) + "未在库内或未出库，请确认" );
        }
        
        for (InstallTableDto installTableDto : batchDto) {

            if (StringUtils.isEmpty(installTableDto.getSBBH())) {
                throw new ToflyDeniedException("水表编号" +installTableDto.getSBBH() + "水表编号不允许为空");
            }

            if (StringUtils.isEmpty(installTableDto.getSBYT())) {
                throw new ToflyDeniedException("水表编号" +installTableDto.getSBBH() + "水表用途不允许为空");
            }

            if (StringUtils.isEmpty(installTableDto.getYSXZ())) {
                throw new ToflyDeniedException("水表编号" +installTableDto.getSBBH() + "用水性质不允许为空");
            }

            Long deptId = !StringUtils.isEmpty(installTableDto.getAZRY()) ? userClent.getById(Long.valueOf(installTableDto.getAZRY())).getResult().getDepartmentId() : null;
            Date date = installTableDto.getAZRQ() == null ? null : cn.hutool.core.date.DateUtil.parse(installTableDto.getAZRQ(), "yyyy-MM-dd HH:mm:ss");

            bwrksbdatailService.update(Wrappers.<Bwrksbdatail>lambdaUpdate()
                    .set(!StringUtils.isEmpty(installTableDto.getYHBH()), Bwrksbdatail::getBwKhbh, installTableDto.getYHBH())
                    .set(!StringUtils.isEmpty(installTableDto.getYHXM()), Bwrksbdatail::getBwKhxm, installTableDto.getYHXM())
                    .set(!StringUtils.isEmpty(installTableDto.getLXDH()), Bwrksbdatail::getBwKhdh, installTableDto.getLXDH())
                    .set(!StringUtils.isEmpty(installTableDto.getYHDZ()), Bwrksbdatail::getBwKhdz, installTableDto.getYHDZ())
                    .set(!StringUtils.isEmpty(installTableDto.getGDDH()), Bwrksbdatail::getGddh, installTableDto.getGDDH())
                    .set(!StringUtils.isEmpty(installTableDto.getAZRQ()), Bwrksbdatail::getBwAzrq, date)
                    .set(!StringUtils.isEmpty(installTableDto.getAZRY()), Bwrksbdatail::getBwAzry, installTableDto.getAZRY())
                    .set(!StringUtils.isEmpty(installTableDto.getSBQD()), Bwrksbdatail::getBwSbqd, installTableDto.getSBQD())
                    .set(!StringUtils.isEmpty(installTableDto.getAZFS()), Bwrksbdatail::getAzfs, installTableDto.getAZFS())
                    .set(!StringUtils.isEmpty(installTableDto.getSFNCYS()), Bwrksbdatail::getSfncys, installTableDto.getSFNCYS())
                    .set(!StringUtils.isEmpty(installTableDto.getJYZ()), Bwrksbdatail::getJyz, installTableDto.getJYZ())
                    .set(!StringUtils.isEmpty(installTableDto.getJyzBm()), Bwrksbdatail::getJyzBm, installTableDto.getJyzBm())
                    .set(!StringUtils.isEmpty(installTableDto.getBZBH()), Bwrksbdatail::getBzbh, installTableDto.getBZBH())
                    .set(!StringUtils.isEmpty(installTableDto.getYHDZ()), Bwrksbdatail::getSbazdz, installTableDto.getYHDZ())
                    .set(!StringUtils.isEmpty(installTableDto.getSBYT()), Bwrksbdatail::getSbyt, installTableDto.getSBYT())
                    .set(!StringUtils.isEmpty(installTableDto.getSbytName()), Bwrksbdatail::getSbytName, installTableDto.getSbytName())
                    .set(!StringUtils.isEmpty(installTableDto.getYSXZ()), Bwrksbdatail::getYsxz, installTableDto.getYSXZ())
                    .set(!StringUtils.isEmpty(installTableDto.getYsxzName()), Bwrksbdatail::getYsxzName, installTableDto.getYsxzName())
                    .set(!StringUtils.isEmpty(deptId), Bwrksbdatail::getAzbm, deptId)
                    .set(Bwrksbdatail::getIssyc, 0)
                    .set(Bwrksbdatail::getBwSbzt, 3)
                    .eq(Bwrksbdatail::getBwSbbh, installTableDto.getSBBH()));
        }

        return true;
    }

    /**
     * 获取用水性质
     *
     * @return object
     */
    @Override
    public Map<String, Object> getQualityOrUse() throws Exception {

        Map<String, Object> result = new HashMap<>();


        CommonParam cp = new CommonParam();
        cp.setACTION("query");

        Map map1 = CallAPIUtil.callAPIUtil(cp, "/api/Business/UseNatures");
        //获取用水性质
        Map apiResult = callAPIService.getApiResult(new SyncCommonDto(1, 200), "/api/Business/UseNatures");

        if (ApiCallEnum.STATUS_CODE_OK.getCode().equals(String.valueOf(apiResult.get("statusCode")))) {
            result.put("quality", JSONObject.parseObject(String.valueOf(map1.get("data")), List.class));
        } else {
            result.put("quality", null);
        }

        Map map2 = CallAPIUtil.callAPIUtil(cp, "/api/Business/GetWaterUSEDTYPE");

        if ("0000".equals(map2.get("Code"))) {
            result.put("use", JSONObject.parseObject(String.valueOf(map2.get("data")), List.class));
        } else {
            result.put("use", null);
        }
        return result;
    }

}
