package com.huimv.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huimv.admin.common.token.TokenSign;
import com.huimv.admin.common.utils.DataUill;
import com.huimv.admin.common.utils.Result;
import com.huimv.admin.common.utils.ResultCode;
import com.huimv.admin.entity.*;
import com.huimv.admin.entity.vo.*;
import com.huimv.admin.mapper.*;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huimv.admin.common.token.TokenSign;
import com.huimv.admin.common.utils.*;
import com.huimv.admin.entity.*;
import com.huimv.admin.mapper.*;
import com.huimv.admin.service.IBillPersonnelAdmissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jdk.nashorn.internal.scripts.JS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 入场申请 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-07-21
 */
@Service
public class BillPersonnelAdmissionServiceImpl extends ServiceImpl<BillPersonnelAdmissionMapper, BillPersonnelAdmission> implements IBillPersonnelAdmissionService {
    @Resource
    private BillPersonnelAdmissionMapper billPersonnelAdmissionMapper;
    @Resource
    private BaseProcessMapper baseProcessMapper;
    @Resource
    private BillPcrMapper billPcrMapper;
    @Resource
    private BaseLocationMapper baseLocationMapper;
    @Resource
    private BillIsolateMapper billIsolateMapper;
    @Resource
    private BillCleanMapper billCleanMapper;
    @Resource
    private SysAccountMultilevelMapper sysAccountMultilevelMapper;
    @Autowired
    private UploadImage uploadImage;
    @Autowired
    private BillDryMapper dryMapper;
    @Resource
    private BillGoodsInventoryMapper billGoodsInventoryMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addAdmission(HttpServletRequest httpServletRequest, String admissionType, String vistitType, String userName, String phone, String workName, String papersType, String papersCode, MultipartFile imgUrl, String img, String vistitDate, String vistitReson, String destId, String destName, String farmId, String carNum, String source, String goods) throws IOException {
        Integer userId = TokenSign.getMemberIdByJwtToken(httpServletRequest);
        if (!PhoneNumberValidator.isValidPhoneNumber(phone)) {
            return new Result(10001, "手机号格式错误！", false);
        }
        if (papersType.equals("0")) {
            if (!IDCardValidator.isValidIDCard(papersCode)) {
                return new Result(10001, "身份证号格式错误!", false);
            }
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        BillPersonnelAdmission billPersonnelAdmission = new BillPersonnelAdmission();
        billPersonnelAdmission.setAdmissionType(Integer.parseInt(admissionType));
        billPersonnelAdmission.setVistitType(Integer.parseInt(vistitType));
        billPersonnelAdmission.setDestId(Integer.parseInt(destId));
        billPersonnelAdmission.setDestName(destName);
        billPersonnelAdmission.setAdmissionUserId(userId);
        billPersonnelAdmission.setAdmissionUserName(userName);
        billPersonnelAdmission.setVistitDate(LocalDateTime.parse(vistitDate, dateTimeFormatter));
        billPersonnelAdmission.setSubDate(LocalDateTime.now());
        billPersonnelAdmission.setPhone(phone);
        billPersonnelAdmission.setWorkName(workName);
        billPersonnelAdmission.setPapersType(Integer.parseInt(papersType));
        billPersonnelAdmission.setPapersCode(papersCode);
        if (ObjectUtil.isNotEmpty(carNum)) {
            billPersonnelAdmission.setCarNum(carNum);
        }
        if (ObjectUtil.isNotEmpty(imgUrl)) {
            if (uploadImage.getImageCom(imgUrl).equals("上传失败")) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new Result(10001, "图片上传失败", false);
            }
            billPersonnelAdmission.setImgUrl(uploadImage.getImageCom(imgUrl));
        }
        if (ObjectUtil.isNotEmpty(img)) {
            billPersonnelAdmission.setImgUrl(img);
        }
        if (ObjectUtil.isNotEmpty(source)) {
            billPersonnelAdmission.setSource(source);
        }
        billPersonnelAdmission.setVistitReson(vistitReson);
        billPersonnelAdmission.setFarmId(Integer.parseInt(farmId));
        BaseProcess baseProcess = new BaseProcess();
        baseProcess.setDestName(destName);
        baseProcess.setDestId(Integer.parseInt(destId));
        baseProcess.setAdmissionUserId(userId);
        baseProcess.setAdmissionUserName(userName);
        baseProcess.setSubDate(DateTime.now());
        baseProcess.setUpdateDate(LocalDateTime.now().format(dateTimeFormatter));
        baseProcess.setCurrentStatus("0");
        //获取位置
        BaseLocation baseLocation;
        if (vistitType.equals("5")) {
            baseLocation = baseLocationMapper.selectById(destId);
        } else {
            baseLocation = baseLocationMapper.selectOne(new QueryWrapper<BaseLocation>().eq("farm_id", farmId).eq("vistit_type", vistitType).eq("parent_id", 0));
        }
        if (ObjectUtil.isEmpty(baseLocation)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result(10001, "该来访类型位置不存在", false);
        }
        baseProcess.setCurrentLocation(baseLocation.getLocationName());
        baseProcess.setCurrentLocationId(baseLocation.getId().toString());
        baseProcess.setFarmId(Integer.parseInt(farmId));
        baseProcessMapper.insert(baseProcess);
        billPersonnelAdmission.setProcessId(baseProcess.getId());
        billPersonnelAdmissionMapper.insert(billPersonnelAdmission);
        ArrayList<String> phoneList = new ArrayList<>();
        List<SysAccountMultilevel> safe = sysAccountMultilevelMapper.selectList(new QueryWrapper<SysAccountMultilevel>().eq("farm_ids", farmId).eq("type", 3));
        for (SysAccountMultilevel sysAccountMultilevel : safe) {
            phoneList.add(sysAccountMultilevel.getPhone());
        }
//        SendSMS.sendSMS(phoneList,TokenSign.getUserNameByJwtToken(httpServletRequest)+"入场申请测试");
        if (ObjectUtil.isNotEmpty(goods)) {
            ObjectMapper objectMapper = new ObjectMapper();
            List<BillGoodsInventory> admissionAndGoods = objectMapper.readValue(goods, new TypeReference<List<BillGoodsInventory>>() {
            });
            for (BillGoodsInventory good : admissionAndGoods) {
                good.setBillAdmission(billPersonnelAdmission.getId());
                BaseLocation baseLocation1 = baseLocationMapper.selectById(destId);
                good.setCurrentLocation(baseLocation1.getLocationName());
                good.setCurrentLocationId(baseLocation1.getId());
                billGoodsInventoryMapper.insert(good);
            }
        }
        return Result.SUCCESS();
    }

    @Override
    public Result listPersonalAdmission(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String pageNo = paramsMap.get("pageNum");
        String pageSize = paramsMap.get("pageSize");
        String vistitType = paramsMap.get("vistitType");
        Page<BillPersonnelAdmission> page = new Page<>(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        QueryWrapper<BillPersonnelAdmission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(vistitType), "vistit_type", vistitType).eq("admission_user_id", TokenSign.getMemberIdByJwtToken(httpServletRequest)).orderByDesc("sub_date");
        Page<BillPersonnelAdmission> billPersonnelAdmissionPage = billPersonnelAdmissionMapper.selectPage(page, new QueryWrapper<BillPersonnelAdmission>().eq(StringUtils.isNotBlank(vistitType), "vistit_type", vistitType).eq("admission_user_id", TokenSign.getMemberIdByJwtToken(httpServletRequest)).orderByDesc("sub_date"));
        return new Result(ResultCode.SUCCESS, billPersonnelAdmissionPage, billPersonnelAdmissionMapper.selectCount(queryWrapper));
    }

