package com.huimv.receive.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.receive.common.token.TokenSign;
import com.huimv.receive.common.utils.FlowUtil;
import com.huimv.receive.common.utils.Result;
import com.huimv.receive.common.utils.ResultCode;
import com.huimv.receive.common.utils.UploadImage;
import com.huimv.receive.entity.*;
import com.huimv.receive.mapper.*;
import com.huimv.receive.service.IBillCleanBeforeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * <p>
 * 洗消表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-03-11
 */
@Service
public class BillCleanBeforeServiceImpl extends ServiceImpl<BillCleanBeforeMapper, BillCleanBefore> implements IBillCleanBeforeService {

    @Autowired
    private BillCleanBeforeMapper billCleanBeforeMapper;
    @Autowired
    private UploadImage uploadImage;
    @Autowired
    private BaseProcessMapper processMapper;
    @Autowired
    private BaseLocationMapper locationMapper;
    @Autowired
    private BillPcrMapper pcrMapper;
    @Autowired
    private BillCleanMapper cleanMapper;
    @Autowired
    private BillIsolateMapper isolateMapper;
    @Autowired
    private BillSamplingMapper samplingMapper;
    @Autowired
    private BillDryMapper dryMapper;
    @Autowired
    private BillGoodsInventoryMapper inventoryMapper;


    @Override
    public Result list(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String type = paramsMap.get("type");//展示类型
        String data = paramsMap.get("data");
        String pageNum = paramsMap.get("pageNum");
        String pageSize = paramsMap.get("pageSize");
        if ("".equals(pageNum) || null == pageNum) {
            pageNum = "1";
        }
        if ("".equals(pageSize) || null == pageSize) {
            pageSize = "20";
        }
        Page<BillCleanBefore> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        QueryWrapper<BillCleanBefore> queryWrapper = new QueryWrapper<>();
        queryWrapper/*.in("farm_id", farmId)*/
                .in("test_location_id", TokenSign.getWorkIdByJwtToken(httpServletRequest)).orderByDesc("sub_date").eq("vistit_type", type);
        if ("0".equals(data)) {
            queryWrapper.in("bill_status", 0, 1, 2, 3);
        }
        if ("1".equals(data)) {
            queryWrapper.eq("bill_status", 0);
        }
        if ("2".equals(data)) {
            queryWrapper.eq("bill_status", 1);
        }
        if ("3".equals(data)) {
            queryWrapper.in("bill_status", 2, 3);
        }
        QueryWrapper<BillCleanBefore> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("vistit_type", type);
        queryWrapper2/*.in("farm_id", farmId)*/.in("test_location_id", TokenSign.getWorkIdByJwtToken(httpServletRequest)).orderByDesc("sub_date");
        queryWrapper2.eq("bill_status", 0);
        return new Result(ResultCode.SUCCESS, billCleanBeforeMapper.selectPage(page, queryWrapper), billCleanBeforeMapper.selectCount(queryWrapper2));
    }

    @Override
    public Result listById(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String id = paramsMap.get("id");
        BillCleanBefore billPcr = billCleanBeforeMapper.selectById(id);
        return new Result(ResultCode.SUCCESS, billPcr);
    }

