package com.huimv.receive.service.impl;

import cn.hutool.core.util.ObjectUtil;
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.entity.vo.BillGoodsInventoryVo;
import com.huimv.receive.mapper.*;
import com.huimv.receive.service.IBillGoodsInventoryService;
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.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2023-08-22
 */
@Service
public class BillGoodsInventoryServiceImpl extends ServiceImpl<BillGoodsInventoryMapper, BillGoodsInventory> implements IBillGoodsInventoryService {

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

    @Override
    public Result listAll(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        QueryWrapper<BillGoodsInventory> queryWrapper = new QueryWrapper<>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
        if ("21".equals(farmId)) {
            queryWrapper.eq("farm_id", 26);
        } else {
            queryWrapper.eq("farm_id", farmId);
        }
        queryWrapper.ge("create_date", calendar.getTime());
        List<BillGoodsInventoryVo> billGoodsInventoryVos = inventoryMapper.listAll(queryWrapper);
        return new Result(ResultCode.SUCCESS, billGoodsInventoryVos);
    }
    public String getUrl(String content, MultipartFile image) throws IOException {
        if (ObjectUtil.isNotEmpty(image)){
            if ( !"".equals(content)){
                content = content +","+uploadImage.getImageCom(image);
            }else {
                content = content +uploadImage.getImageCom(image);
            }
        }
        return content;
    }
    @Override
    public Result edit(HttpServletRequest httpServletRequest, String id, String goods, MultipartFile imgUrl1,
                       MultipartFile imgUrl2,
                       MultipartFile imgUrl3,
                       MultipartFile imgUrl4,
                       MultipartFile imgUrl5,
                       MultipartFile imgUrl6/*, String wayType*/) throws IOException {

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        BillGoodsInventory goodsInventory = inventoryMapper.selectById(id);
        if (goodsInventory.getBillStatus() != 0) {
            return new Result(10001, "此条记录已被他人修改，请退出刷新查看！", false);
        }
        String goodsName = "";
        String goodsType = "";
        String goodsNum = "";
        String goodsTypeName = "";
        String goodsUnit = "";


        goodsInventory.setGoodsName(goodsName);
        goodsInventory.setGoodsType(goods);
        goodsInventory.setGoodsNums(goodsNum);
        goodsInventory.setGoodsTypeName(goodsTypeName);
        goodsInventory.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
        goodsInventory.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
        goodsInventory.setGoodsUnit(goodsUnit);
        goodsInventory.setBillStatus(1);
        goodsInventory.setSubDate(LocalDateTime.now());
//        goodsInventory.setWayType(wayType);
//
//        if (ObjectUtil.isNotEmpty(imgUrl1)) {
//            String  imageCom = uploadImage.getImageCom(imgUrl1);
//            if (imageCom.equals("上传失败")) {
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return new Result(10001, "图片1上传失败", false);
//            }
//
//        }
        String content ="";
        content = getUrl(content,imgUrl1);
        content = getUrl(content,imgUrl2);
        content = getUrl(content,imgUrl3);
        content = getUrl(content,imgUrl4);
        content = getUrl(content,imgUrl5);
        content = getUrl(content,imgUrl6);

        goodsInventory.setImgUrl(content);
        QueryWrapper<BaseProcess> processQueryWrapper = new QueryWrapper<>();
        processQueryWrapper.eq("id", goodsInventory.getBillAdmission());
        BaseProcess baseProcess = processMapper.selectOne(processQueryWrapper);//进程

        QueryWrapper<BaseLocation> locationQueryWrapper = new QueryWrapper<>();
        locationQueryWrapper.eq("id", goodsInventory.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]);


