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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tofly.api.UserClent;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.watermeter.custom.dto.NewChangeTableDto;
import com.tofly.watermeter.custom.entity.marketing.CommonParam;
import com.tofly.watermeter.custom.entity.meterBusiness.dto.ChangeTableBatchDto;
import com.tofly.watermeter.custom.entity.meterBusiness.dto.ChangeTableCondition;
import com.tofly.watermeter.custom.entity.meterBusiness.dto.ChangeTableDto;
import com.tofly.watermeter.custom.mapper.meterBusiness.ChangeTableMapper;
import com.tofly.watermeter.custom.service.meterBusiness.ChangeTableService;
import com.tofly.watermeter.custom.service.meterBusiness.export.ExportCommonCodeService;
import com.tofly.watermeter.em.ApiCallEnum;
import com.tofly.watermeter.entity.Bwhbdatail;
import com.tofly.watermeter.entity.Bwrksbdatail;
import com.tofly.watermeter.entity.Qfkhjbxx;
import com.tofly.watermeter.mapper.BwhbdatailMapper;
import com.tofly.watermeter.service.BwhbdatailService;
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 com.tofly.watermeter.util.service.FileUpLoadService;
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 org.springframework.web.multipart.MultipartFile;

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

@Service
@AllArgsConstructor
@Slf4j
public class ChangeTableServiceImpl implements ChangeTableService {

    private final QfkhjbxxService qfkhjbxxService;
    private final BwrksbdatailService bwrksbdatailService;
    private final BwhbdatailService bwhbdatailService;
    private final ChangeTableMapper changeTableMapper;
    private final ExportCommonCodeService exportCommonCodeService;
    private final FileUpLoadService fileUpLoadService;
    private final UserClent userClent;
    private final BwhbdatailMapper bwhbdatailMapper;
    private final CallAPIService callAPIService;

