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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
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.ftp.config.FtpUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.watermeter.config.FilePathBean;
import com.tofly.watermeter.custom.entity.CustomGzSb;
import com.tofly.watermeter.custom.entity.CustomSearch;
import com.tofly.watermeter.custom.entity.ZySbInfo;
import com.tofly.watermeter.custom.mapper.ZySbInfoMapper;
import com.tofly.watermeter.custom.service.ZySbInfoService;
import com.tofly.watermeter.entity.*;
import com.tofly.watermeter.service.*;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author by Wangjieliu
 * @date 2021/3/17.
 */
@Service
@AllArgsConstructor
public class ZySbInfoServiceImpl extends ServiceImpl<ZySbInfoMapper, ZySbInfo> implements ZySbInfoService {

    private final TfYwpnBwsjblglService sjblService;
    private final FilePathBean filePathBean;
    private final FileService fileService;
    private final BwzysbjddatailService zyjdService;
    private final BwzjbcjdatailService zjcjService;
    private final BwrksbdatailService bwrksbdatail;
    private final BwgzbcjdatailService gzService;
    private final BwckdatailService ckService;
    private final BwsbyjglService yjglService;
    private final BwsjdatailService bwsjdatailService;
    private final QfkhjbxxService qfkhjbxxService;


    @Override
    public boolean insert(TfYwpnBwsjblgl bwcjbl) {
        TfYwpnBwsjblgl cjbl = sjblService.getOne(Wrappers.<TfYwpnBwsjblgl>lambdaQuery()
                .eq(TfYwpnBwsjblgl::getSbkj, bwcjbl.getSbkj()));
        if (StringUtil.isNotNull(cjbl)) {
            throw new ToflyDeniedException("已有口径：" + cjbl.getSbkjName() + "的比例配置；抽检比例为：" + cjbl.getSjbl() + "%");
        }
        return sjblService.save(bwcjbl);
    }

    @Override
    public boolean deleteConfig(Long sbkj) {
        //如果已经有存在入库首检的记录，则不能删除这条首检比例配置
        int kjNum = bwsjdatailService.count(Wrappers.<Bwsjdatail>lambdaQuery().eq(Bwsjdatail::getBwSbkj, sbkj));
        if (0 != kjNum) {
            throw new ToflyDeniedException("该首检比例配置不能删除");
        }
        sjblService.remove(Wrappers.<TfYwpnBwsjblgl>lambdaQuery().eq(TfYwpnBwsjblgl::getSbkj, sbkj));
        return true;
    }

    @Override
    public IPage getConfig(Page page, TfYwpnBwsjblgl sjbl) {
        return sjblService.page(page, Wrappers.query(sjbl).orderByAsc("sbkj"));
    }