    @Override
    public Result listPersonalCleanBefore(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String pageNo = paramsMap.get("pageNum");
        String pageSize = paramsMap.get("pageSize");
        String vistitType = paramsMap.get("vistitType");
        Integer userId = TokenSign.getMemberIdByJwtToken(httpServletRequest);
        Page<BillCleanBefore> page = new Page<>(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        LambdaQueryWrapper<BillCleanBefore> queryWrapper = new QueryWrapper<BillCleanBefore>().lambda()
                .eq(BillCleanBefore::getFarmId, farmId)
                .eq(BillCleanBefore::getAdmissionUserId, userId)
                .eq(ObjectUtil.isNotEmpty(vistitType), BillCleanBefore::getVistitType, vistitType)
                .orderByDesc(BillCleanBefore::getSubDate);
        Page<BillCleanBefore> billCleanBeforePage = billCleanBeforeMapper.selectPage(page, queryWrapper);
        Integer count = billCleanBeforeMapper.selectCount(queryWrapper);
        return new Result(ResultCode.SUCCESS, billCleanBeforePage, count);
    }

    @Override
    public Result edit(HttpServletRequest httpServletRequest, String farmId, String id, String date,
                       MultipartFile img1,MultipartFile img2,MultipartFile img3,MultipartFile img4) throws ParseException, IOException {
        String imgUrl = "";
        String s1 = "";
        String s2 = "";
        String s3 = "";
        String s4 = "";

        if (ObjectUtil.isNotEmpty(img1)) {
            String  s= uploadImage.uploadImg(img1);
            if ("上传失败".equals(s1)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new Result(10001, "图片1上传失败", false);
            }
            s1 = s;
        }
        if (ObjectUtil.isNotEmpty(img2)) {
            String  s= uploadImage.uploadImg(img2);
            if ("上传失败".equals(s2)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new Result(10001, "图片2上传失败", false);
            }
            s2 = "," + s;
        }
        if (ObjectUtil.isNotEmpty(img3)) {
            String  s= uploadImage.uploadImg(img3);
            s3 = "," + s;
            if ("上传失败".equals(s)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new Result(10001, "图片3上传失败", false);
            }
        }
        if (ObjectUtil.isNotEmpty(img4)) {
            String s = uploadImage.uploadImg(img4);
            s4 = "," + s;
            if ("上传失败".equals(s)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new Result(10001, "图片4上传失败", false);
            }
        }
        imgUrl=s1+s2+s3+s4;


        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        BillCleanBefore cleanBefore = billCleanBeforeMapper.selectById(id);
        if (cleanBefore.getBillStatus() != 0) {
            return new Result(10001, "此条记录已被他人修改，请退出刷新查看！", false);
        }
        cleanBefore.setImgUrl(imgUrl);
        cleanBefore.setImgStatus(1);


        QueryWrapper<BaseProcess> processQueryWrapper = new QueryWrapper<>();
        processQueryWrapper.eq("id", cleanBefore.getProcessId());
        BaseProcess baseProcess = processMapper.selectOne(processQueryWrapper);//进程

        QueryWrapper<BaseLocation> locationQueryWrapper = new QueryWrapper<>();
        locationQueryWrapper.eq("id", cleanBefore.getTestLocationId());
        BaseLocation baseLocation = locationMapper.selectOne(locationQueryWrapper);//当前pcr检测所在的位置

        String allLocationId = baseProcess.getAllLocationId();//所有的位置id
        String allFlowId = baseProcess.getAllFlowId();//所有的流程id
        String currentFlowId = baseProcess.getCurrentFlowId();//当前已经完成的流程id
        String substring1 = allFlowId.substring(currentFlowId.length() + 1, allFlowId.length());
        String[] split = substring1.split(",");
        Integer nextId = Integer.parseInt(split[0]);


        cleanBefore.setBillStatus(1);
        cleanBefore.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
        cleanBefore.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
        cleanBefore.setTestLocation(baseLocation.getLocationName());
        cleanBefore.setTestLocationId(baseLocation.getId());
        cleanBefore.setCheckDate(LocalDateTime.parse(date, dateTimeFormatter));
        cleanBefore.setPassDate(LocalDateTime.now());


        Object newObject = BillPcrServiceImpl.getNewObject(nextId, cleanBefore.getDestName(), cleanBefore.getDestId(), cleanBefore.getAdmissionUserName(),
                cleanBefore.getAdmissionUserId(), cleanBefore.getVistitDate(), cleanBefore.getSubDate(),
                cleanBefore.getProcessId(), Integer.parseInt(cleanBefore.getFarmId()), cleanBefore.getTestLocation(), cleanBefore.getTestLocationId(),
                cleanBefore.getVistitType(), cleanBefore.getPhone(), cleanBefore.getDepartureName(), cleanBefore.getDepartureId()
                ,cleanBefore.getMidId(),cleanBefore.getMidName(),cleanBefore.getFarmName());
        if (nextId == 0) {
            if (split.length == 1) {
                baseProcess.setProcessType(1);
                String[] strings = allLocationId.split(",");
                String ss2 = "";
                for (int i = 0; i < strings.length; i++) {
                    strings[i].replaceAll(strings[i], "2");
                    if (i == strings.length - 1) {
                        ss2 = ss2 + strings[i].replaceAll(strings[i], "2");
                    } else {
                        ss2 = strings[i].replaceAll(strings[i], "2") + "," + ss2;
                    }
                }
                baseProcess.setAllLocationStatus(ss2);
            } else {
                String[] strings = allLocationId.split(",");
                Integer index = 0;
                for (int i = 0; i < strings.length; i++) {
                    if ((baseLocation.getId().toString()).equals(strings[i])) {
                        index = i;
                    }
                }
                QueryWrapper<BaseLocation> queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("id", strings[index + 2]);
                BaseLocation location = locationMapper.selectOne(queryWrapper1);
                FlowUtil flowUtil = new FlowUtil();
                Object entity = flowUtil.getEntity(Integer.parseInt(split[1]), cleanBefore.getVistitType(), cleanBefore.getDestName()
                        , cleanBefore.getDestId(), cleanBefore.getAdmissionUserId(), cleanBefore.getAdmissionUserName(), cleanBefore.getPhone(),
                        cleanBefore.getVistitDate(), location.getId(), location.getLocationName(), Integer.parseInt(cleanBefore.getFarmId())
                        , baseProcess.getId(), cleanBefore.getDepartureName(), cleanBefore.getDepartureId(),cleanBefore.getMidId(),cleanBefore.getMidName(),cleanBefore.getFarmName());
                if (Integer.parseInt(split[1]) == 1) {
                    //新增采样
                    BillSampling billSampling = (BillSampling) entity;
                    if (cleanBefore.getVistitType() != 0) {
                        billSampling.setCarNum(cleanBefore.getCarNum());
                    }
                    if (cleanBefore.getVistitType() == 5) {
                        billSampling.setResource(cleanBefore.getResource());
                        billSampling.setFeedImgUrl(cleanBefore.getFeedImgUrl());
                        billSampling.setRemark(cleanBefore.getRemark());
                    }
                    samplingMapper.insert(billSampling);
                } else if (Integer.parseInt(split[1]) == 2) {
                    //新增pcr
                    BillPcr billClean = (BillPcr) entity;
                    if (cleanBefore.getVistitType() != 0) {
                        billClean.setCarNum(cleanBefore.getCarNum());
                    }
                    if (cleanBefore.getVistitType() == 5) {
                        billClean.setResource(cleanBefore.getResource());
                        billClean.setFeedImgUrl(cleanBefore.getFeedImgUrl());
                        billClean.setRemark(cleanBefore.getRemark());
                    }

                    pcrMapper.insert(billClean);
                } else if (Integer.parseInt(split[1]) == 3) {
                    //新增洗澡
                    BillClean billClean = (BillClean) entity;
                    if (cleanBefore.getVistitType() != 0) {
                        billClean.setCarNum(cleanBefore.getCarNum());
                    }
                    if (cleanBefore.getVistitType() == 5) {
                        billClean.setResource(cleanBefore.getResource());
                        billClean.setFeedImgUrl(cleanBefore.getFeedImgUrl());
                        billClean.setRemark(cleanBefore.getRemark());
                    }
                    cleanMapper.insert(billClean);
                } else if (Integer.parseInt(split[1]) == 4) {
                    //新增隔离
                    BillIsolate pcr = (BillIsolate) entity;
                    if (cleanBefore.getVistitType() != 0) {
                        pcr.setCarNum(cleanBefore.getCarNum());
                    }
                    if (cleanBefore.getVistitType() == 5) {
                        pcr.setResource(cleanBefore.getResource());
                        pcr.setFeedImgUrl(cleanBefore.getFeedImgUrl());
                        pcr.setRemark(cleanBefore.getRemark());
                    }
                    isolateMapper.insert(pcr);
                } else if (Integer.parseInt(split[1]) == 5) {
                    BillDry billClean = (BillDry) entity;
                    if (cleanBefore.getVistitType() != 0) {
                        billClean.setCarNum(cleanBefore.getCarNum());
                    }
                    if (cleanBefore.getVistitType() == 5) {
                        billClean.setResource(cleanBefore.getResource());
                        billClean.setFeedImgUrl(cleanBefore.getFeedImgUrl());
                        billClean.setRemark(cleanBefore.getRemark());
                    }
                    dryMapper.insert(billClean);
                    //新增烘干
                } else if (Integer.parseInt(split[1]) == 6) {
                    //新增洗澡前拍照
                    BillCleanBefore before = (BillCleanBefore) entity;
                    if (cleanBefore.getVistitType() != 0) {
                        before.setCarNum(cleanBefore.getCarNum());
                    }
                    if (cleanBefore.getVistitType() == 5) {
                        before.setResource(cleanBefore.getResource());
                        before.setFeedImgUrl(cleanBefore.getFeedImgUrl());
                        before.setRemark(cleanBefore.getRemark());
                    }
                    billCleanBeforeMapper.insert(before);
                } else if (Integer.parseInt(split[1]) == 7) {
                    //新增洗澡前拍照
                    BillGoodsInventory before = (BillGoodsInventory) entity;
                    if (cleanBefore.getVistitType() != 0) {
                        before.setCarNum(cleanBefore.getCarNum());
                    }
                    if (cleanBefore.getVistitType() == 5) {
                        before.setResource(cleanBefore.getResource());
                        before.setFeedImgUrl(cleanBefore.getFeedImgUrl());
                        before.setRemark(cleanBefore.getRemark());
                    }
                    inventoryMapper.insert(before);
                }
                baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId + "," + split[1]);

                Integer locationId = cleanBefore.getTestLocationId();
                String[] split2 = allLocationId.split(",");
                int a = 0;
                for (int i = 0; i < split2.length; i++) {
                    if (locationId.toString().equals(split2[i])) {
                        a = i + 1;
                    }
                }
                int indexOf = 2 * (a - 2);//当前位置在所有流程位置中的下标
                String substring = baseProcess.getAllLocationStatus().substring(0, indexOf + 3);//截取已经过的位置状态
                String[] split1 = substring.split(",");
                String sb2 = "";
                for (int i = 0; i < split1.length; i++) {
                    if (i == split1.length - 1) {
                        sb2 = sb2 + split1[i].replaceAll(split1[i], "2");
                    } else {
                        sb2 = split1[i].replaceAll(split1[i], "2") + "," + sb2;
                    }
                }
                sb2 = sb2 + baseProcess.getAllLocationStatus().substring(indexOf + 3);
                StringBuilder sb = new StringBuilder(sb2);
                sb.replace(indexOf + 4, indexOf + 5, "2");
                sb.replace(indexOf + 6, indexOf + 7, "1");
                baseProcess.setAllLocationStatus(sb.toString());
            }
        } else if (nextId == 1) {
            //新增采样
            BillSampling billSampling = (BillSampling) newObject;
            if (cleanBefore.getVistitType() != 0) {
                billSampling.setCarNum(cleanBefore.getCarNum());
            }
            if (cleanBefore.getVistitType() == 5) {
                billSampling.setResource(cleanBefore.getResource());
                billSampling.setFeedImgUrl(cleanBefore.getFeedImgUrl());
                billSampling.setRemark(cleanBefore.getRemark());
            }
            samplingMapper.insert(billSampling);
            baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId);
        } else if (nextId == 2) {
            //新增pcr
            BillPcr billClean = (BillPcr) newObject;
            if (cleanBefore.getVistitType() != 0) {
                billClean.setCarNum(cleanBefore.getCarNum());
            }
            if (cleanBefore.getVistitType() == 5) {
                billClean.setResource(cleanBefore.getResource());
                billClean.setFeedImgUrl(cleanBefore.getFeedImgUrl());
                billClean.setRemark(cleanBefore.getRemark());
            }
            pcrMapper.insert(billClean);
            baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId);
        } else if (nextId == 3) {
            //新增洗澡
            BillClean billClean = (BillClean) newObject;
            if (cleanBefore.getVistitType() != 0) {
                billClean.setCarNum(cleanBefore.getCarNum());
            }
            if (cleanBefore.getVistitType() == 5) {
                billClean.setResource(cleanBefore.getResource());
                billClean.setFeedImgUrl(cleanBefore.getFeedImgUrl());
                billClean.setRemark(cleanBefore.getRemark());
            }
            cleanMapper.insert(billClean);
            baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId);
        } else if (nextId == 4) {
            //新增隔离
            BillIsolate pcr = (BillIsolate) newObject;
            if (cleanBefore.getVistitType() != 0) {
                pcr.setCarNum(cleanBefore.getCarNum());
            }
            if (cleanBefore.getVistitType() == 5) {
                pcr.setResource(cleanBefore.getResource());
                pcr.setFeedImgUrl(cleanBefore.getFeedImgUrl());
                pcr.setRemark(cleanBefore.getRemark());
            }
            isolateMapper.insert(pcr);
            baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId);
        } else if (nextId == 5) {
            BillDry billClean = (BillDry) newObject;
            if (cleanBefore.getVistitType() != 0) {
                billClean.setCarNum(cleanBefore.getCarNum());
            }
            if (cleanBefore.getVistitType() == 5) {
                billClean.setResource(cleanBefore.getResource());
                billClean.setFeedImgUrl(cleanBefore.getFeedImgUrl());
                billClean.setRemark(cleanBefore.getRemark());
            }
            dryMapper.insert(billClean);
            baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId);
            //新增烘干
        } else if (nextId == 6) {
            //新增洗澡前拍照
            BillCleanBefore before = (BillCleanBefore) newObject;
            if (cleanBefore.getVistitType() != 0) {
                before.setCarNum(cleanBefore.getCarNum());
            }
            if (cleanBefore.getVistitType() == 5) {
                before.setResource(cleanBefore.getResource());
                before.setFeedImgUrl(cleanBefore.getFeedImgUrl());
                before.setRemark(cleanBefore.getRemark());
            }
            billCleanBeforeMapper.insert(before);
            baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId);
        } else if (nextId == 7) {
            //新增洗澡前拍照
            BillGoodsInventory before = (BillGoodsInventory) newObject;
            if (cleanBefore.getVistitType() != 0) {
                before.setCarNum(cleanBefore.getCarNum());
            }
            if (cleanBefore.getVistitType() == 5) {
                before.setResource(cleanBefore.getResource());
                before.setFeedImgUrl(cleanBefore.getFeedImgUrl());
                before.setRemark(cleanBefore.getRemark());
            }
            inventoryMapper.insert(before);
            baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId);
        }
        baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + LocalDateTime.now().format(dateTimeFormatter));
        baseProcess.setCurrentLocation(baseProcess.getCurrentLocation() + "," + baseLocation.getLocationName());
        baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId() + "," + baseLocation.getId());
        String status = baseProcess.getCurrentStatus();
        String substring = status.substring(0, status.length() - 1);

        baseProcess.setCurrentStatus(substring + "1," + 0);
        processMapper.updateById(baseProcess);
        billCleanBeforeMapper.updateById(cleanBefore);
        return new Result(10000, "修改成功！", true);
    }

    @Override
    public Result listAll(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String type = paramsMap.get("type");//展示类型
        String data = paramsMap.get("data");
        String pageNum = paramsMap.get("pageNum");
        String pageSize = paramsMap.get("pageSize");

        Page<BillCleanBefore> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        QueryWrapper<BillCleanBefore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId).orderByDesc("sub_date").eq("vistit_type", type);
        if ("0".equals(data)) {
            queryWrapper.in("bill_status", 0, 1, 2, 3);
        }
        if ("1".equals(data)) {
            queryWrapper.eq("bill_status", 0);
        }
        if ("2".equals(data)) {
            queryWrapper.in("bill_status", 1);
        }
        if ("3".equals(data)) {
            queryWrapper.eq("bill_status", 3);
        }
        return new Result(ResultCode.SUCCESS, billCleanBeforeMapper.selectPage(page, queryWrapper));
    }
}
