package com.huimv.receive.service.impl;

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

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

/**
 * <p>
 * 洗消表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-03-11
 */
@Service
public class BillSamplingServiceImpl extends ServiceImpl<BillSamplingMapper, BillSampling> implements IBillSamplingService {

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

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

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

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



    @Override
    public Result edit(HttpServletRequest httpServletRequest, String farmId, String id, String date, MultipartFile img) throws ParseException, IOException {
        String s = "";
        if (uploadImage.getVideoCom(img).equals("上传失败")) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result(10001, "视频上传失败", false);
        }
        s = uploadImage.getVideoCom(img);

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

        BillSampling sampling = billSamplingMapper.selectById(id);
        sampling.setImgUrl(s);
        sampling.setImgStatus(1);


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

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


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


        Object newObject = BillPcrServiceImpl.getNewObject(nextId, sampling.getDestName(), sampling.getDestId(), sampling.getAdmissionUserName(),
                sampling.getAdmissionUserId(), sampling.getVistitDate(), sampling.getSubDate(),
                sampling.getProcessId(), Integer.parseInt(sampling.getFarmId()), sampling.getTestLocation(), sampling.getTestLocationId(),
                sampling.getVistitType(), sampling.getPhone());
        if (nextId == 0) {
            int index = allLocationId.indexOf(baseLocation.getId());
            StringBuilder status = new StringBuilder(baseProcess.getAllLocationId());
            status.setCharAt(index, '1');
            status.setCharAt(index + 2, '1');
            baseProcess.setAllLocationStatus(status.toString());
        } else if (nextId == 1) {
            //新增采样
            BillSampling billSampling = (BillSampling) newObject;
            billSamplingMapper.insert(billSampling);
        } else if (nextId == 2) {
            //新增pcr
            BillPcr billClean = (BillPcr) newObject;
            pcrMapper.insert(billClean);
        } else if (nextId == 3) {
            //新增洗澡
            BillClean billClean = (BillClean) newObject;
            cleanMapper.insert(billClean);
        } else if (nextId == 4) {
            //新增隔离
            BillIsolate pcr = (BillIsolate) newObject;
            isolateMapper.insert(pcr);
        } else if (nextId == 5) {
            BillDry billClean = (BillDry) newObject;
            dryMapper.insert(billClean);
            //新增烘干
        } else if (nextId == 6) {
            //新增洗澡前拍照
            BillCleanBefore before = new BillCleanBefore();
            billCleanBeforeMapper.insert(before);
        }
        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);
        baseProcess.setCurrentFlowId(baseProcess.getCurrentLocationId() + "," + nextId);
        processMapper.updateById(baseProcess);
        billSamplingMapper.updateById(sampling);
        return new Result(10000, "修改成功!", true);
    }
}