    @Override
    public boolean updateConfig(TfYwpnBwsjblgl sjbl) {
        Integer id = sjbl.getId();
        String kjbm = sjbl.getKjbm();
        Long sbkj = sjbl.getSbkj();
        Integer bl = sjbl.getSjbl();

        return sjblService.update(Wrappers.<TfYwpnBwsjblgl>lambdaUpdate()
                .eq(TfYwpnBwsjblgl::getId, id).set(StringUtil.isNotEmpty(kjbm), TfYwpnBwsjblgl::getKjbm, kjbm)
                .set(StringUtil.isNotNull(sbkj), TfYwpnBwsjblgl::getSbkj, sbkj)
                .set(StringUtil.isNotNull(bl), TfYwpnBwsjblgl::getSjbl, bl)
                .set(TfYwpnBwsjblgl::getCreateUser, SecurityUtils.getUserId()));
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertZyjg(Bwzysbjddatail bwzysbjddatail, HttpServletRequest request) {

        //这是增加争议鉴定
        if (StringUtil.isNull(bwzysbjddatail.getId())) {

            String gbbh = bwzysbjddatail.getBwGdbh();

            if (StringUtils.isEmpty(gbbh)) {
                throw new ToflyDeniedException("工单编号不允许为空");
            }

            StringBuilder fileIds = zyFile(request);
            if (fileIds.length() > 0) {
                bwzysbjddatail.setBwFileid(fileIds.substring(0, fileIds.length() - 1));
            }
            //根据水表编号查询，该水表是否已安装，没有安装不能争议鉴定
            Bwrksbdatail sbDetail = bwrksbdatail.getOne(Wrappers.<Bwrksbdatail>lambdaQuery()
                    .eq(Bwrksbdatail::getBwSbbh, bwzysbjddatail.getSbbh())
                    .select(Bwrksbdatail::getBwSbzt, Bwrksbdatail::getBwKhbh, Bwrksbdatail::getBwKhdh,
                            Bwrksbdatail::getBwKhdz, Bwrksbdatail::getBwKhxm, Bwrksbdatail::getBwSbcj,
                            Bwrksbdatail::getBwSblx, Bwrksbdatail::getBwSbkj));

            if (sbDetail != null) {
                bwzysbjddatail.setBwYhbh(sbDetail.getBwKhbh());
                bwzysbjddatail.setBwYhdz(sbDetail.getBwKhdz());
                bwzysbjddatail.setBwYhxm(sbDetail.getBwKhxm());
                bwzysbjddatail.setBwLxdh(sbDetail.getBwKhdh());
                bwzysbjddatail.setBwSbcj(sbDetail.getBwSbcj());
                bwzysbjddatail.setBwSbkj(sbDetail.getBwSbkj());
                bwzysbjddatail.setBwSblx(sbDetail.getBwSblx());
            } else {
                List<Qfkhjbxx> clientInfo = qfkhjbxxService.list(Wrappers.<Qfkhjbxx>lambdaQuery()
                        .eq(Qfkhjbxx::getYhbh, bwzysbjddatail.getBwYhbh())
                        .eq(Qfkhjbxx::getSbbh, bwzysbjddatail.getSbbh()));
                if (clientInfo == null || clientInfo.isEmpty()){
                    throw new ToflyDeniedException("请确认该客户是否存在或已安装水表");
                }else {
                    Qfkhjbxx info = clientInfo.get(0);
                    bwzysbjddatail.setBwYhbh(info.getYhbh());
                    bwzysbjddatail.setBwYhdz(info.getYhdz());
                    bwzysbjddatail.setBwYhxm(info.getYhxm());
                    bwzysbjddatail.setBwLxdh(info.getLxdh());
                    bwzysbjddatail.setBwSbcj(Long.parseLong(info.getSbcj()));
                    bwzysbjddatail.setBwSbkj(Long.parseLong(info.getSbkj()));
                    bwzysbjddatail.setBwSblx(Long.parseLong(info.getSblx()));
                }
            }
            zyjdService.save(bwzysbjddatail);
            //修改工单
            ckService.updateGdZt(gbbh, "4");
            return true;
        }//修改争议鉴定
        else {
            //先查询该争议鉴定的图片，然后将其删除
            Bwzysbjddatail detail = zyjdService.getOne(Wrappers.<Bwzysbjddatail>lambdaQuery()
                    .eq(Bwzysbjddatail::getId, bwzysbjddatail.getId()).select(Bwzysbjddatail::getBwFileid));
            if (StringUtil.isNotNull(detail)) {
                //文件ID
                List<String> fileIds = Arrays.asList(detail.getBwFileid().split(","));
                //查询文件路径
                List<String> filePaths = fileService.list(Wrappers.<File>lambdaQuery().in(File::getId, fileIds)
                        .select(File::getFilePath)).stream().map(File::getFilePath).collect(Collectors.toList());
                filePaths.forEach(FtpUtil::deleteFile);
            }
            //文件
            StringBuilder fileIds = zyFile(request);
            if (fileIds.length() > 0) {
                bwzysbjddatail.setBwFileid(fileIds.substring(0, fileIds.length() - 1));
            }
            String fileId = bwzysbjddatail.getBwFileid();
            String sjly = bwzysbjddatail.getBwSjly();
            String jyjg = bwzysbjddatail.getBwJyjg();
            Date jyrq = bwzysbjddatail.getBwJyrq();
            String jyry = bwzysbjddatail.getBwJyry();
            String sbbh = bwzysbjddatail.getSbbh();
            String bz = bwzysbjddatail.getBwBz();
            //修改数据
            return zyjdService.update(Wrappers.<Bwzysbjddatail>lambdaUpdate()
                    .eq(Bwzysbjddatail::getId, bwzysbjddatail.getId()).set(StringUtil.isNotEmpty(fileId), Bwzysbjddatail::getBwFileid, fileId)
                    .set(StringUtil.isNotEmpty(sjly), Bwzysbjddatail::getBwSjly, sjly).set(StringUtil.isNotEmpty(jyjg), Bwzysbjddatail::getBwJyjg, jyjg)
                    .set(StringUtil.isNotNull(jyrq), Bwzysbjddatail::getBwJyrq, jyrq).set(StringUtil.isNotEmpty(jyry), Bwzysbjddatail::getBwJyry, jyry)
                    .set(StringUtil.isNotEmpty(sbbh), Bwzysbjddatail::getSbbh, sbbh).set(StringUtil.isNotEmpty(bz), Bwzysbjddatail::getBwBz, bz));

        }
    }

    public StringBuilder zyFile(HttpServletRequest request) {
        MultiValueMap<String, MultipartFile> files = ((MultipartHttpServletRequest) request).getMultiFileMap();
        StringBuilder fileIds = new StringBuilder("");
        files.forEach((k, v) -> {
            //保存照片
            v.forEach(file -> {
                //文件名
                String fileName = file.getOriginalFilename();
                if (!"".equals(fileName)) {
                    //文件路径
                    String filePath = filePathBean.getZyCheck() + IdWorker.getIdStr() + fileName.substring(fileName.lastIndexOf("."));
                    boolean b = FtpUtil.uploadFile2Ftp(file, filePath);
                    if (b) {
                        File localFile = new File();
                        localFile.setFilePath(filePath);
                        localFile.setFileName(fileName);
                        localFile.setOtherName(IdWorker.getIdStr() + fileName.substring(fileName.lastIndexOf(".")));
                        localFile.setTableName("TF_YWPN_BWZYSBJDDATAIL_W");//关联表名称
//                        localFile.setTableId(bwzysbjddatail.getId());
                        //获取后缀
                        String suffix = fileName.substring(fileName.lastIndexOf("."));
                        localFile.setFileFormat(suffix);
                        localFile.setFileSize(file.getSize() + "kb");
                        fileService.save(localFile);
                        //获得文件ID
                        fileIds.append(localFile.getId() + ",");
                    }
                }
            });
        });
        return fileIds;
    }

    @Override
    public boolean insertZy(Bwzysbjddatail bwzysbjddatail) {
        return zyjdService.save(bwzysbjddatail);
    }

    @Override
    public IPage getZy(Page page, Bwzysbjddatail bwzysbjddatail) {
        return baseMapper.getZy(page, bwzysbjddatail);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteZy(Long id) {
        //查询文件ID
        String fileIds = zyjdService.getOne(Wrappers.<Bwzysbjddatail>lambdaQuery().eq(Bwzysbjddatail::getId, id).select(Bwzysbjddatail::getBwFileid)).getBwFileid();
        String ids = fileIds.substring(0, fileIds.length() - 1);
        List<String> list = Arrays.asList(ids.split(","));
        List<File> files = fileService.listByIds(list);
        //删除服务器中的文件
        files.forEach(k -> {
            FtpUtil.deleteFile(k.getFilePath());
        });
        //删除数据库文件记录
        fileService.removeByIds(list);
        //删除争议检定记录
        return zyjdService.removeById(id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delSpot(Long id) {
        //查询水表ID
        Bwzjbcjdatail sbInfo = zjcjService.getOne(Wrappers.<Bwzjbcjdatail>lambdaQuery().eq(Bwzjbcjdatail::getId, id)
                .select(Bwzjbcjdatail::getSbid, Bwzjbcjdatail::getBwSbbh));
        //修改水表状态；这里暂时不知道修改成什么状态，业务也没有提及
        zjcjService.removeById(id);
        //修改移交检查状态
        yjglService.update(Wrappers.<Bwsbyjgl>lambdaUpdate()
                .eq(Bwsbyjgl::getSbzsbh, sbInfo.getBwSbbh()).set(Bwsbyjgl::getCheckFlag, "0"));
        return true;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertSpot(Bwzjbcjdatail bwzjbcjdatail) {
        //判断合格与不合格
        if (StringUtil.isEmpty(bwzjbcjdatail.getBwJyjg())) {
            throw new ToflyDeniedException("请正确填写是否合格");
        }

        //根据水表编号查询得到水表ID
        Bwrksbdatail bwrksbdatail = getId(bwzjbcjdatail.getBwSbbh());
        Long sbId = null;
        if (StringUtil.isNotNull(bwrksbdatail)) {
            sbId = bwrksbdatail.getId();
//            String sbzt = bwrksbdatail.getBwSbzt();
            //存在外来表周检情况
//        if (StringUtil.isNull(sbId)) {
//            throw new ToflyDeniedException("请正确输入水表编号");
//        }
            //如果是本系统的水表；需要验证状态
/*            if (!"61".equals(sbzt)) {
//                if ("950".equals(sbzt)){
//                    throw new ToflyDeniedException("该水表已维修好，不用进行周检(抽检)");
//                }
                throw new ToflyDeniedException("请正确填写需要周检(抽检)水表");
            }*/
        }

        Bwzjbcjdatail cj = new Bwzjbcjdatail();
        cj.setBwBz(bwzjbcjdatail.getBwBz());
        cj.setBwSbbh(bwzjbcjdatail.getBwSbbh());
        cj.setBwQ1(bwzjbcjdatail.getBwQ1());
        cj.setBwQ2(bwzjbcjdatail.getBwQ2());
        cj.setBwQ3(bwzjbcjdatail.getBwQ3());
        cj.setBwJyjg(bwzjbcjdatail.getBwJyjg());
        cj.setSbid(sbId);
        cj.setBwSbcj(bwzjbcjdatail.getBwSbcj());
        cj.setBwSbkj(bwzjbcjdatail.getBwSbkj());
        cj.setBwSblx(bwzjbcjdatail.getBwSblx());
        zjcjService.save(cj);
        //修改水表状态
//        if ("2".equals(bwzjbcjdatail.getBwJyjg())){
//            bwrksbdatail.update(Wrappers.<Bwrksbdatail>lambdaUpdate().eq(Bwrksbdatail::getId,sbId).set(Bwrksbdatail::getBwSbzt,"61"));
//        }
        yjglService.update(Wrappers.<Bwsbyjgl>lambdaUpdate().eq(Bwsbyjgl::getSbzsbh, bwzjbcjdatail.getBwSbbh())
                .set(Bwsbyjgl::getCheckFlag, "1"));
        return true;
    }

    @Override
    public IPage getSpot(Page page, CustomSearch search) {
        return baseMapper.getSpot(page, search);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delExcrete(Long id) {
        //根据故障表ID查询水表编号
        Bwgzbcjdatail gzServiceOne = gzService.getOne(Wrappers.<Bwgzbcjdatail>lambdaQuery().eq(Bwgzbcjdatail::getId, id).select(Bwgzbcjdatail::getBwSbbh, Bwgzbcjdatail::getBwFileid));
        //删除故障表记录
        gzService.removeById(id);
        //删除文件
        List<String> fileListId = Arrays.asList(gzServiceOne.getBwFileid().split(","));
        //查询文件路径
        List<String> filePaths = fileService.list(Wrappers.<File>lambdaQuery().in(File::getId, fileListId)
                .select(File::getFilePath)).stream().map(File::getFilePath).collect(Collectors.toList());
        filePaths.forEach(k -> {
            FtpUtil.deleteFile(k);
        });
        //删除文件记录表中的数据
        fileService.removeByIds(fileListId);
        //修改水表状态
        bwrksbdatail.update(Wrappers.<Bwrksbdatail>lambdaUpdate().eq(Bwrksbdatail::getBwSbbh, gzServiceOne.getBwSbbh())
                .set(Bwrksbdatail::getBwSbzt, "61"));
        //修改移交检查状态
        yjglService.update(Wrappers.<Bwsbyjgl>lambdaUpdate()
                .eq(Bwsbyjgl::getSbzsbh, gzServiceOne.getBwSbbh()).set(Bwsbyjgl::getCheckFlag, "0"));
        return true;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertExcrete(Bwgzbcjdatail bwgzbcjdatail, HttpServletRequest request) {
        //保存文件这一坨代码，后期抽出来公共使用
        MultiValueMap<String, MultipartFile> files = ((MultipartHttpServletRequest) request).getMultiFileMap();
        StringBuilder fileIds = new StringBuilder("");
        files.forEach((k, v) -> {
            //保存照片
            v.forEach(file -> {
                //文件名
                String fileName = file.getOriginalFilename();
                if (!"".equals(fileName)) {
                    //文件路径
                    String filePath = filePathBean.getZyCheck() + IdWorker.getIdStr() + fileName.substring(fileName.lastIndexOf("."));
                    boolean b = FtpUtil.uploadFile2Ftp(file, filePath);
                    if (b) {
                        File localFile = new File();
                        localFile.setFilePath(filePath);
                        localFile.setFileName(fileName);
                        localFile.setOtherName(IdWorker.getIdStr() + fileName.substring(fileName.lastIndexOf(".")));
                        localFile.setTableName("TF_YWPN_BWGZBCJDATAIL_W");//关联表名称
                        //获取后缀
                        String suffix = fileName.substring(fileName.lastIndexOf("."));
                        localFile.setFileFormat(suffix);
                        localFile.setFileSize(file.getSize() + "kb");
                        fileService.save(localFile);
                        //获得文件ID
                        fileIds.append(localFile.getId() + ",");
                    }
                }
            });
        });
        //根据水表编号查询得到水表ID
        Bwrksbdatail bwrksbdatail = getId(bwgzbcjdatail.getBwSbbh());
        Long sbId = null;
        if (StringUtil.isNotNull(bwrksbdatail)) {
            sbId = bwrksbdatail.getId();
            String sbzt = bwrksbdatail.getBwSbzt();
            //如果是本系统的水表；需要验证状态
            if (!"61".equals(sbzt)) {
//                if ("950".equals(sbzt)){
//                    throw new ToflyDeniedException("该水表已维修好，不用进行周检(抽检)");
//                }
                throw new ToflyDeniedException("请正确填写需要拆检水表");
            }
        }
        String newFileIds = "";
        if (fileIds.length() > 0) {
            newFileIds = fileIds.substring(0, fileIds.length() - 1);
        }
        bwgzbcjdatail.setBwFileid(newFileIds);
        //水表ID
        bwgzbcjdatail.setSbid(sbId);
        gzService.save(bwgzbcjdatail);
        //得到刚插入数据的ID
        Long id = bwgzbcjdatail.getId();
        //文件ID集合
        List<String> fileIdList = Arrays.asList(newFileIds.split(","));
        //修改文件数据表中的tableId字段
        baseMapper.updateFile(id, fileIdList);
        //修改水表状态
//        bwrksbdatail.update(Wrappers.<Bwrksbdatail>lambdaUpdate().eq(Bwrksbdatail::getId, sbId).set(Bwrksbdatail::getBwSbzt, "58"));
        yjglService.update(Wrappers.<Bwsbyjgl>lambdaUpdate().eq(Bwsbyjgl::getSbzsbh, bwgzbcjdatail.getBwSbbh())
                .set(Bwsbyjgl::getCheckFlag, "1"));
        return true;
    }

    @Override
    public IPage<CustomGzSb> getExcrete(Page page, CustomSearch search) {
        return baseMapper.getExcrete(page, search);
    }


    //前缀
    public static String prefix(String sbbh) {
        int index = sbbh.indexOf("-");
        return sbbh.substring(0, index + 1);
    }

    //编号
    public static Long num(String sbbh) {
        int index = sbbh.indexOf("-");
        return Long.parseLong(sbbh.substring(index + 1));
    }

    public Bwrksbdatail getId(String importSbbh) {
        //先查询水表入库的ID，方便以后查询厂家、口径等信息，因为数据库表的不满足，不能每个表都存放厂家、口径等信息，只能去保存水表入库的ID，然后链表查询
//        String prefix = prefix(importSbbh);
//        Long sbbh = num(importSbbh);
        Bwrksbdatail bwrksbdatailOne = bwrksbdatail.getOne(Wrappers.<Bwrksbdatail>lambdaQuery().eq(Bwrksbdatail::getBwSbbh, importSbbh)
                .select(Bwrksbdatail::getId, Bwrksbdatail::getBwSbzt));
        return bwrksbdatailOne;

    }


}