    /**
     * 水表换表
     *
     * @param dto dto
     * @return boolean
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changeTable(ChangeTableDto dto, List<MultipartFile> signature, List<MultipartFile> images) throws Exception {

        if (StringUtils.isEmpty(dto.getYhbh())) {
            throw new ToflyDeniedException("用户编号为空");
        }

        Qfkhjbxx qfkhjbxx = qfkhjbxxService.getOne(Wrappers.<Qfkhjbxx>lambdaQuery()
                .eq(Qfkhjbxx::getYhbh, dto.getYhbh()));

        if (qfkhjbxx != null) {

            String signatureId = null;
            String imageId = null;
            if (CollectionUtil.isNotEmpty(signature)) {
                signatureId = fileUpLoadService.saveFileList(signature, "/xrty/changeTable", "TF_YWPN_BWHBDATAIL_W").toString();
            }
            if ((CollectionUtil.isNotEmpty(images))) {
                imageId = fileUpLoadService.saveFileList(images, "/xrty/changeTable", "TF_YWPN_BWHBDATAIL_W").toString();
            }

            String date = DateUtil.getDateFormat(new Date(), "yyyyMMdd-");

            dto.setAction("QUERY");

            Map map = CallAPIUtil.callAPIUtil(dto, "/api/Business/WaterReplace");

            if (CollectionUtil.isNotEmpty(map)) {
                throw new ToflyDeniedException("调用换表同步接口失败");
            }

            log.info(String.valueOf(map.get("massage")));
            //0000代表添加成功
            if ("0000".equals(map.get("Code"))) {
                Bwhbdatail dbl = new Bwhbdatail();
                dbl.setAzfs(dto.getSbazfs())
                        .setBwBz(dto.getBz())
                        .setBwHblx(Long.valueOf(dto.getSblx()))
                        .setBwKhbh(dto.getYhbh())
                        .setBwHbrq(new Date())
                        .setBwHbry(dto.getHbr())
                        .setBwHbyy(dto.getHbyy())
                        .setBwJbcj(qfkhjbxx.getSbcj())
                        .setBwJblx(qfkhjbxx.getSblx())
                        .setBwJbbh(qfkhjbxx.getSbbh())
                        .setBwJbkj(qfkhjbxx.getSbkj())
                        .setBwJbzd(Long.valueOf(dto.getJbzd()))
                        .setBwJbqd(Long.valueOf(dto.getJbqd()))
                        .setBwKhdz(qfkhjbxx.getYhdz())
                        .setBwKhdh(qfkhjbxx.getLxdh())
                        .setBwKhxm(qfkhjbxx.getYhxm())
                        .setBwHblx(Long.valueOf(dto.getSblx()))
                        .setSqr(dto.getSqr())
                        .setHbsl(dto.getHbsl())
                        .setBwLsbh(date + System.currentTimeMillis())
                        .setJsfs(dto.getHbsljsfs())
                        .setBwXbqd(Long.valueOf(dto.getXbqd()))
                        .setSbm(dto.getSbsbm())
                        .setQfh(dto.getSbqfh())
                        .setBwXbcj(dto.getSbmp())
                        .setBwXblx(dto.getSblx())
                        .setSbxh(dto.getSbxh())
                        .setBwXbkj(dto.getSbkj())
                        .setBwXbbh(dto.getSbbh())
                        .setJbAzrq(qfkhjbxx.getAzrq())
                        .setSignature(signatureId)
                        .setImage(imageId)
                        .setBwHbbm(changeTableMapper.getDeptId(Long.valueOf(dto.getHbr())));
                long betweenDay = cn.hutool.core.date.DateUtil.between(qfkhjbxx.getAzrq(), dbl.getBwHbrq(), DateUnit.DAY);
                dbl.setSyDate(betweenDay);

                bwhbdatailService.save(dbl);

                Long departmentId = userClent.getById(Long.valueOf(dto.getHbr())).getResult().getDepartmentId();

                Bwrksbdatail bwrksbdatail = bwrksbdatailService.getOne(Wrappers.<Bwrksbdatail>lambdaQuery().eq(Bwrksbdatail::getBwSbbh, dto.getSbbh()));

                if (bwrksbdatail != null) {
                    bwrksbdatail.setBwKhbh(dto.getYhbh()).setBwKhxm(qfkhjbxx.getYhxm()).setBwKhdh(qfkhjbxx.getLxdh())
                            .setBwKhdz(qfkhjbxx.getYhdz()).setBwAzry(Long.valueOf(dto.getHbr())).setBwSbqd(Integer.valueOf(dto.getXbqd()))
                            .setAzfs(dto.getSbazfs()).setSfncys(qfkhjbxx.getSfncys()).setJyz(qfkhjbxx.getJyz()).setAzbm(departmentId)
                            .setGddh(qfkhjbxx.getLxdh()).setSbazdz(qfkhjbxx.getYhdz()).setIssyc("1").setMsg("换表成功").setBwSbzt("3").setBwAzrq(new Date());

                    bwrksbdatailService.updateById(bwrksbdatail);
                }

                //旧表改为换表状态
                bwrksbdatailService.update(Wrappers.<Bwrksbdatail>lambdaUpdate()
                        .eq(Bwrksbdatail::getBwSbbh, qfkhjbxx.getSbbh()).set(Bwrksbdatail::getBwSbzt, 9));

            } else {
                throw new ToflyDeniedException(map.get("message").toString());
            }
        } else {
            throw new ToflyDeniedException("用户不存在");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changeTableStaging(ChangeTableDto dto, List<MultipartFile> signature, List<MultipartFile> images) {
        if (StringUtils.isEmpty(dto.getYhbh())) {
            throw new ToflyDeniedException("用户编号为空");
        }
        log.info("换表开始");
        Qfkhjbxx qfkhjbxx = qfkhjbxxService.getOne(Wrappers.<Qfkhjbxx>lambdaQuery()
                .eq(Qfkhjbxx::getYhbh, dto.getYhbh()));

        if (qfkhjbxx != null) {

            String signatureId = null;
            String imageId = null;
            if (CollectionUtil.isNotEmpty(signature)) {
                signatureId = fileUpLoadService.saveFileList(signature, "/home/ftpfile/changeTable", "TF_YWPN_BWHBDATAIL_W").toString();
            }
            if ((CollectionUtil.isNotEmpty(images))) {
                imageId = fileUpLoadService.saveFileList(images, "/home/ftpfile/changeTable", "TF_YWPN_BWHBDATAIL_W").toString();
            }

            String date = DateUtil.getDateFormat(new Date(), "yyyyMMdd-");

            long hbsl = Long.parseLong(dto.getJbzd()) - Long.parseLong(dto.getJbqd());
            Bwhbdatail dbl = new Bwhbdatail();
            if (!StringUtils.isEmpty(qfkhjbxx.getSbbh())) {
                dbl.setBwJbbh(qfkhjbxx.getSbbh());
            }
            if (!StringUtils.isEmpty(qfkhjbxx.getSbcj())) {
                dbl.setBwJbcj(qfkhjbxx.getSbcj());
            }
            if (!StringUtils.isEmpty(qfkhjbxx.getSbkj())) {
                dbl.setBwJbkj(qfkhjbxx.getSbkj());
            }
            if (!StringUtils.isEmpty(qfkhjbxx.getSblx())) {
                dbl.setBwJblx(qfkhjbxx.getSblx());
            }
            dbl.setAzfs(dto.getSbazfs())
                    .setBwBz(dto.getBz())
                    .setRemark(dto.getRemark())
                    .setBwHblx(Long.valueOf(dto.getSblx()))
                    .setBwKhbh(dto.getYhbh())
                    .setBwHbrq(new Date())
                    .setBwHbry(dto.getHbr())
                    .setBwHbyy(dto.getHbyy())
                    .setBwJbzd(Long.valueOf(dto.getJbzd()))
                    .setBwJbqd(Long.valueOf(dto.getJbqd()))
                    .setBwKhdz(qfkhjbxx.getYhdz())
                    .setBwKhdh(qfkhjbxx.getLxdh())
                    .setBwKhxm(qfkhjbxx.getYhxm())
                    .setBwHblx(Long.valueOf(dto.getSblx()))
                    .setSqr(dto.getSqr())
                    .setHbsl(String.valueOf(hbsl))
                    .setBwLsbh(date + System.currentTimeMillis())
                    .setJsfs(dto.getHbsljsfs())
                    .setBwXbqd(Long.valueOf(dto.getXbqd()))
                    .setSbm(dto.getSbsbm())
                    .setQfh(dto.getSbqfh())
                    .setBwXbcj(dto.getSbmp())
                    .setBwXblx(dto.getSblx())
                    .setSbxh(dto.getSbxh())
                    .setBwXbkj(dto.getSbkj())
                    .setBwXbbh(dto.getSbbh())
                    .setJbAzrq(qfkhjbxx.getAzrq())
                    .setSignature(signatureId)
                    .setImage(imageId)
                    .setIsSync(0L)
                    .setModelCode(dto.getModelCode())
                    .setModelName(dto.getModelName())
                    .setLocation(dto.getLocation())
                    .setMeterBox(dto.getMeterBox())
                    .setJyz(qfkhjbxx.getJyz())
                    .setNcys(qfkhjbxx.getSfncys())
                    .setBwHbbm(changeTableMapper.getDeptId(Long.valueOf(dto.getHbr())));

            long betweenDay = cn.hutool.core.date.DateUtil.between(qfkhjbxx.getAzrq(), dbl.getBwHbrq(), DateUnit.DAY);
            dbl.setSyDate(betweenDay);
            log.info(dbl.toString());
            bwhbdatailService.save(dbl);
        }
        return true;
    }

    /**
     * 批量换表
     *
     * @return Boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changeTableBatch(String json, List<MultipartFile> signature, List<MultipartFile> images) {

        ChangeTableBatchDto changeTableBatchDto = JSONObject.parseObject(json, ChangeTableBatchDto.class);

        if (changeTableBatchDto == null || CollectionUtil.isEmpty(changeTableBatchDto.getInfos())) {
            throw new ToflyDeniedException("传入数据为空");
        }

        List<ChangeTableDto> dtoList = changeTableBatchDto.getInfos();

        String signatureId = null;
        String imageId = null;
        if (CollectionUtil.isNotEmpty(signature)) {
            signatureId = fileUpLoadService.saveFileList(signature, "/xrty/changeTable", "TF_YWPN_BWHBDATAIL_W").toString();
        }
        if ((CollectionUtil.isNotEmpty(images))) {
            imageId = fileUpLoadService.saveFileList(images, "/xrty/changeTable", "TF_YWPN_BWHBDATAIL_W").toString();
        }

        Bwhbdatail dbl;

        for (ChangeTableDto dto : dtoList) {
            if (StringUtils.isEmpty(dto.getYhbh())) {
                throw new ToflyDeniedException("用户编号为空");
            }

            dbl = new Bwhbdatail();

            Qfkhjbxx qfkhjbxx = qfkhjbxxService.getOne(Wrappers.<Qfkhjbxx>lambdaQuery()
                    .eq(Qfkhjbxx::getYhbh, dto.getYhbh()));

            String date = DateUtil.getDateFormat(new Date(), "yyyyMMdd-");

            dto.setAction("QUERY");

            log.info(dto.toString());

            Map map = null;
            try {
                map = CallAPIUtil.callAPIUtil(dto, "/api/Business/WaterReplace");
            } catch ( Exception e ) {
                log.info(e.toString());
                e.printStackTrace();
            }
            //同步默认信息
            dbl.setIsSync(0L);
            if (CollectionUtil.isNotEmpty(map)) {
                //0000代表添加成功
                if ("0000".equals(map.get("Code"))) {
                    dbl.setIsSync(1L);
                    Long userId = SecurityUtils.getUserId();

                    dbl.setAzfs(dto.getSbazfs())
                            .setBwBz(dto.getBz())
                            .setBwHblx(dto.getSblx() != null ? Long.valueOf(dto.getSblx()) : null)
                            .setBwKhbh(dto.getYhbh())
                            .setBwHbrq(new Date())
                            .setSignature(signatureId)
                            .setImage(imageId)
                            .setBwHbry(dto.getHbr())
                            .setBwHbyy(dto.getHbyy())
                            .setBwJbzd(dto.getJbzd() != null ? Long.valueOf(dto.getJbzd()) : null)
                            .setBwJbqd(dto.getJbqd() != null ? Long.valueOf(dto.getJbqd()) : null)
                            .setSqr(dto.getSqr())
                            .setHbsl(dto.getHbsl())
                            .setBwLsbh(date + System.currentTimeMillis())
                            .setJsfs(dto.getHbsljsfs())
                            .setBwXbqd(dto.getXbqd() != null ? Long.valueOf(dto.getXbqd()) : null)
                            .setSbm(dto.getSbsbm())
                            .setQfh(dto.getSbqfh())
                            .setBwXbcj(dto.getSbmp())
                            .setBwXblx(dto.getSblx())
                            .setSbxh(dto.getSbxh())
                            .setBwXbkj(dto.getSbkj())
                            .setBwXbbh(dto.getSbbh())
                            .setCreateUser(userId)
                            .setBwHbbm(dto.getHbr() != null ? changeTableMapper.getDeptId(Long.valueOf(dto.getHbr())) : null);

                    if (qfkhjbxx != null) {
                        long betweenDay = cn.hutool.core.date.DateUtil.between(qfkhjbxx.getAzrq(), dbl.getBwHbrq(), DateUnit.DAY);
                        dbl.setBwJbcj(qfkhjbxx.getSbcj())
                                .setBwJblx(qfkhjbxx.getSblx())
                                .setBwJbbh(qfkhjbxx.getSbbh())
                                .setBwJbkj(qfkhjbxx.getSbkj())
                                .setBwKhdz(qfkhjbxx.getYhdz())
                                .setSyDate(betweenDay)
                                .setBwKhdh(qfkhjbxx.getLxdh())
                                .setJbAzrq(qfkhjbxx.getAzrq())
                                .setBwKhxm(qfkhjbxx.getYhxm());
                    }

                    bwhbdatailService.save(dbl);

                    Long departmentId = 0L;
                    if (dto.getHbr() != null) {
                        departmentId = userClent.getById(Long.valueOf(dto.getHbr())).getResult().getDepartmentId();
                    }

                    Bwrksbdatail bwrksbdatail = bwrksbdatailService.getOne(Wrappers.<Bwrksbdatail>lambdaQuery().eq(Bwrksbdatail::getBwSbbh, dto.getSbbh()));

                    if (bwrksbdatail != null) {
                        bwrksbdatail.setBwKhbh(dto.getYhbh())
                                .setBwKhxm(qfkhjbxx != null ? qfkhjbxx.getYhxm() : "")
                                .setBwKhdh(qfkhjbxx != null ? qfkhjbxx.getLxdh() : "")
                                .setBwKhdz(qfkhjbxx != null ? qfkhjbxx.getYhdz() : "")
                                .setBwAzry(StringUtils.isEmpty(dto.getHbr()) ? 0L : Long.parseLong(dto.getHbr()))
                                .setBwSbqd(StringUtils.isEmpty(dto.getXbqd()) ? 0 : Integer.parseInt(dto.getXbqd()))
                                .setAzfs(dto.getSbazfs())
                                .setSfncys(qfkhjbxx != null ? qfkhjbxx.getSfncys() : "")
                                .setJyz(qfkhjbxx != null ? qfkhjbxx.getJyz() : "")
                                .setAzbm(departmentId)
                                .setGddh(qfkhjbxx != null ? qfkhjbxx.getLxdh() : "")
                                .setSbazdz(qfkhjbxx != null ? qfkhjbxx.getYhdz() : "")
                                .setBwSbzt("3").setBwAzrq(new Date());

                        bwrksbdatailService.updateById(bwrksbdatail);
                    }

                    String sbbh = "-1";
                    if (qfkhjbxx != null) {
                        sbbh = qfkhjbxx.getSbbh();
                    }
                    //旧表改为换表状态
                    bwrksbdatailService.update(Wrappers.<Bwrksbdatail>lambdaUpdate()
                            .eq(Bwrksbdatail::getBwSbbh, sbbh).set(Bwrksbdatail::getBwSbzt, 9));
                } else {
                    throw new ToflyDeniedException(map.get("message").toString());
                }
            } else {
                throw new ToflyDeniedException("调用换表同步接口失败");
            }

        }
        return true;
    }

    /**
     * 查询安装水表用户
     *
     * @param dto 查询条件
     * @return list
     */
    @Override
    public Page<Map> queryInfo(Page page, String dto, String sbkj, String sblx, String sbcj) {
        return qfkhjbxxService.page(page, Wrappers.<Qfkhjbxx>lambdaQuery()
                .ne(Qfkhjbxx::getYhzt, 9)
                .eq(!StringUtils.isEmpty(sbcj), Qfkhjbxx::getSbcj, sbcj)
                .eq(!StringUtils.isEmpty(sbkj), Qfkhjbxx::getSbkj, sbkj)
                .eq(!StringUtils.isEmpty(sblx), Qfkhjbxx::getSblx, sblx)
                .and(!StringUtils.isEmpty(dto), v -> v.like(Qfkhjbxx::getYhbh, dto)
                        .or().like(Qfkhjbxx::getYhxm, dto)
                        .or().like(Qfkhjbxx::getYhdz, dto)
                        .or().like(Qfkhjbxx::getLxdh, dto)
                        .or().like(Qfkhjbxx::getSbbh, dto)));
    }

