package com.huimv.receive.service.impl;

import cn.hutool.core.util.ObjectUtil;
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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.entity.*;
import com.huimv.receive.entity.vo.BaseProcessByLocationVo;
import com.huimv.receive.entity.vo.BaseProcessVo;
import com.huimv.receive.entity.vo.ProcessVo;
import com.huimv.receive.mapper.*;
import com.huimv.receive.service.IBaseProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 流程表 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-07-21
 */
@Service
public class BaseProcessServiceImpl extends ServiceImpl<BaseProcessMapper, BaseProcess> implements IBaseProcessService {

    @Autowired
    private BaseProcessMapper baseProcessMapper;
    @Autowired
    private BillPcrMapper pcrMapper;
    @Autowired
    private BillCleanMapper cleanMapper;
    @Autowired
    private BillCleanBeforeMapper cleanBeforeMapper;
    @Autowired
    private BillDryMapper dryMapper;
    @Autowired
    private BillIsolateMapper isolateMapper;
    @Autowired
    private BillSamplingMapper samplingMapper;
    @Autowired
    private BillGoodsInventoryMapper goodsInventoryMapper;
    @Autowired
    private BillPersonnelAdmissionMapper admissionMapper;
    @Autowired
    private SysAccountMultilevelMapper accountMultilevelMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Override
    public Result getOne(Map<String, String> map) {
        String id = map.get("processId");
        BaseProcess byId = this.getById(id);
        String[] allLocation = byId.getAllLocation().split(",");
        String[] allLocationId = byId.getAllLocationId().split(",");
        String[] allLocationStatus = byId.getAllLocationStatus().split(",");
        List list = new ArrayList();
        for (int i = 0; i < allLocation.length; i++) {
            BaseProcessVo baseProcessVo = new BaseProcessVo();
            baseProcessVo.setAllLocation(allLocation[i]);
            baseProcessVo.setAllLocationId(allLocationId[i]);
            baseProcessVo.setAllLocationSatus(allLocationStatus[i]);
            list.add(baseProcessVo);
        }
        return new Result(ResultCode.SUCCESS,list);
    }

    @Override
    public Result pageByLocationId(Map<String, String> map) {
        String locationId = map.get("locationId");
        String processId = map.get("processId");
        List<BaseProcessByLocationVo> baseProcessByLocationVos =  baseProcessMapper.pageByLocationId(locationId,processId);
        for (BaseProcessByLocationVo baseProcessByLocationVo : baseProcessByLocationVos) {
            String imgUrl = baseProcessByLocationVo.getImgUrl();
            if (StringUtils.isNotBlank(imgUrl)){
                List<String> list = Arrays.asList(imgUrl.split(","));
                baseProcessByLocationVo.setImgUrls(list);
            }
            String carryImgUrl = baseProcessByLocationVo.getCarryImgUrl();
            if (StringUtils.isNotBlank(carryImgUrl)){
                List<String> carryImgUrlList = Arrays.asList(carryImgUrl.split(","));
                baseProcessByLocationVo.setCarryImgUrls(carryImgUrlList);
            }
        }
        return new Result(ResultCode.SUCCESS,baseProcessByLocationVos);
    }

    @Override
    public Result listAll(HttpServletRequest httpServletRequest,Map<String, String> map) {
        Integer id = TokenSign.getMemberIdByJwtToken(httpServletRequest);//账户id
        SysAccountMultilevel sysAccountMultilevel = accountMultilevelMapper.selectById(id);
        String farmId = map.get("farmId");
        String type = map.get("type");//0 全部 1进行中 2 已完成
        String pageNum = map.get("pageNum");
        String pageSize = map.get("pageSize");
        if ("".equals(type) || null == type) {
            type = "0";
        }
        QueryWrapper<BaseProcess> queryWrapper = new QueryWrapper<>();
        if ("0".equals(type)) {
            queryWrapper.in("a.process_type", 0, 1, 2,3);
        } else if ("1".equals(type)) {
            queryWrapper.eq("a.process_type", 0);
        } else {
            queryWrapper.in("a.process_type", 1, 2,3);
        }
        queryWrapper.orderByDesc("a.sub_date");
        Page<ProcessVo> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        QueryWrapper<BaseProcess> queryWrapper1 = new QueryWrapper<>();
        if (sysAccountMultilevel.getType() == 3) {
            SysUser user = userMapper.selectById(sysAccountMultilevel.getUserId());
            if (user.getIsAllFarm() == 1) {
                queryWrapper1.eq("process_type", 0);
            } else {
                queryWrapper1.eq("farm_id", farmId).eq("process_type", 0);
                queryWrapper.eq("a.farm_id", farmId);
            }
        } else {
            queryWrapper1.eq("farm_id", farmId).eq("process_type", 0);
            queryWrapper.eq("a.farm_id", farmId);
        }

        return new Result(ResultCode.SUCCESS, baseProcessMapper.listAll(queryWrapper, page),baseProcessMapper.selectCount(queryWrapper1));
    }