        Object newObject = BillPcrServiceImpl.getNewObject(nextId, goodsInventory.getDestName(), goodsInventory.getDestId(), goodsInventory.getAdmissionUserName(),
                goodsInventory.getAdmissionUserId(), goodsInventory.getVistitDate(), goodsInventory.getSubDate(),
                goodsInventory.getBillAdmission(), Integer.parseInt(goodsInventory.getFarmId()), goodsInventory.getTestLocation(), goodsInventory.getTestLocationId(),
                goodsInventory.getVistitType(), goodsInventory.getPhone(), goodsInventory.getDepartureName(), goodsInventory.getDepartureId()
                ,goodsInventory.getMidId(),goodsInventory.getMidName(),goodsInventory.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]), goodsInventory.getVistitType(), goodsInventory.getDestName()
                        , goodsInventory.getDestId(), goodsInventory.getAdmissionUserId(), goodsInventory.getAdmissionUserName(), goodsInventory.getPhone(),
                        goodsInventory.getVistitDate(), location.getId(), location.getLocationName(), Integer.parseInt(goodsInventory.getFarmId())
                        , baseProcess.getId(), goodsInventory.getDepartureName(), goodsInventory.getDepartureId(),goodsInventory.getMidId()
                        ,goodsInventory.getMidName(),goodsInventory.getFarmName());
                if (Integer.parseInt(split[1]) == 1) {
                    //新增采样
                    BillSampling billSampling = (BillSampling) entity;
                    if (goodsInventory.getVistitType() != 0) {
                        billSampling.setCarNum(goodsInventory.getCarNum());
                    }
                    if (goodsInventory.getVistitType() == 5) {
                        billSampling.setResource(goodsInventory.getResource());
                        billSampling.setFeedImgUrl(goodsInventory.getFeedImgUrl());
                        billSampling.setRemark(goodsInventory.getRemark());
                    }
                    billSamplingMapper.insert(billSampling);
                } else if (Integer.parseInt(split[1]) == 2) {
                    //新增pcr
                    BillPcr billClean = (BillPcr) entity;
                    if (goodsInventory.getVistitType() != 0) {
                        billClean.setCarNum(goodsInventory.getCarNum());
                    }
                    if (goodsInventory.getVistitType() == 5) {
                        billClean.setResource(goodsInventory.getResource());
                        billClean.setFeedImgUrl(goodsInventory.getFeedImgUrl());
                        billClean.setRemark(goodsInventory.getRemark());
                    }
                    pcrMapper.insert(billClean);
                } else if (Integer.parseInt(split[1]) == 3) {
                    //新增洗澡
                    BillClean billClean = (BillClean) entity;
                    if (goodsInventory.getVistitType() != 0) {
                        billClean.setCarNum(goodsInventory.getCarNum());
                    }
                    if (goodsInventory.getVistitType() == 5) {
                        billClean.setResource(goodsInventory.getResource());
                        billClean.setFeedImgUrl(goodsInventory.getFeedImgUrl());
                        billClean.setRemark(goodsInventory.getRemark());
                    }
                    cleanMapper.insert(billClean);
                } else if (Integer.parseInt(split[1]) == 4) {
                    //新增隔离
                    BillIsolate pcr = (BillIsolate) entity;
                    if (goodsInventory.getVistitType() != 0) {
                        pcr.setCarNum(goodsInventory.getCarNum());
                    }
                    if (goodsInventory.getVistitType() == 5) {
                        pcr.setResource(goodsInventory.getResource());
                        pcr.setFeedImgUrl(goodsInventory.getFeedImgUrl());
                        pcr.setRemark(goodsInventory.getRemark());
                    }
                    isolateMapper.insert(pcr);
                } else if (Integer.parseInt(split[1]) == 5) {
                    BillDry billClean = (BillDry) entity;
                    if (goodsInventory.getVistitType() != 0) {
                        billClean.setCarNum(goodsInventory.getCarNum());
                    }
                    if (goodsInventory.getVistitType() == 5) {
                        billClean.setResource(goodsInventory.getResource());
                        billClean.setFeedImgUrl(goodsInventory.getFeedImgUrl());
                        billClean.setRemark(goodsInventory.getRemark());
                    }
                    dryMapper.insert(billClean);
                    //新增烘干
                } else if (Integer.parseInt(split[1]) == 6) {
                    //新增洗澡前拍照
                    BillCleanBefore before = (BillCleanBefore) entity;
                    if (goodsInventory.getVistitType() != 0) {
                        before.setCarNum(goodsInventory.getCarNum());
                    }
                    if (goodsInventory.getVistitType() == 5) {
                        before.setResource(goodsInventory.getResource());
                        before.setFeedImgUrl(goodsInventory.getFeedImgUrl());
                        before.setRemark(goodsInventory.getRemark());
                    }
                    billCleanBeforeMapper.insert(before);
                } else if (Integer.parseInt(split[1]) == 7) {
                    //新增洗澡前拍照
                    BillGoodsInventory before = (BillGoodsInventory) entity;
                    if (goodsInventory.getVistitType() != 0) {
                        before.setCarNum(goodsInventory.getCarNum());
                    }
                    if (goodsInventory.getVistitType() == 5) {
                        before.setResource(goodsInventory.getResource());
                        before.setFeedImgUrl(goodsInventory.getFeedImgUrl());
                        before.setRemark(goodsInventory.getRemark());
                    }
                    inventoryMapper.insert(before);
                }
                baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId + "," + split[1]);
                Integer locationId = goodsInventory.getTestLocationId();
                int indexOf = allLocationId.indexOf(locationId.toString());//当前位置在所有流程位置中的下标
                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 (goodsInventory.getVistitType() != 0) {
                billSampling.setCarNum(goodsInventory.getCarNum());
            }
            if (goodsInventory.getVistitType() == 5) {
                billSampling.setResource(goodsInventory.getResource());
                billSampling.setFeedImgUrl(goodsInventory.getFeedImgUrl());
                billSampling.setRemark(goodsInventory.getRemark());
            }
            billSamplingMapper.insert(billSampling);
            baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId);
        } else if (nextId == 2) {
            //新增pcr
            BillPcr billClean = (BillPcr) newObject;
            if (goodsInventory.getVistitType() != 0) {
                billClean.setCarNum(goodsInventory.getCarNum());
            }
            if (goodsInventory.getVistitType() == 5) {
                billClean.setResource(goodsInventory.getResource());
                billClean.setFeedImgUrl(goodsInventory.getFeedImgUrl());
                billClean.setRemark(goodsInventory.getRemark());
            }
            pcrMapper.insert(billClean);
            baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId);
        } else if (nextId == 3) {
            //新增洗澡
            BillClean billClean = (BillClean) newObject;
            if (goodsInventory.getVistitType() != 0) {
                billClean.setCarNum(goodsInventory.getCarNum());
            }
            if (goodsInventory.getVistitType() == 5) {
                billClean.setResource(goodsInventory.getResource());
                billClean.setFeedImgUrl(goodsInventory.getFeedImgUrl());
                billClean.setRemark(goodsInventory.getRemark());
            }
            cleanMapper.insert(billClean);
            baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId);
        } else if (nextId == 4) {
            //新增隔离
            BillIsolate pcr = (BillIsolate) newObject;
            if (goodsInventory.getVistitType() != 0) {
                pcr.setCarNum(goodsInventory.getCarNum());
            }
            if (goodsInventory.getVistitType() == 5) {
                pcr.setResource(goodsInventory.getResource());
                pcr.setFeedImgUrl(goodsInventory.getFeedImgUrl());
                pcr.setRemark(goodsInventory.getRemark());
            }
            isolateMapper.insert(pcr);
            baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId);
        } else if (nextId == 5) {
            BillDry billClean = (BillDry) newObject;
            if (goodsInventory.getVistitType() != 0) {
                billClean.setCarNum(goodsInventory.getCarNum());
            }
            if (goodsInventory.getVistitType() == 5) {
                billClean.setResource(goodsInventory.getResource());
                billClean.setFeedImgUrl(goodsInventory.getFeedImgUrl());
                billClean.setRemark(goodsInventory.getRemark());
            }
            dryMapper.insert(billClean);
            baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId);
            //新增烘干
        } else if (nextId == 6) {
            //新增洗澡前拍照
            BillCleanBefore before = (BillCleanBefore) newObject;
            if (goodsInventory.getVistitType() != 0) {
                before.setCarNum(goodsInventory.getCarNum());
            }
            if (goodsInventory.getVistitType() == 5) {
                before.setResource(goodsInventory.getResource());
                before.setFeedImgUrl(goodsInventory.getFeedImgUrl());
                before.setRemark(goodsInventory.getRemark());
            }
            billCleanBeforeMapper.insert(before);
            baseProcess.setCurrentFlowId(baseProcess.getCurrentFlowId() + "," + nextId);
        } else if (nextId == 7) {
            //新增洗澡前拍照
            BillGoodsInventory before = (BillGoodsInventory) newObject;
            if (goodsInventory.getVistitType() != 0) {
                before.setCarNum(goodsInventory.getCarNum());
            }
            if (goodsInventory.getVistitType() == 5) {
                before.setResource(goodsInventory.getResource());
                before.setFeedImgUrl(goodsInventory.getFeedImgUrl());
                before.setRemark(goodsInventory.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);
        inventoryMapper.updateById(goodsInventory);
        return new Result(10000, "修改成功!", true);
    }

    @Override
    public Result list(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String type = paramsMap.get("type");//0 全部 1未填写 2已填写
        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 = "10";
        }
        if ("".equals(type) || null == type) {
            type = "0";
        }
        QueryWrapper<BillGoodsInventory> queryWrapper = new QueryWrapper<>();
        Page<BillGoodsInventory> page = new Page(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        queryWrapper.eq("farm_id", farmId).orderByDesc("sub_date");
        if ("0".equals(type)) {
            queryWrapper.in("bill_status", 0, 1,3);
        } else {
            queryWrapper.eq("bill_status", type);
        }
        return new Result(ResultCode.SUCCESS,inventoryMapper.selectPage(page,queryWrapper));
    }
}