    @Override
    public List<Map> countChangeTable(HttpServletResponse response, ChangeTableCondition dto) {
        List<Map> maps = changeTableMapper.countChangeTable(dto);
        if (dto.getExport() != null && dto.getExport() == 1) {
            exportCommonCodeService.exportCode(response, "countChangeTableService", maps);
        }
        return maps;
    }

    @Override
    public Page<Map> queryChangeTable(Page page, HttpServletResponse response, ChangeTableCondition dto) {
        Page<Map> mapPage = changeTableMapper.queryChangeTable(page, dto);
        List<Map> records = mapPage.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            for (Map map : records) {
                String image = String.valueOf(map.get("image"));
                map.put("imagePath", !StringUtils.isEmpty(image) ? bwhbdatailMapper.getImagePath(image) : null);

            }
        }
        if (dto.getExport() == 1) {
            exportCommonCodeService.exportCode(response, "queryChangeTableService", records);
        }
        return mapPage;
    }

    /**
     * 批量添加暂存接口
     *
     * @param json      数据
     * @param signature 签名
     * @param images    图片
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchInsertStaging(String json, List<MultipartFile> signature, List<MultipartFile> images) {

        ChangeTableBatchDto changeTableBatchDto = JSONObject.parseObject(json, ChangeTableBatchDto.class);

        if (changeTableBatchDto == null || CollectionUtil.isEmpty(changeTableBatchDto.getInfos())) {
            throw new ToflyDeniedException("传入数据为空");
        }
        Set<ChangeTableDto> dtoList = new HashSet<>(changeTableBatchDto.getInfos());
//        List<ChangeTableDto> dtoList = changeTableBatchDto.getInfos();

        String signatureId = null;
        String imageId = null;
        if (CollectionUtil.isNotEmpty(signature)) {
            signatureId = fileUpLoadService.saveFileList(signature, "/xrty/changeTable", "TF_YWPN_BWHBDATAIL_W").toString();
        }
        if ((CollectionUtil.isNotEmpty(images))) {
            imageId = fileUpLoadService.saveFileList(images, "/xrty/changeTable", "TF_YWPN_BWHBDATAIL_W").toString();
        }

        Bwhbdatail dbl;

        for (ChangeTableDto dto : dtoList) {
            if (StringUtils.isEmpty(dto.getYhbh())) {
                throw new ToflyDeniedException("用户编号为空");
            }

            dbl = new Bwhbdatail();

            Qfkhjbxx qfkhjbxx = qfkhjbxxService.getOne(Wrappers.<Qfkhjbxx>lambdaQuery()
                    .eq(Qfkhjbxx::getYhbh, dto.getYhbh()));

            String date = DateUtil.getDateFormat(new Date(), "yyyyMMdd-");
            //同步默认信息
            //添加默认状态未同步
            dbl.setIsSync(0L);
            Long userId = SecurityUtils.getUserId();
            dbl.setAzfs(dto.getSbazfs())
                    .setBwBz(dto.getBz())
                    .setRemark(dto.getRemark())
                    .setBwHblx(dto.getSblx() != null ? Long.valueOf(dto.getSblx()) : null)
                    .setBwKhbh(dto.getYhbh())
                    .setBwHbrq(new Date())
                    .setSignature(signatureId)
                    .setImage(imageId)
                    .setBwHbry(dto.getHbr())
                    .setBwHbyy(dto.getHbyy())
                    .setBwJbzd(dto.getJbzd() != null ? Long.valueOf(dto.getJbzd()) : null)
                    .setBwJbqd(dto.getJbqd() != null ? Long.valueOf(dto.getJbqd()) : null)
                    .setSqr(dto.getSqr())
                    .setHbsl(dto.getHbsl())
                    .setBwLsbh(date + System.currentTimeMillis())
                    .setJsfs(dto.getHbsljsfs())
                    .setBwXbqd(dto.getXbqd() != null ? Long.valueOf(dto.getXbqd()) : null)
                    .setSbm(dto.getSbsbm())
                    .setQfh(dto.getSbqfh())
                    .setBwXbcj(dto.getSbmp())
                    .setBwXblx(dto.getSblx())
                    .setSbxh(dto.getSbxh())
                    .setBwXbkj(dto.getSbkj())
                    .setBwXbbh(dto.getSbbh())
                    .setCreateUser(userId)
                    .setBwHbbm(dto.getHbr() != null ? changeTableMapper.getDeptId(Long.valueOf(dto.getHbr())) : null);

            if (qfkhjbxx != null) {
                long betweenDay = cn.hutool.core.date.DateUtil.between(qfkhjbxx.getAzrq(), dbl.getBwHbrq(), DateUnit.DAY);
                if (!StringUtils.isEmpty(qfkhjbxx.getSbbh())) {
                    dbl.setBwJbbh(qfkhjbxx.getSbbh());
                }
                if (!StringUtils.isEmpty(qfkhjbxx.getSbcj())) {
                    dbl.setBwJbcj(qfkhjbxx.getSbcj());
                }
                if (!StringUtils.isEmpty(qfkhjbxx.getSbkj())) {
                    dbl.setBwJbkj(qfkhjbxx.getSbkj());
                }
                if (!StringUtils.isEmpty(qfkhjbxx.getSblx())) {
                    dbl.setBwJblx(qfkhjbxx.getSblx());
                }
                dbl.setBwKhdz(qfkhjbxx.getYhdz())
                        .setSyDate(betweenDay)
                        .setBwKhdh(qfkhjbxx.getLxdh())
                        .setJbAzrq(qfkhjbxx.getAzrq())
                        .setBwKhxm(qfkhjbxx.getYhxm());
            }

            bwhbdatailService.save(dbl);
        }
        return true;
    }

    /**
     * 新水表接口
     *
     * @param ids 换表id
     * @return boolean
     */
    @Override
    public boolean newChangeTable(String ids, Long state, String auditOpinion) {
        List<Bwhbdatail> changeTableList = bwhbdatailService.list(Wrappers.<Bwhbdatail>lambdaQuery()
                .in(Bwhbdatail::getId, Arrays.asList(ids.split(","))));

        Long userId = SecurityUtils.getUserId();

//        ChangeTableDto dto;
        NewChangeTableDto nctd;
        for (Bwhbdatail change : changeTableList) {
            //无需同步,保存审核意见即可
            if (state != null && state == 3) {
                change.setIsSync(state);
                change.setAuditOpinion(auditOpinion);
                bwhbdatailService.updateById(change);
                continue;
            }
            //根据用户编号获取用户信息
            Map<String,String> params = new HashMap<>(1);
            params.put("code",change.getBwKhbh());
            Map userInfoMap = callAPIService.getApiResult(params, "/api/v1/koi/replace/meter/record/get");

            Long bwJbzd = change.getBwJbzd();
            if (ApiCallEnum.STATUS_CODE_OK.getCode().equals(String.valueOf(userInfoMap.get("statusCode")))){
                //查询的客户信息
                Map clientMap = JSONObject.parseObject(String.valueOf(userInfoMap.get("data")), Map.class);
                if (clientMap != null && clientMap.size() > 0){
                    //最后抄表读数
                    Long latestReadScale = Long.valueOf(String.valueOf(clientMap.get("latestReadScale")));

                    if (bwJbzd < latestReadScale){
                        throw new ToflyDeniedException("必须大于或等于最后抄表读数，请重新修改水表止度");
                    }
                    //用户id
                    String id = String.valueOf(clientMap.get("id"));
                    nctd = new NewChangeTableDto();
                    nctd.setUserId(id);
                    nctd.setChangerName("系统设计师");
                    nctd.setApplicantName(change.getSqr());
                    nctd.setCaliberCode("0"+change.getBwXbkj());
                    nctd.setLocation(change.getLocation());
                    nctd.setIsOrder(0L);
                    nctd.setMeterBox(change.getMeterBox());
                    nctd.setMeterCode(change.getBwXbbh());
                    nctd.setMeteringBillingDateType(change.getJsfs());
                    nctd.setMeterType(change.getBwXblx());
                    nctd.setOldEndSacle(String.valueOf(bwJbzd));
                    nctd.setReadWater(bwJbzd - latestReadScale);
                    nctd.setReason(change.getBwHbyy());
                    nctd.setStartSacle(change.getBwXbqd());
                    nctd.setTime(change.getBwHbrq().getTime());
                    nctd.setSpecCode(change.getModelCode());
                    nctd.setVendorCode(change.getBwXbcj());
                    log.info("换表同步数据为：" + JSONObject.toJSONString(nctd));
                    Map apiResult = callAPIService.getApiResult(nctd, "/api/v1/koi/replace/meter/record/create");
                    String msg;
                    if (ApiCallEnum.STATUS_CODE_OK.getCode().equals(String.valueOf(apiResult.get("statusCode")))){
                        List<Bwrksbdatail> bwrksbdatailList = bwrksbdatailService.list(Wrappers.<Bwrksbdatail>lambdaQuery().eq(Bwrksbdatail::getBwSbbh, nctd.getMeterCode()));
                        if (CollectionUtil.isEmpty(bwrksbdatailList)) {
                            continue;
                        }
                        Bwrksbdatail bwrksbdatail = bwrksbdatailList.get(0);
                        if (bwrksbdatail != null) {
                            bwrksbdatail.setBwKhbh(change.getBwKhbh())
                                    .setBwKhxm(change.getBwKhxm())
                                    .setBwKhdh(change.getBwKhbh())
                                    .setBwKhdz(change.getBwKhdz())
                                    .setBwAzry(StringUtils.isEmpty(change.getBwHbry()) ? 0L : Long.parseLong(change.getBwHbry()))
                                    .setBwSbqd(StringUtils.isEmpty(change.getBwXbqd()) ? 0 : Integer.parseInt(String.valueOf(change.getBwXbqd())))
                                    .setAzfs(change.getAzfs())
                                    .setSfncys(change.getNcys())
                                    .setJyz(change.getJyz())
                                    .setAzbm(userClent.getById(userId).getResult().getDepartmentId())
                                    .setGddh(change.getBwKhdh())
                                    .setSbazdz(change.getBwKhdz())
                                    .setBwSbzt("3").setBwAzrq(change.getBwHbrq());

                            bwrksbdatailService.updateById(bwrksbdatail);
                        }
                        state = 1L;
                        msg = "同步成功";
                    }else {
                        state = 2L;
                        msg = String.valueOf(apiResult.get("message"));
                    }
                    bwhbdatailService.update(Wrappers.<Bwhbdatail>lambdaUpdate()
                            .eq(Bwhbdatail::getId, change.getId())
                            .set(!StringUtils.isEmpty(auditOpinion), Bwhbdatail::getAuditOpinion, auditOpinion)
                            .set(Bwhbdatail::getIsSync, state)
                            .set(Bwhbdatail::getMsg, msg));
                }else {
                    throw new ToflyDeniedException("营销系统未查询到用户编号：" + change.getBwKhbh() + " 的用户");
                }

            }
            /*dto = new ChangeTableDto();

            dto.setAction("query").setHbsl(change.getHbsl())
                    .setBz(change.getBwBz())
                    .setCzy(userId.toString())
                    .setHbr(change.getBwHbry())
                    .setHbrq(DateUtil.parseDateToStr("yyyyMMdd", change.getBwHbrq()))
                    .setHbsljsfs(change.getJsfs())
                    .setHbyy(change.getBwHbyy())
                    .setJbqd(String.valueOf(change.getBwJbqd()))
                    .setJbzd(String.valueOf(bwJbzd))
                    .setSbazfs(change.getAzfs())
                    .setSbbh(change.getBwXbbh())
                    .setSbkj(change.getBwXbkj())
                    .setSblx(change.getBwXblx())
                    .setSbmp(change.getBwXbcj())
                    .setSbqfh(change.getQfh())
                    .setSbsbm(change.getSbm())
                    .setSbxh(change.getSbxh())
                    .setSqr(change.getSqr())
                    .setXbqd(String.valueOf(change.getBwXbqd()))
                    .setYhbh(change.getBwKhbh());

            Map map = null;
            try {
                log.info("换表同步数据为：" + JSONObject.toJSONString(dto));
                map = CallAPIUtil.callAPIUtil(dto, "/api/Business/WaterReplace");
            } catch ( Exception e ) {
                e.printStackTrace();
            }
            String msg = null;
            if (CollectionUtil.isEmpty(map)) {
                throw new ToflyDeniedException("接口调用失败");
            } else {
                if ("0000".equals(map.get("Code"))) {
                    Long departmentId = 0L;
                    if (dto.getHbr() != null) {
                        departmentId = userClent.getById(Long.valueOf(dto.getHbr())).getResult().getDepartmentId();
                    }
                    List<Bwrksbdatail> bwrksbdatailList = bwrksbdatailService.list(Wrappers.<Bwrksbdatail>lambdaQuery().eq(Bwrksbdatail::getBwSbbh, dto.getSbbh()));
                    if (CollectionUtil.isEmpty(bwrksbdatailList)) {
                        continue;
                    }
                    Bwrksbdatail bwrksbdatail = bwrksbdatailList.get(0);
                    if (bwrksbdatail != null) {
                        bwrksbdatail.setBwKhbh(dto.getYhbh())
                                .setBwKhxm(change.getBwKhxm())
                                .setBwKhdh(change.getBwKhbh())
                                .setBwKhdz(change.getBwKhdz())
                                .setBwAzry(StringUtils.isEmpty(change.getBwHbry()) ? 0L : Long.parseLong(change.getBwHbry()))
                                .setBwSbqd(StringUtils.isEmpty(change.getBwXbqd()) ? 0 : Integer.parseInt(String.valueOf(change.getBwXbqd())))
                                .setAzfs(change.getAzfs())
                                .setSfncys(change.getNcys())
                                .setJyz(change.getJyz())
                                .setAzbm(departmentId)
                                .setGddh(change.getBwKhdh())
                                .setSbazdz(change.getBwKhdz())
                                .setBwSbzt("3").setBwAzrq(change.getBwHbrq());

                        bwrksbdatailService.updateById(bwrksbdatail);
                    }
                    state = 1L;
                    msg = "同步成功";
                } else {
                    state = 2L;
                    msg = String.valueOf(map.get("message"));
                }
                bwhbdatailService.update(Wrappers.<Bwhbdatail>lambdaUpdate()
                        .eq(Bwhbdatail::getId, change.getId())
                        .set(!StringUtils.isEmpty(auditOpinion), Bwhbdatail::getAuditOpinion, auditOpinion)
                        .set(Bwhbdatail::getIsSync, state)
                        .set(Bwhbdatail::getMsg, msg));
            }*/
        }

        return true;
    }

    /**
     * 水表换表信息修改
     *
     * @param signatures 签名
     * @param images     图片
     * @param datail     换表信息
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateChangeTable(List<MultipartFile> signatures, List<MultipartFile> images, Bwhbdatail datail) {
        if (!StringUtils.isEmpty(datail.getBwKhbh())) {
            Qfkhjbxx info = qfkhjbxxService.getOne(Wrappers.<Qfkhjbxx>lambdaQuery()
                    .eq(Qfkhjbxx::getYhbh, datail.getBwKhbh()));
            datail.setBwKhxm(info.getYhxm());
            datail.setBwKhdz(info.getYhdz());
            datail.setBwKhdh(info.getLxdh());
        }
        if (!StringUtils.isEmpty(datail.getBwXbbh())) {
            Bwrksbdatail tableInfo = bwrksbdatailService.getOne(Wrappers.<Bwrksbdatail>lambdaQuery()
                    .eq(Bwrksbdatail::getBwSbbh, datail.getBwXbbh()));
            if (tableInfo != null) {
                datail.setBwXbcj(String.valueOf(tableInfo.getBwSbcj()));
                datail.setBwXbkj(String.valueOf(tableInfo.getBwSbkj()));
                datail.setBwXblx(String.valueOf(tableInfo.getBwSblx()));
            }

        }
        if (!StringUtils.isEmpty(datail.getBwJbbh())) {
            Bwrksbdatail tableInfo = bwrksbdatailService.getOne(Wrappers.<Bwrksbdatail>lambdaQuery()
                    .eq(Bwrksbdatail::getBwSbbh, datail.getBwJbbh()));
            if (tableInfo != null) {
                datail.setBwJbcj(String.valueOf(tableInfo.getBwSbcj()));
                datail.setBwJbkj(String.valueOf(tableInfo.getBwSbkj()));
                datail.setBwJblx(String.valueOf(tableInfo.getBwSblx()));
            }

        }
        String signatureId = null;
        String imageId = null;
        if (CollectionUtil.isNotEmpty(signatures)) {
            signatureId = fileUpLoadService.saveFileList(signatures, "/xrty/changeTable", "TF_YWPN_BWHBDATAIL_W").toString();
        }
        if ((CollectionUtil.isNotEmpty(images))) {
            imageId = fileUpLoadService.saveFileList(images, "/xrty/changeTable", "TF_YWPN_BWHBDATAIL_W").toString();
        }

        if (!StringUtils.isEmpty(signatureId)) {
            datail.setSignature(signatureId);
        }

        String image = datail.getImage();
        if (!StringUtils.isEmpty(imageId)) {
            if (StringUtils.isEmpty(image)) {
                datail.setImage(imageId);
            } else {
                datail.setImage(StringUtils.isEmpty(image) ? imageId : image + "," + imageId);
            }
        }
        log.info("换表数据修改数据为：" + datail.toString());
        return bwhbdatailService.updateById(datail);
    }

    /**
     * 换表原因
     *
     * @return list
     */
    @Override
    public List<Map<String, String>> changeTableCause() throws Exception {
        // 给定的 JSON 数据
        String json = "[{\"hbyyBm\":\"1\",\"hbyyMc\":\"表坏\"},{\"hbyyBm\":\"2\",\"hbyyMc\":\"改口径\"},{\"hbyyBm\":\"3\",\"hbyyMc\":\"虚拟换表\"},{\"hbyyBm\":\"5\",\"hbyyMc\":\"周检轮换\"},{\"hbyyBm\":\"4\",\"hbyyMc\":\"增容\"},{\"hbyyBm\":\"12\",\"hbyyMc\":\"检定不合格\"},{\"hbyyBm\":\"8\",\"hbyyMc\":\"字轮不进位\"},{\"hbyyBm\":\"9\",\"hbyyMc\":\"倒转/倒装\"},{\"hbyyBm\":\"11\",\"hbyyMc\":\"远传数据异常\"},{\"hbyyBm\":\"7\",\"hbyyMc\":\"水表不走\"},{\"hbyyBm\":\"10\",\"hbyyMc\":\"封铅遗失\"},{\"hbyyBm\":\"6\",\"hbyyMc\":\"表黑/表雾/错针/表炸/人为破坏\"}]";
        // 使用 Gson 将 JSON 数据转换为 List<Map<String, String>>
        List<Map<String, String>> mapList = new Gson().fromJson(json, new TypeToken<List<Map<String, String>>>() {
        }.getType());
        return mapList;

//        CommonParam cp = new CommonParam();
//        cp.setACTION("query");
//        Map map = CallAPIUtil.callAPIUtil(cp, "api/Business/WaterReplaceReason");
//        if (CollectionUtil.isNotEmpty(map)) {
//            if ("0000".equals(map.get("Code"))) {
//                List<Map> data = JSONObject.parseArray(map.get("data").toString(), Map.class);
//                Map m;
//                List<Map> result = new ArrayList<>();
//                if (CollectionUtil.isNotEmpty(data)) {
//                    for (Map datum : data) {
//                        m = new HashMap();
//                        m.put("hbyyBm", datum.get("BM"));
//                        m.put("hbyyMc", datum.get("MC"));
//                        result.add(m);
//                    }
//                }
//                return result;
//            } else {
//                throw new ToflyDeniedException(String.valueOf(map.get("message")));
//            }
//        } else {
//            throw new ToflyDeniedException("获取换表原因失败");
//        }
    }

    /**
     * 根据类型统计换表信息
     *
     * @param dto sto
     * @return list
     */
    @Override
    public List<Map> changeTableCountByType(ChangeTableCondition dto) {
        return changeTableMapper.changeTableCountByType(dto);
    }

    /**
     * 根据厂家获取型号
     *
     * @param factory 厂家id
     * @return list
     */
    @Override
    public List<Map> getModelInfo(String factory) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("factoryCode", factory);
        Map apiResult = callAPIService.getApiResult(param, "/api/v1/fish/meter/spec/find/name");
        if (ApiCallEnum.STATUS_CODE_OK.getCode().equals(String.valueOf(apiResult.get("statusCode")))){
            return JSONObject.parseArray(String.valueOf(apiResult.get("data")),Map.class);
        }
        return null;
    }

}