    @Override
    public Result listAdmission(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String pageNo = paramsMap.get("pageNum");
        String pageSize = paramsMap.get("pageSize");
        String type = paramsMap.get("type");
        String farmId = paramsMap.get("farmId");
        QueryWrapper<BillPersonnelAdmission> queryWrapper = new QueryWrapper<>();
        Integer userType = TokenSign.getUserTypeByJwtToken(httpServletRequest);
        if (userType == 3) {
            //生物安全负责人
            queryWrapper.eq("admission_type", 0);
        } else if (userType == 2) {
            //紧急入场
            queryWrapper.ne("admission_type", 0);
        }
        switch (type) {
            case "1":
                queryWrapper.eq("bill_status", 0);
                break;
            case "2":
                queryWrapper.eq("bill_status", 1);
                break;
            case "3":
                queryWrapper.eq("bill_status", 2);
                break;
            default:
                break;
        }
        queryWrapper.orderByDesc("sub_date").eq("farm_id", farmId);
//        List<BaseLocation> baseLocations = baseLocationMapper.selectList(new QueryWrapper<BaseLocation>().eq("serial_number", 0));
//        List<Integer> locationIds = new ArrayList<>();
//        for (BaseLocation baseLocation : baseLocations) {
//            locationIds.add(baseLocation.getId());
//        }
//        if (!locationIds.contains(Integer.parseInt(TokenSign.getWorkIdByJwtToken(httpServletRequest)))){
//            queryWrapper.eq("id",0);
//        }
        Page<BillPersonnelAdmission> page = new Page<>(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        Page<BillPersonnelAdmission> billPersonnelAdmissionPage = billPersonnelAdmissionMapper.selectPage(page, queryWrapper);
        QueryWrapper<BillPersonnelAdmission> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("farm_id", farmId);
        if (userType == 3) {
            //生物安全负责人
            queryWrapper1.eq("admission_type", 0);
        } else if (userType == 2) {
            //紧急入场
            queryWrapper1.ne("admission_type", 0);
        }
        queryWrapper1.eq("bill_status", 0);
        return new Result(ResultCode.SUCCESS, billPersonnelAdmissionPage, billPersonnelAdmissionMapper.selectList(queryWrapper1).size());
    }

    @Override
    @Transactional
    public Result handleAdmission(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String type = paramsMap.get("type");
        String id = paramsMap.get("id");
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        BillPersonnelAdmission billPersonnelAdmission = billPersonnelAdmissionMapper.selectById(id);
        Integer userType = TokenSign.getUserTypeByJwtToken(httpServletRequest);
        billPersonnelAdmission.setPassDate(LocalDateTime.now());
        billPersonnelAdmission.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
        billPersonnelAdmission.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
        BaseProcess baseProcess = baseProcessMapper.selectById(billPersonnelAdmission.getProcessId());

        ArrayList<String> phoneList = new ArrayList<>();
        phoneList.add(billPersonnelAdmission.getPhone());
        if (StringUtils.isBlank(baseProcess.getUpdateDate())) {
            baseProcess.setUpdateDate(LocalDateTime.now().format(dateTimeFormatter));
        } else {
            baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + LocalDateTime.now().format(dateTimeFormatter));
        }
        if (type.equals("0")) {
            String[] split = baseProcess.getCurrentStatus().split(",");
            split[split.length - 1] = "2";
            //拒绝
            billPersonnelAdmission.setBillStatus(2);
            baseProcess.setProcessType(2);
            baseProcess.setCurrentStatus(String.join(",", split));
//            SendSMS.sendSMS(phoneList,"拒绝入场申请测试");
        } else {
            //通过
            billPersonnelAdmission.setBillStatus(1);
            //获取pcr位置
            String locationId = baseProcess.getCurrentLocationId();
            String[] strings = locationId.split(",");
            String laseLocationId = strings[strings.length - 1];
            BaseLocation baseLocation = baseLocationMapper.selectById(laseLocationId);
            if (userType == 3) {
                String[] split = baseProcess.getCurrentStatus().split(",");
                split[split.length - 1] = "1";
                StringBuilder result = new StringBuilder();
                for (String element : split) {
                    result.append(element).append(",");
                }
                result.append("0");
                baseProcess.setCurrentStatus(result.toString());
                baseProcess.setCurrentLocation(baseProcess.getCurrentLocation() + "," + baseLocation.getLocationName());
                baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId() + "," + baseLocation.getId());
                BillPcr billPcr = new BillPcr();
                billPcr.setVistitType(billPersonnelAdmission.getVistitType());
                billPcr.setDestName(billPersonnelAdmission.getDestName());
                billPcr.setDestId(billPersonnelAdmission.getDestId());
                billPcr.setPhone(billPersonnelAdmission.getPhone());
                billPcr.setAdmissionUserId(billPersonnelAdmission.getAdmissionUserId());
                billPcr.setAdmissionUserName(billPersonnelAdmission.getAdmissionUserName());
                billPcr.setSubDate(LocalDateTime.now());
                billPcr.setVistitDate(billPersonnelAdmission.getVistitDate());
                billPcr.setFarmId(billPersonnelAdmission.getFarmId());
                billPcr.setProcessId(billPersonnelAdmission.getProcessId());
                billPcr.setAdmissionId(Integer.parseInt(id));
                if (ObjectUtil.isNotEmpty(billPersonnelAdmission.getCarNum())) {
                    billPcr.setCarNum(billPersonnelAdmission.getCarNum());
                }
                billPcr.setTestLocation(baseLocation.getLocationName());
                billPcr.setTestLocationId(baseLocation.getId());
                billPcrMapper.insert(billPcr);
//                SendSMS.sendSMS(phoneList,"通过入场申请测试");
            } else {
                baseProcess.setCurrentStatus("1");
//                baseProcess.setCurrentLocation(baseProcess.getCurrentLocation()+","+baseLocation.getLocationName());
//                baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId() +","+baseLocation.getId());
                //TODO 紧急入场通过先不处理
            }
        }
        baseProcessMapper.updateById(baseProcess);
        billPersonnelAdmissionMapper.updateById(billPersonnelAdmission);
        return Result.SUCCESS();
    }

    @Override
    public Result listAll(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String type = paramsMap.get("type");
        String farmId = paramsMap.get("farmId");
        String pageNo = paramsMap.get("pageNum");
        String pageSize = paramsMap.get("pageSize");
        Page<FactoryDirectorVo> page = new Page<>(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        IPage<FactoryDirectorVo> factoryDirectorList;
        if (type.equals("0")) {
            factoryDirectorList = billPersonnelAdmissionMapper.listAll(type, farmId, page);
        } else {
            factoryDirectorList = billPersonnelAdmissionMapper.listCarAll(type, farmId, page);
        }

        return new Result(ResultCode.SUCCESS, factoryDirectorList, factoryDirectorList.getSize());
    }

    @Override
    public Result getDetail(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String type = paramsMap.get("type");
        String id = paramsMap.get("id");
        if (type.equals("0")) {
            BillPersonnelAdmission billPersonnelAdmission = billPersonnelAdmissionMapper.selectById(id);
            BillAdmissionAndGoods billAdmissionAndGoods = new BillAdmissionAndGoods();
            BeanUtil.copyProperties(billPersonnelAdmission, billAdmissionAndGoods);
            List<BillGoodsInventory> billGoodsInventories = billGoodsInventoryMapper.selectList(new QueryWrapper<BillGoodsInventory>().eq("bill_admission", id));
            billAdmissionAndGoods.setGoods(billGoodsInventories);
            return new Result(ResultCode.SUCCESS, billAdmissionAndGoods);
        } else if (type.equals("1")) {
            return new Result(ResultCode.SUCCESS, billPcrMapper.selectById(id));
        } else if (type.equals("2")) {
            return new Result(ResultCode.SUCCESS, billCleanMapper.selectById(id));
        } else if (type.equals("4")) {
            return new Result(ResultCode.SUCCESS, dryMapper.selectById(id));
        } else {
            return new Result(ResultCode.SUCCESS, billIsolateMapper.selectById(id));
        }
    }

    @Override
    public Result countAdmission(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String type = paramsMap.get("type");
        if ("".equals(type) || type == null) {
            type = "1";
        }
        List<ListAdmissionVo> admissionVo = null;
        QueryWrapper<BillPersonnelAdmission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        //默认今日
        if ("1".equals(type)) {
            Date timesmorning = DataUill.getTimesmorning();
            queryWrapper.ge("sub_date", timesmorning);
            admissionVo = billPersonnelAdmissionMapper.countAdmission(queryWrapper);
            for (ListAdmissionVo listAdmissionVo : admissionVo) {
                QueryWrapper<BillPersonnelAdmission> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("farm_id", farmId).ge("sub_date", timesmorning)
                        .eq("vistit_type", listAdmissionVo.getType()).eq("bill_status", 1);
                QueryWrapper<BillPersonnelAdmission> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("farm_id", farmId).ge("sub_date", timesmorning)
                        .eq("vistit_type", listAdmissionVo.getType()).eq("bill_status", 2);
                listAdmissionVo.setPassCount(billPersonnelAdmissionMapper.selectCount(queryWrapper1));
                listAdmissionVo.setRefuseCount(billPersonnelAdmissionMapper.selectCount(queryWrapper2));
            }
        } else if ("2".equals(type)) {
            // 本周
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
            queryWrapper.ge("sub_date", calendar.getTime());
            admissionVo = billPersonnelAdmissionMapper.countAdmission(queryWrapper);
            for (ListAdmissionVo listAdmissionVo : admissionVo) {
                QueryWrapper<BillPersonnelAdmission> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("farm_id", farmId).ge("sub_date", calendar.getTime())
                        .eq("vistit_type", listAdmissionVo.getType()).eq("bill_status", 1);
                QueryWrapper<BillPersonnelAdmission> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("farm_id", farmId).ge("sub_date", calendar.getTime())
                        .eq("vistit_type", listAdmissionVo.getType()).eq("bill_status", 2);
                listAdmissionVo.setPassCount(billPersonnelAdmissionMapper.selectCount(queryWrapper1));
                listAdmissionVo.setRefuseCount(billPersonnelAdmissionMapper.selectCount(queryWrapper2));
            }
        } else if ("3".equals(type)) {
            //本月
            Date timesMonthmorning = DataUill.getTimesMonthmorning();
            queryWrapper.ge("sub_date", timesMonthmorning);
            admissionVo = billPersonnelAdmissionMapper.countAdmission(queryWrapper);
            for (ListAdmissionVo listAdmissionVo : admissionVo) {
                QueryWrapper<BillPersonnelAdmission> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("farm_id", farmId).ge("sub_date", timesMonthmorning)
                        .eq("vistit_type", listAdmissionVo.getType()).eq("bill_status", 1);
                QueryWrapper<BillPersonnelAdmission> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("farm_id", farmId).ge("sub_date", timesMonthmorning)
                        .eq("vistit_type", listAdmissionVo.getType()).eq("bill_status", 2);
                listAdmissionVo.setPassCount(billPersonnelAdmissionMapper.selectCount(queryWrapper1));
                listAdmissionVo.setRefuseCount(billPersonnelAdmissionMapper.selectCount(queryWrapper2));
            }
        }
        return new Result(ResultCode.SUCCESS, admissionVo);
    }

    @Override
    public Result listTop(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String type = paramsMap.get("type");
        if ("".equals(type) || type == null) {
            type = "1";
        }
        List<ListAdmissionVo> admissionVo = null;
        QueryWrapper<BillPersonnelAdmission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        //今日
        if ("1".equals(type)) {
            Date timesmorning = DataUill.getTimesmorning();
            queryWrapper.ge("sub_date", timesmorning);
            admissionVo = billPersonnelAdmissionMapper.countAdmission(queryWrapper);
        } else if ("2".equals(type)) {
            // 本周
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
            queryWrapper.ge("sub_date", calendar.getTime());
            admissionVo = billPersonnelAdmissionMapper.countAdmission(queryWrapper);
        } else if ("3".equals(type)) {
            //本月
            Date timesMonthmorning = DataUill.getTimesMonthmorning();
            queryWrapper.ge("sub_date", timesMonthmorning);
            admissionVo = billPersonnelAdmissionMapper.countAdmission(queryWrapper);
        }
        JSONArray jsonArray = new JSONArray();
        for (ListAdmissionVo listAdmissionVo : admissionVo) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", listAdmissionVo.getType());
            jsonObject.put("count", listAdmissionVo.getCount());
            jsonArray.add(jsonObject);
        }
        JSONArray array = jsonArraySort(jsonArray, "count", true);
        return new Result(ResultCode.SUCCESS, array);
    }

    @Override
    public Result admissionTail(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String type = paramsMap.get("type");
        if ("".equals(type) || type == null) {
            type = "3";
        }
        //今日
        List<BillAdmissionVo> admissionVos = null;
        QueryWrapper<BillPersonnelAdmission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        if ("1".equals(type)) {
            Date timesmorning = DataUill.getTimesmorning();
            queryWrapper.ge("sub_date", timesmorning);
            admissionVos = billPersonnelAdmissionMapper.admissionTail(queryWrapper);
        } else if ("2".equals(type)) {
            // 本周
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
            queryWrapper.ge("sub_date", calendar.getTime());
            admissionVos = billPersonnelAdmissionMapper.admissionTail(queryWrapper);
        } else if ("3".equals(type)) {
            //本月
            Date timesMonthmorning = DataUill.getTimesMonthmorning();
            queryWrapper.ge("sub_date", timesMonthmorning);
            admissionVos = billPersonnelAdmissionMapper.admissionTail(queryWrapper);
        }
        return new Result(ResultCode.SUCCESS, admissionVos);
    }

    @Override
    public Result selectList(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String type = paramsMap.get("type");//来访类型
        String destId = paramsMap.get("destId");//目的地
        String startTime = paramsMap.get("startTime");
        String endTime = paramsMap.get("endTime");
        String pageNum = paramsMap.get("pageNum");
        String pageSize = paramsMap.get("pageSize");
        if ("".equals(pageNum) || null == pageNum) {
            pageNum = "1";
        }
        if ("".equals(pageSize) || null == pageSize) {
            pageSize = "10";
        }
        QueryWrapper<BillPersonnelAdmission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId).eq("dest_id", destId);
        queryWrapper.between("sub_date", startTime, endTime);
        Page<BillPersonnelAdmission> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        return new Result(ResultCode.SUCCESS, billPersonnelAdmissionMapper.selectPage(page, queryWrapper));
    }

    @Override
    public void printAdmission(HttpServletResponse httpServletRequest, Map<String, String> paramsMap) throws Exception {
        String ids = paramsMap.get("ids");
        String[] split = ids.split(",");
        List<BillPersonnelAdmission> list = new ArrayList<>();
        for (String s : split) {
            BillPersonnelAdmission admission = billPersonnelAdmissionMapper.selectById(s);
            list.add(admission);
        }
        Print.printAdmission(list);
    }

    /*数组排序*/
    public static JSONArray jsonArraySort(JSONArray jsonArr, String sortKey, boolean is_desc) {
        //存放排序结果json数组
        JSONArray sortedJsonArray = new JSONArray();
        //用于排序的list
        List<JSONObject> jsonValues = new ArrayList<JSONObject>();
        //将参数json数组每一项取出，放入list

        for (int i = 0; i < jsonArr.size(); i++) {
            jsonValues.add(jsonArr.getJSONObject(i));
        }
        //快速排序，重写compare方法，完成按指定字段比较，完成排序
        Collections.sort(jsonValues, new Comparator<JSONObject>() {
            //排序字段
            private final String KEY_NAME = sortKey;

            //重写compare方法
            @Override
            public int compare(JSONObject a, JSONObject b) {
                //如果用String接会导致一位数和两位数混合比对的时候不能准确比出来，要用int类型接
                //String valA = new String();
                //String valB = new String();
                Float valA = 0.00f;
                Float valB = 0.00f;
                try {
                    valA = Float.parseFloat(a.getString(KEY_NAME));
                    valB = Float.parseFloat(b.getString(KEY_NAME));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //是升序还是降序
                if (is_desc) {
                    return -valA.compareTo(valB);
                } else {
                    return -valB.compareTo(valA);
                }

            }
        });
        //将排序后结果放入结果jsonArray
        for (int i = 0; i < jsonArr.size(); i++) {
            sortedJsonArray.add(jsonValues.get(i));
        }

        return sortedJsonArray;
    }

    @Autowired
    private BillPcrMapper pcrMapper;
    @Autowired
    private BaseProcessMapper processMapper;
    @Autowired
    private BaseLocationMapper locationMapper;
    @Autowired
    private BillCleanMapper cleanMapper;
    @Autowired
    private BillIsolateMapper isolateMapper;

    @Override
    public Result listPrc(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String type = paramsMap.get("type");//类型
        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<BillPcr> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        if ("".equals(type) || null == type) {
            type = "0";
        }
        String farmId = paramsMap.get("farmId");
        QueryWrapper<BillPcr> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("farm_id", farmId).orderByDesc("sub_date");
        if ("0".equals(type)) {
            queryWrapper.in("pcr_type", 1, 2, 3);
        }
        if ("1".equals(type)) {
            queryWrapper.eq("pcr_type", 1);
        }
        if ("2".equals(type)) {
            queryWrapper.eq("pcr_type", 2);
        }
        if ("3".equals(type)) {
            queryWrapper.eq("pcr_type", 3);
        }
        QueryWrapper<BillPcr> queryWrapper1 = new QueryWrapper<>();

        queryWrapper1.eq("farm_id", farmId).orderByDesc("sub_date").eq("pcr_type", 1);
        return new Result(ResultCode.SUCCESS, pcrMapper.selectPage(page, queryWrapper), pcrMapper.selectCount(queryWrapper1));
    }

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

    @Override
    public Result editStatus(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) throws ParseException {
        String farmId = paramsMap.get("farmId");
        String type = paramsMap.get("type");
        String id = paramsMap.get("id");
        String data = paramsMap.get("data");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (StringUtils.isBlank(data)) {
            data = sdf.format(new Date());
        }
        BillPcr billPcr = pcrMapper.selectById(id);

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

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


        if (baseProcess.getProcessType() == 2 || baseProcess.getProcessType() == 1) {
            return new Result(10001, "修改失败！该申请已提前结束或者被拒绝", false);
        } else {
            if (billPcr.getDestId() >= billPcr.getTestLocationId()) { //说明当前不是目的地
                if ("1".equals(type)) {
                    billPcr.setBillStatus(1);
                    billPcr.setPcrType(2);
                    billPcr.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                    billPcr.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                    billPcr.setTestLocation(baseLocation.getLocationName());
                    billPcr.setTestLocationId(baseLocation.getId());
                    billPcr.setPassDate(sdf.parse(sdf.format(new Date())));
                    billPcr.setCheckDate(sdf.parse(data));

                    //通过生成洗消记录
                    BillClean billClean = new BillClean();
                    billClean.setPhone(billPcr.getPhone());
                    billClean.setVistitType(billPcr.getVistitType());
                    billClean.setDestName(billPcr.getDestName());
                    billClean.setDestId(billPcr.getDestId());
                    billClean.setAdmissionUserName(billPcr.getAdmissionUserName());
                    billClean.setAdmissionUserId(billPcr.getAdmissionUserId());
                    billClean.setVistitDate(billPcr.getVistitDate());
                    billClean.setSubDate(LocalDateTime.now());
                    billClean.setFarmId(billPcr.getFarmId());
                    billClean.setPassUserName(billPcr.getPassUserName());
                    billClean.setPassDate(billPcr.getPassDate());
                    billClean.setPassUserId(billPcr.getPassUserId());
                    billClean.setProcessId(billPcr.getProcessId());
                    billClean.setTestLocation(baseLocation.getLocationName());
                    billClean.setTestLocationId(baseLocation.getId());
                    billClean.setImgStatus(0);
                    billClean.setCarNum(billPcr.getCarNum());
                    cleanMapper.insert(billClean);

                    baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                    baseProcess.setCurrentLocation(baseProcess.getCurrentLocation() + "," + baseLocation.getNextLocation());
                    baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId() + "," + baseLocation.getNextId());
                    String status = baseProcess.getCurrentStatus();
                    String substring = status.substring(0, status.length() - 1);

                    baseProcess.setCurrentStatus(substring + "1," + 0);

                    processMapper.updateById(baseProcess);
                    pcrMapper.updateById(billPcr);
                    return new Result(10000, "修改成功！", true);
                } else {
                    billPcr.setBillStatus(2);
                    billPcr.setPcrType(3);
                    billPcr.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                    billPcr.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                    billPcr.setTestLocation(baseLocation.getLocationName());
                    billPcr.setTestLocationId(baseLocation.getId());
                    billPcr.setPassDate(sdf.parse(sdf.format(new Date())));
                    billPcr.setCheckDate(sdf.parse(data));

                    baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                    baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                    baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
                    String status = baseProcess.getCurrentStatus();
                    String substring = status.substring(0, status.length() - 1);

                    baseProcess.setCurrentStatus(substring + "2");
                    baseProcess.setProcessType(2);
                    processMapper.updateById(baseProcess);
                    pcrMapper.updateById(billPcr);
                    return new Result(10000, "修改成功！", true);
                }
            } else {
                if ("1".equals(type)) {
                    billPcr.setBillStatus(1);
                    billPcr.setPcrType(2);
                    billPcr.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                    billPcr.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                    billPcr.setTestLocation(baseLocation.getLocationName());
                    billPcr.setTestLocationId(baseLocation.getId());
                    billPcr.setPassDate(sdf.parse(sdf.format(new Date())));
                    billPcr.setCheckDate(sdf.parse(data));

                    baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                    baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                    baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
                    String status = baseProcess.getCurrentStatus();
                    String substring = status.substring(0, status.length() - 1);
                    baseProcess.setCurrentStatus(substring + "1");
                    baseProcess.setProcessType(1);
                    processMapper.updateById(baseProcess);
                    pcrMapper.updateById(billPcr);
                    return new Result(10000, "修改成功！", true);
                } else {
                    baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                    baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                    baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
                    String status = baseProcess.getCurrentStatus();
                    String substring = status.substring(0, status.length() - 1);
                    baseProcess.setCurrentStatus(substring + "2");
                    baseProcess.setProcessType(2);
                    billPcr.setBillStatus(2);
                    billPcr.setPcrType(3);
                    billPcr.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                    billPcr.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                    billPcr.setTestLocation(baseLocation.getLocationName());
                    billPcr.setTestLocationId(baseLocation.getId());
                    billPcr.setPassDate(sdf.parse(sdf.format(new Date())));
                    billPcr.setCheckDate(sdf.parse(data));

                    processMapper.updateById(baseProcess);
                    pcrMapper.updateById(billPcr);
                    return new Result(10000, "修改成功！", true);
                }

            }
        }
    }

    @Override
    public Result listIsolate(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String type = paramsMap.get("type");//类型
        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<BillIsolate> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        if ("".equals(type) || null == type) {
            type = "0";
        }
        String farmId = paramsMap.get("farmId");
        QueryWrapper<BillIsolate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId).orderByDesc("sub_date");
        if ("0".equals(type)) {
            queryWrapper.in("bill_status", 0, 1, 2, 3);
        }
        if ("1".equals(type)) {
            queryWrapper.eq("bill_status", 0);
        }
        if ("2".equals(type)) {
            queryWrapper.in("bill_status", 1, 2);
        }
        if ("3".equals(type)) {
            queryWrapper.eq("bill_status", 3);
        }
        QueryWrapper<BillIsolate> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("farm_id", farmId).orderByDesc("sub_date").eq("bill_status", 0);
        return new Result(ResultCode.SUCCESS, isolateMapper.selectPage(page, queryWrapper), isolateMapper.selectCount(queryWrapper1));
    }

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

    @Override
    public Result commitIsolate(HttpServletRequest httpServletRequest, BillIsolate billIsolate) {
        BillIsolate isolate = isolateMapper.selectById(billIsolate.getId());
        Date startDate = billIsolate.getIsolateStartDate();
        String dayNum = billIsolate.getIsolateDayNum();//隔离天数
        Date endDate = billIsolate.getIsolateEndDate();
        isolate.setIsolateStartDate(startDate);
        isolate.setIsolateEndDate(endDate);
        isolate.setIsolateDayNum(dayNum);
        isolate.setBillStatus(1);
        isolateMapper.updateById(isolate);
 /*       ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);
        Runnable task = new Runnable() {
            @Override
            public void run() {
                //这里写业务
                BillIsolate isolate = isolateMapper.selectById(billIsolate.getId());
                QueryWrapper<BaseLocation> locationQueryWrapper = new QueryWrapper<>();
                locationQueryWrapper.eq("farm_id", isolate.getFarmId()).eq("id", isolate.getIsolateLocationId());
                BaseLocation baseLocation = locationMapper.selectOne(locationQueryWrapper);//当前所在的位置
                QueryWrapper<BaseProcess> processQueryWrapper = new QueryWrapper<>();
                processQueryWrapper.eq("farm_id", isolate.getFarmId()).eq("id", isolate.getProcessId());
                BaseProcess baseProcess = processMapper.selectOne(processQueryWrapper);//进程
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                if (isolate.getBillStatus() == 1) {
                    isolate.setBillStatus(2);
                    if (isolate.getDestId() >= isolate.getIsolateLocationId()) { //当前不是目的地
                        if (isolate.getIsolateLocationId() == 3 && baseProcess.getDestId() > 3) {

                            //通过生成洗消记录
                            BillClean billClean = new BillClean();
                            billClean.setPhone(isolate.getPhone());
                            billClean.setVistitType(isolate.getVistitType());
                            billClean.setDestName(isolate.getDestName());
                            billClean.setDestId(isolate.getDestId());
                            billClean.setAdmissionUserName(isolate.getAdmissionUserName());
                            billClean.setAdmissionUserId(isolate.getAdmissionUserId());
                            billClean.setVistitDate(isolate.getVistitDate());
                            billClean.setSubDate(isolate.getSubDate());
                            billClean.setFarmId(isolate.getFarmId());
                            billClean.setPassUserName(isolate.getPassUserName());
                            billClean.setPassDate(isolate.getPassDate());
                            billClean.setPassUserId(isolate.getPassUserId());
                            billClean.setProcessId(isolate.getProcessId());
                            billClean.setTestLocation(baseLocation.getNextLocation());
                            billClean.setTestLocationId(baseLocation.getNextId());
                            cleanMapper.insert(billClean);
                            baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                            baseProcess.setCurrentLocation(baseProcess.getCurrentLocation() + "," + baseLocation.getNextLocation());
                            baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId() + "," + baseLocation.getNextId());
                            String status = baseProcess.getCurrentStatus();
                            String substring = status.substring(0, status.length() - 1);
                            baseProcess.setCurrentStatus(substring + "1," + 0);
                            processMapper.updateById(baseProcess);
                        } else {
                            baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                            baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                            baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
                            String status = baseProcess.getCurrentStatus();
                            String substring = status.substring(0, status.length() - 1);
                            baseProcess.setCurrentStatus(substring + "2");
                            baseProcess.setProcessType(1);
                            processMapper.updateById(baseProcess);
                        }
                    } else {
                        baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                        baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                        baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
                        String status = baseProcess.getCurrentStatus();
                        String substring = status.substring(0, status.length() - 1);
                        baseProcess.setCurrentStatus(substring + "2");
                        baseProcess.setProcessType(1);
                        processMapper.updateById(baseProcess);
                    }
                    isolateMapper.updateById(isolate);
                }
            }
        };
        // 设定延迟时间（两小时后执行，单位为秒）
        long delay = (endDate.getTime() - startDate.getTime()) / 1000;
        // 执行定时任务
        scheduler.schedule(task, delay, TimeUnit.SECONDS);*/
        return new Result(10000, "提交成功！", true);
    }

    @Override
    public Result editIsolate(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) throws ParseException {
        String id = paramsMap.get("id");
        String farmId = paramsMap.get("farmId");
        String remark = paramsMap.get("remark");//是否提前结束隔离的标识
        BillIsolate billIsolate = isolateMapper.selectById(id);
        BaseProcess baseProcess = processMapper.selectById(billIsolate.getProcessId());
        QueryWrapper<BaseLocation> locationQueryWrapper = new QueryWrapper<>();
        locationQueryWrapper.eq(StringUtils.isNotBlank(farmId), "farm_id", farmId).eq("id", billIsolate.getIsolateLocationId());
        BaseLocation baseLocation = locationMapper.selectOne(locationQueryWrapper);//当前隔离所在的位置

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String end = sdf.format(billIsolate.getIsolateEndDate());
        String start = sdf.format(billIsolate.getIsolateStartDate());
        String now = sdf.format(new Date());
        int res = now.compareTo(end);
        if (res > 0) {//当前时间晚于隔离结束时间
            if (baseProcess.getDestId().equals(billIsolate.getIsolateLocationId()) || baseProcess.getDestId() >= 13) {
                //目的地就是当前隔离地点
                baseProcess.setProcessType(1);
                baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
            } else {
                baseProcess.setProcessType(0);
                baseProcess.setCurrentLocation(baseProcess.getCurrentLocation() + "," + baseLocation.getNextLocation());
                baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId() + "," + baseLocation.getNextId());
            }
            if (billIsolate.getIsolateLocationId() == 3 && baseProcess.getDestId() >= 4) {
                //通过生成洗消记录
                BillClean billClean = new BillClean();
                billClean.setVistitType(billIsolate.getVistitType());
                billClean.setDestName(billIsolate.getDestName());
                billClean.setDestId(billIsolate.getDestId());
                billClean.setAdmissionUserName(billIsolate.getAdmissionUserName());
                billClean.setAdmissionUserId(billIsolate.getAdmissionUserId());
                billClean.setVistitDate(billIsolate.getVistitDate());
                billClean.setSubDate(LocalDateTime.now());
                billClean.setFarmId(billIsolate.getFarmId());
                billClean.setPassUserName(billIsolate.getPassUserName());
                billClean.setPassDate(billIsolate.getPassDate());
                billClean.setPassUserId(billIsolate.getPassUserId());
                billClean.setProcessId(billIsolate.getProcessId());
                billClean.setTestLocation("场内");
                billClean.setTestLocationId(4);
                billClean.setPhone(billIsolate.getPhone());
                cleanMapper.insert(billClean);
            }

            billIsolate.setIsolateRealEndDate(new Date());
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cal1 = Calendar.getInstance();
            Calendar cal2 = Calendar.getInstance();
            Date startDate = sdf1.parse(start);
            Date endDate = sdf1.parse(now);
            cal1.setTime(startDate);
            cal2.setTime(endDate);
            long days = (cal2.getTimeInMillis() - cal1.getTimeInMillis()) / (1000 * 3600 * 24);
            billIsolate.setIsolateRealDayNum(Long.toString(days));
            billIsolate.setBillStatus(2);
            billIsolate.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
            billIsolate.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));

            baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + now);

            String status = baseProcess.getCurrentStatus();
            String substring = status.substring(0, status.length() - 1);
            baseProcess.setCurrentStatus(substring + "1," + 0);

            isolateMapper.updateById(billIsolate);
            processMapper.updateById(baseProcess);
            return new Result(10000, "正常解除隔离成功！", true);
        } else {
            //提前结束隔离
            if (baseProcess.getDestId().equals(billIsolate.getIsolateLocationId())) {
                //目的地就是当前隔离地点
                baseProcess.setProcessType(1);
                baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
            } else {
                baseProcess.setProcessType(0);
                baseProcess.setCurrentLocation(baseProcess.getCurrentLocation() + "," + baseLocation.getNextLocation());
                baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId() + "," + baseLocation.getNextId());
            }

            if (billIsolate.getIsolateLocationId() == 3 && baseProcess.getDestId() >= 4) {
                //通过生成洗消记录
                BillClean billClean = new BillClean();
                billClean.setVistitType(billIsolate.getVistitType());
                billClean.setDestName(billIsolate.getDestName());
                billClean.setDestId(billIsolate.getDestId());
                billClean.setAdmissionUserName(billIsolate.getAdmissionUserName());
                billClean.setAdmissionUserId(billIsolate.getAdmissionUserId());
                billClean.setVistitDate(billIsolate.getVistitDate());
                billClean.setSubDate(LocalDateTime.now());
                billClean.setFarmId(billIsolate.getFarmId());
                billClean.setPassUserName(billIsolate.getPassUserName());
                billClean.setPassDate(billIsolate.getPassDate());
                billClean.setPassUserId(billIsolate.getPassUserId());
                billClean.setProcessId(billIsolate.getProcessId());
                billClean.setTestLocation("场内");
                billClean.setTestLocationId(4);
                billClean.setPhone(billIsolate.getPhone());
                cleanMapper.insert(billClean);
            }
            billIsolate.setIsolateRealEndDate(new Date());
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cal1 = Calendar.getInstance();
            Calendar cal2 = Calendar.getInstance();
            Date startDate = sdf1.parse(start);
            Date endDate = sdf1.parse(now);
            cal1.setTime(startDate);
            cal2.setTime(endDate);
            long days = (cal2.getTimeInMillis() - cal1.getTimeInMillis()) / (1000 * 3600 * 24);
            billIsolate.setIsolateRealDayNum(Long.toString(days));
            billIsolate.setBillStatus(3);
            billIsolate.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
            billIsolate.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));

            baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + now);

            String status = baseProcess.getCurrentStatus();
            String substring = status.substring(0, status.length() - 1);
            baseProcess.setCurrentStatus(substring + "1," + 0);

            isolateMapper.updateById(billIsolate);
            processMapper.updateById(baseProcess);
            return new Result(10000, "提前解除隔离成功！", true);
        }
    }

    @Override
    public Result listClean(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String type = paramsMap.get("type");//类型
        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<CleanAndDryVo2> cleanAndDryVo2Page = null;
        Page<CleanAndDryVo2> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        if ("".equals(type) || null == type) {
            type = "0";
        }
        String farmId = paramsMap.get("farmId");
        QueryWrapper<BillClean> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId).ne("vistit_type", 0).orderByDesc("sub_date").eq("img_status", 1);
        QueryWrapper<BillDry> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("farm_id", farmId).ne("vistit_type", 0).orderByDesc("sub_date").eq("img_status", 1);
        if ("0".equals(type)) {
            cleanAndDryVo2Page = cleanMapper.CleanAndDry2(page, farmId, "0,1,2".split(","));
        }
        ArrayList<String> arrayList = new ArrayList<>();
        if ("1".equals(type)) {
            arrayList.add("0");
            String[] s = arrayList.toArray(new String[arrayList.size()]);
            cleanAndDryVo2Page = cleanMapper.CleanAndDry2(page, farmId, s);
        }
        if ("2".equals(type)) {
            arrayList.add("1");
            String[] s = arrayList.toArray(new String[arrayList.size()]);
            cleanAndDryVo2Page = cleanMapper.CleanAndDry2(page, farmId, s);
        }
        if ("3".equals(type)) {
            arrayList.add("2");
            String[] s = arrayList.toArray(new String[arrayList.size()]);
            cleanAndDryVo2Page = cleanMapper.CleanAndDry2(page, farmId, s);
        }
        queryWrapper.eq("bill_status", 0);
        queryWrapper1.eq("bill_status", 0);
        Integer integer = cleanMapper.selectCount(queryWrapper);
        Integer integer1 = dryMapper.selectCount(queryWrapper1);
        return new Result(ResultCode.SUCCESS, cleanAndDryVo2Page, integer + integer1);

    }

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

    //清洗和洗消的检测
    @Override
    public Result editClean(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) throws ParseException {
        String result = paramsMap.get("result");
        String id = paramsMap.get("id");
        String farmId = paramsMap.get("farmId");
        BillClean billClean = cleanMapper.selectById(id);
        QueryWrapper<BaseProcess> processQueryWrapper = new QueryWrapper<>();
        processQueryWrapper.eq("farm_id", farmId).eq("id", billClean.getProcessId());
        BaseProcess baseProcess = processMapper.selectOne(processQueryWrapper);//进程

        QueryWrapper<BaseLocation> locationQueryWrapper = new QueryWrapper<>();
        locationQueryWrapper.eq("farm_id", farmId).eq("id", billClean.getTestLocationId());
        BaseLocation baseLocation = locationMapper.selectOne(locationQueryWrapper);//当前洗消检测所在的位置
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (baseProcess.getProcessType() == 2 || baseProcess.getProcessType() == 1) {
            return new Result(10001, "修改失败！该申请已提前结束或者被拒绝", false);
        } else {
            if (billClean.getDestId() >= billClean.getTestLocationId()) { //说明当前不是目的地
                if ("1".equals(result)) {
                    billClean.setBillStatus(1);
                    billClean.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                    billClean.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                    billClean.setTestLocation(baseLocation.getLocationName());
                    billClean.setTestLocationId(baseLocation.getId());
                    billClean.setPassDate(sdf.parse(sdf.format(new Date())));
                    billClean.setCheckDate(sdf.parse(sdf.format(new Date())));

                    //拉猪车结束
                    if (billClean.getTestLocationId() == 16) {
                        baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                        baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                        baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
                        String status = baseProcess.getCurrentStatus();
                        String substring = status.substring(0, status.length() - 1);
                        baseProcess.setCurrentStatus(substring + "1");
                        baseProcess.setProcessType(1);
                    } else {
                        baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                        baseProcess.setCurrentLocation(baseProcess.getCurrentLocation() + "," + baseLocation.getNextLocation());
                        baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId() + "," + baseLocation.getNextId());
                        String status = baseProcess.getCurrentStatus();
                        String substring = status.substring(0, status.length() - 1);
                        baseProcess.setCurrentStatus(substring + "1," + 0);
                    }


                    //环保车洗消合格生成烘干申请
                    if (billClean.getTestLocationId() == 12 || billClean.getTestLocationId() == 13) {
                        BillDry billDry = new BillDry();
                        billDry.setVistitType(billClean.getVistitType());
                        billDry.setDestName(billClean.getDestName());
                        billDry.setDestId(billClean.getDestId());
                        billDry.setAdmissionUserName(billClean.getAdmissionUserName());
                        billDry.setAdmissionUserId(billClean.getAdmissionUserId());
                        billDry.setVistitDate(billClean.getVistitDate());
                        billDry.setSubDate(LocalDateTime.now());
                        billDry.setFarmId(billClean.getFarmId());
                        billDry.setBillStatus(0);
                        billDry.setProcessId(billClean.getProcessId());
                        billDry.setTestLocation(baseLocation.getLocationName());
                        billDry.setTestLocationId(baseLocation.getId());
                        billDry.setPhone(billClean.getPhone());
                        billDry.setCarNum(billClean.getCarNum());
                        billDry.setImgStatus(0);
                        dryMapper.insert(billDry);
                    }
                    //拉猪车洗消合格生成烘干申请

                    if (billClean.getTestLocationId() == 15) {
                        QueryWrapper<BillClean> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("farm_id", farmId).eq("process_id", baseProcess.getId());
                        List<BillClean> billCleans = cleanMapper.selectList(queryWrapper);
                        if (billCleans.size() == 1) {
                            BillDry billDry = new BillDry();
                            billDry.setVistitType(billClean.getVistitType());
                            billDry.setDestName(billClean.getDestName());
                            billDry.setDestId(billClean.getDestId());
                            billDry.setAdmissionUserName(billClean.getAdmissionUserName());
                            billDry.setAdmissionUserId(billClean.getAdmissionUserId());
                            billDry.setVistitDate(billClean.getVistitDate());
                            billDry.setSubDate(LocalDateTime.now());
                            billDry.setFarmId(billClean.getFarmId());
                            billDry.setBillStatus(0);
                            billDry.setProcessId(billClean.getProcessId());
                            billDry.setTestLocation(baseLocation.getLocationName());
                            billDry.setTestLocationId(baseLocation.getId());
                            billDry.setPhone(billClean.getPhone());
                            billDry.setCarNum(billClean.getCarNum());
                            billDry.setImgStatus(0);
                            dryMapper.insert(billDry);
                        }
                    }

                    //送猪车洗消合格生成烘干申请
                    if (billClean.getTestLocationId() == 17) {
                        BillDry billDry = new BillDry();
                        billDry.setVistitType(billClean.getVistitType());
                        billDry.setDestName(billClean.getDestName());
                        billDry.setDestId(billClean.getDestId());
                        billDry.setAdmissionUserName(billClean.getAdmissionUserName());
                        billDry.setAdmissionUserId(billClean.getAdmissionUserId());
                        billDry.setVistitDate(billClean.getVistitDate());
                        billDry.setSubDate(LocalDateTime.now());
                        billDry.setFarmId(billClean.getFarmId());
                        billDry.setBillStatus(0);
                        billDry.setProcessId(billClean.getProcessId());
                        billDry.setTestLocation(baseLocation.getLocationName());
                        billDry.setTestLocationId(baseLocation.getId());
                        billDry.setPhone(billClean.getPhone());
                        billDry.setCarNum(billClean.getCarNum());
                        billDry.setImgStatus(0);
                        dryMapper.insert(billDry);
                    }
                    processMapper.updateById(baseProcess);
                    cleanMapper.updateById(billClean);
                    return new Result(10000, "修改成功！", true);
                } else {
                    billClean.setBillStatus(2);
                    billClean.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                    billClean.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                    billClean.setTestLocation(baseLocation.getLocationName());
                    billClean.setTestLocationId(baseLocation.getId());
                    billClean.setPassDate(sdf.parse(sdf.format(new Date())));
                    billClean.setCheckDate(sdf.parse(sdf.format(new Date())));
                    billClean.setImgStatus(0);

                    baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                    baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                    baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
                    String status = baseProcess.getCurrentStatus();
                    String substring = status.substring(0, status.length() - 1);

                    baseProcess.setCurrentStatus(substring + "2");
                    baseProcess.setProcessType(2);
                    processMapper.updateById(baseProcess);
                    cleanMapper.updateById(billClean);
                    return new Result(10000, "修改成功！", true);
                }
            } else {
                if ("1".equals(result)) {
                    billClean.setBillStatus(1);
                    billClean.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                    billClean.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                    billClean.setTestLocation(baseLocation.getLocationName());
                    billClean.setTestLocationId(baseLocation.getId());
                    billClean.setPassDate(sdf.parse(sdf.format(new Date())));
                    billClean.setCheckDate(sdf.parse(sdf.format(new Date())));

                    baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                    baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                    baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
                    String status = baseProcess.getCurrentStatus();
                    String substring = status.substring(0, status.length() - 1);
                    baseProcess.setCurrentStatus(substring + "1");
                    baseProcess.setProcessType(1);
                    processMapper.updateById(baseProcess);
                    cleanMapper.updateById(billClean);
                    return new Result(10000, "修改成功！", true);
                } else {
                    baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                    baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                    baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
                    String status = baseProcess.getCurrentStatus();
                    String substring = status.substring(0, status.length() - 1);
                    baseProcess.setCurrentStatus(substring + "2");
                    baseProcess.setProcessType(2);
                    billClean.setBillStatus(2);
                    billClean.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                    billClean.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                    billClean.setTestLocation(baseLocation.getLocationName());
                    billClean.setTestLocationId(baseLocation.getId());
                    billClean.setPassDate(sdf.parse(sdf.format(new Date())));
                    billClean.setCheckDate(sdf.parse(sdf.format(new Date())));
                    billClean.setImgStatus(0);

                    processMapper.updateById(baseProcess);
                    cleanMapper.updateById(billClean);
                    return new Result(10000, "修改成功！", true);
                }

            }
        }
    }

    //烘干检测
    @Override
    public Result editDry(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) throws ParseException {
        String result = paramsMap.get("result");
        String id = paramsMap.get("id");
        String farmId = paramsMap.get("farmId");
        BillDry billClean = dryMapper.selectById(id);
        QueryWrapper<BaseProcess> processQueryWrapper = new QueryWrapper<>();
        processQueryWrapper.eq("farm_id", farmId).eq("id", billClean.getProcessId());
        BaseProcess baseProcess = processMapper.selectOne(processQueryWrapper);//进程

        QueryWrapper<BaseLocation> locationQueryWrapper = new QueryWrapper<>();
        locationQueryWrapper.eq("farm_id", farmId).eq("id", billClean.getTestLocationId());
        BaseLocation baseLocation = locationMapper.selectOne(locationQueryWrapper);//当前洗消检测所在的位置
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (baseProcess.getProcessType() == 2 || baseProcess.getProcessType() == 1) {
            return new Result(10001, "修改失败！该申请已提前结束或者被拒绝", false);
        } else {
            if (billClean.getDestId() >= billClean.getTestLocationId()) { //说明当前不是目的地
                if ("1".equals(result)) {
                    billClean.setBillStatus(1);
                    billClean.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                    billClean.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                    billClean.setTestLocation(baseLocation.getLocationName());
                    billClean.setTestLocationId(baseLocation.getId());
                    billClean.setPassDate(sdf.parse(sdf.format(new Date())));
                    billClean.setCheckDate(sdf.parse(sdf.format(new Date())));

                    //最终结束
                    if (billClean.getTestLocationId() == 13 || billClean.getTestLocationId() == 58 || billClean.getTestLocationId() == 43) {
                        baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                        baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                        baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
                        String status = baseProcess.getCurrentStatus();
                        String substring = status.substring(0, status.length() - 1);
                        baseProcess.setCurrentStatus(substring + "1");
                        baseProcess.setProcessType(1);
                    } else {
                        baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                        baseProcess.setCurrentLocation(baseProcess.getCurrentLocation() + "," + baseLocation.getNextLocation());
                        baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId() + "," + baseLocation.getNextId());
                        String status = baseProcess.getCurrentStatus();
                        String substring = status.substring(0, status.length() - 1);
                        baseProcess.setCurrentStatus(substring + "1," + 0);
                    }

                    //环保车烘干合格生成洗消申请
                    if (billClean.getTestLocationId() == 12 && baseProcess.getDestId() > 12) {

                        BillClean clean = new BillClean();
                        clean.setVistitType(billClean.getVistitType());
                        clean.setDestName(billClean.getDestName());
                        clean.setDestId(billClean.getDestId());
                        clean.setAdmissionUserName(billClean.getAdmissionUserName());
                        clean.setAdmissionUserId(billClean.getAdmissionUserId());
                        clean.setVistitDate(billClean.getVistitDate());
                        clean.setSubDate(LocalDateTime.now());
                        clean.setFarmId(billClean.getFarmId());
                        clean.setBillStatus(0);
                        clean.setProcessId(billClean.getProcessId());
                        clean.setTestLocationId(baseLocation.getNextId());
                        clean.setTestLocation(baseLocation.getNextLocation());
                        clean.setPhone(billClean.getPhone());
                        clean.setCarNum(billClean.getCarNum());
                        clean.setImgStatus(0);
                        cleanMapper.insert(clean);
                    }


                    //拉猪车烘干合格生成洗消申请
                    if (billClean.getTestLocationId() == 15) {
                        BillClean clean = new BillClean();
                        clean.setVistitType(billClean.getVistitType());
                        clean.setDestName(billClean.getDestName());
                        clean.setDestId(billClean.getDestId());
                        clean.setAdmissionUserName(billClean.getAdmissionUserName());
                        clean.setAdmissionUserId(billClean.getAdmissionUserId());
                        clean.setVistitDate(billClean.getVistitDate());
                        clean.setSubDate(LocalDateTime.now());
                        clean.setFarmId(billClean.getFarmId());
                        clean.setBillStatus(0);
                        clean.setProcessId(billClean.getProcessId());
                        clean.setTestLocationId(baseLocation.getId());
                        clean.setTestLocation(baseLocation.getLocationName());
                        clean.setPhone(billClean.getPhone());
                        clean.setCarNum(billClean.getCarNum());
                        clean.setImgStatus(0);
                        cleanMapper.insert(clean);
                    }

                    processMapper.updateById(baseProcess);
                    dryMapper.updateById(billClean);
                    return new Result(10000, "修改成功！", true);
                } else {
                    billClean.setBillStatus(2);
                    billClean.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                    billClean.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                    billClean.setTestLocation(baseLocation.getLocationName());
                    billClean.setTestLocationId(baseLocation.getId());
                    billClean.setPassDate(sdf.parse(sdf.format(new Date())));
                    billClean.setCheckDate(sdf.parse(sdf.format(new Date())));
                    billClean.setImgStatus(0);

                    baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                    baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                    baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
                    String status = baseProcess.getCurrentStatus();
                    String substring = status.substring(0, status.length() - 1);

                    baseProcess.setCurrentStatus(substring + "2");
                    baseProcess.setProcessType(2);
                    processMapper.updateById(baseProcess);
                    dryMapper.updateById(billClean);
                    return new Result(10000, "修改成功！", true);
                }
            } else {
                if ("1".equals(result)) {
                    billClean.setBillStatus(1);
                    billClean.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                    billClean.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                    billClean.setTestLocation(baseLocation.getLocationName());
                    billClean.setTestLocationId(baseLocation.getId());
                    billClean.setPassDate(sdf.parse(sdf.format(new Date())));
                    billClean.setCheckDate(sdf.parse(sdf.format(new Date())));

                    baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                    baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                    baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
                    String status = baseProcess.getCurrentStatus();
                    String substring = status.substring(0, status.length() - 1);
                    baseProcess.setCurrentStatus(substring + "1");
                    baseProcess.setProcessType(1);
                    processMapper.updateById(baseProcess);
                    dryMapper.updateById(billClean);
                    return new Result(10000, "修改成功！", true);
                } else {
                    baseProcess.setUpdateDate(baseProcess.getUpdateDate() + "," + sdf.format(new Date()));
                    baseProcess.setCurrentLocation(baseProcess.getCurrentLocation());
                    baseProcess.setCurrentLocationId(baseProcess.getCurrentLocationId());
                    String status = baseProcess.getCurrentStatus();
                    String substring = status.substring(0, status.length() - 1);
                    baseProcess.setCurrentStatus(substring + "2");
                    baseProcess.setProcessType(2);
                    billClean.setBillStatus(2);
                    billClean.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                    billClean.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                    billClean.setTestLocation(baseLocation.getLocationName());
                    billClean.setTestLocationId(baseLocation.getId());
                    billClean.setPassDate(sdf.parse(sdf.format(new Date())));
                    billClean.setCheckDate(sdf.parse(sdf.format(new Date())));
                    billClean.setImgStatus(0);

                    processMapper.updateById(baseProcess);
                    dryMapper.updateById(billClean);
                    return new Result(10000, "修改成功！", true);
                }

            }
        }
    }

}