    @Override
    public Result edit(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String processId = paramsMap.get("processId");
        BaseProcess baseProcess = baseProcessMapper.selectById(processId);
        baseProcess.setProcessType(3);
        String currentFlowId = baseProcess.getCurrentFlowId();
        //入场申请未审核，直接结束流程
        BillPersonnelAdmission admission = admissionMapper.selectOne(new QueryWrapper<BillPersonnelAdmission>().eq("process_id", processId));
        if (admission.getBillStatus() == 0) {
            admission.setBillStatus(2);
            admission.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
            admission.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
            admission.setPassDate(LocalDateTime.now());
            admissionMapper.updateById(admission);
            baseProcessMapper.updateById(baseProcess);
            return new Result(ResultCode.SUCCESS);
        }
        int count = 0;
        char l = '0';
        for (int i = 0; i < currentFlowId.length(); i++) {
            if (currentFlowId.charAt(i) == l) {
                count++;
            }
        }
        String allLocationId = baseProcess.getAllLocationStatus();
        int a = 2 + 4 * (count - 1);

        String ss2=allLocationId.substring(0, a) + '4' + allLocationId.substring(a + 1);
        baseProcess.setAllLocationStatus(ss2);

        String s = currentFlowId.substring(currentFlowId.length() - 1);
        if ("1".equals(s)) {
            BillSampling billSampling = samplingMapper.selectOne(new QueryWrapper<BillSampling>()
                    .eq("process_id", processId).orderByDesc("id").last(" limit 1"));
            if (ObjectUtil.isNotEmpty(billSampling)) {
                billSampling.setBillStatus(3);
                billSampling.setPassDate(LocalDateTime.now());
                billSampling.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                billSampling.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                samplingMapper.updateById(billSampling);
            }

        } else if ("2".equals(s)) {
            BillPcr billSampling = pcrMapper.selectOne(new QueryWrapper<BillPcr>()
                    .eq("process_id", processId).orderByDesc("id").last(" limit 1"));
            if (ObjectUtil.isNotEmpty(billSampling)) {
                billSampling.setBillStatus(4);
                billSampling.setPassDate(new Date());
                billSampling.setPcrType(4);
                billSampling.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                billSampling.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                pcrMapper.updateById(billSampling);
            }

        }else if ("3".equals(s)) {
            BillClean billSampling = cleanMapper.selectOne(new QueryWrapper<BillClean>()
                    .eq("process_id", processId).orderByDesc("id").last(" limit 1"));
            if (ObjectUtil.isNotEmpty(billSampling)) {
                billSampling.setBillStatus(3);
                billSampling.setPassDate(new Date());
                billSampling.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                billSampling.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                cleanMapper.updateById(billSampling);
            }

        }else if ("4".equals(s)) {
            BillIsolate billSampling = isolateMapper.selectOne(new QueryWrapper<BillIsolate>()
                    .eq("process_id", processId).orderByDesc("id").last(" limit 1"));
            if (ObjectUtil.isNotEmpty(billSampling)) {
                billSampling.setBillStatus(4);
                billSampling.setPassDate(new Date());
                billSampling.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                billSampling.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                isolateMapper.updateById(billSampling);
            }

        }else if ("5".equals(s)) {
            BillDry billSampling = dryMapper.selectOne(new QueryWrapper<BillDry>()
                    .eq("process_id", processId).orderByDesc("id").last(" limit 1"));
            if (ObjectUtil.isNotEmpty(billSampling)) {
                billSampling.setBillStatus(3);
                billSampling.setPassDate(new Date());
                billSampling.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                billSampling.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                dryMapper.updateById(billSampling);
            }

        }else if ("6".equals(s)) {
            BillCleanBefore billSampling = cleanBeforeMapper.selectOne(new QueryWrapper<BillCleanBefore>()
                    .eq("process_id", processId).orderByDesc("id").last(" limit 1"));
            if (ObjectUtil.isNotEmpty(billSampling)) {
                billSampling.setBillStatus(3);
                billSampling.setPassDate(LocalDateTime.now());
                billSampling.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                billSampling.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                cleanBeforeMapper.updateById(billSampling);
            }

        }else if ("7".equals(s)) {
            BillGoodsInventory billSampling = goodsInventoryMapper.selectOne(new QueryWrapper<BillGoodsInventory>()
                    .eq("process_id", processId).orderByDesc("id").last(" limit 1"));
            if (ObjectUtil.isNotEmpty(billSampling)) {
                billSampling.setBillStatus(3);
                billSampling.setSubDate(LocalDateTime.now());
                billSampling.setPassUserName(TokenSign.getUserNameByJwtToken(httpServletRequest));
                billSampling.setPassUserId(TokenSign.getMemberIdByJwtToken(httpServletRequest));
                goodsInventoryMapper.updateById(billSampling);
            }

        }
        baseProcessMapper.updateById(baseProcess);
        return new Result(ResultCode.SUCCESS);
    }

    public static void main(String[] args) {
        String s = "1,2,0";
//        System.out.println(s.substring(s.length() - 1));
//        String[] strings = s.split(",");
//        String ss2 = "";
        int a = 2;
        System.out.println(s.substring(0, a) + '4' + s.substring(a + 1));



        String fl="0,1,2,0,1,2";
        int count = 0;
        char l = '0';
        for (int i = 0; i < fl.length(); i++) {
            if (fl.charAt(i) == '0') {
                count++;
            }
        }
        System.out.println(count);
    }
}
