package com.mvc.service.taizhang;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.constant.DeviceState;
import com.mvc.dao.TStkinDetailMapper;
import com.mvc.dao.TStkinMapper;
import com.mvc.entity.*;
import com.mvc.model.*;
import com.mvc.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class TStkinService {

    @Autowired(required = false)
    private TStkinMapper tStkinMapper;

    @Autowired(required = false)
    private TStkinDetailMapper tStkinDetailMapper;

    @Autowired
    private DeviceAccService deviceAccService;

    @Autowired
    private StateChangeLogService stateChangeLogService;

    @Autowired
    private TStkinDetailService tStkinDetailService;

    @Autowired
    private TaskBatchRemoteService taskBatchRemoteService;

    @Autowired
    private BatteryAccService batteryAccService;

    public Map<String, Object> findAllTStkin(TStkinModel model) {
        Map<String, Object> resMap = new HashMap<>();
        int page = model.getPage();
        int rows = model.getRows();
        Page<Object> pageObject = PageHelper.startPage(page, rows);
        TStkinExample example = new TStkinExample();
        TStkinExample.Criteria criteria = example.createCriteria();
        //根据入库编号
        if (StringUtils.isNotEmpty(model.getBillCode())) {
            criteria.andBillCodeLike(model.getBillCode());
        }
        //根据库房名称
        if (StringUtils.isNotEmpty(model.getStkroomName())) {
            criteria.andStkroomNameLike("%" + model.getStkroomName() + "%");
        }
        //作废状态
        if (StringUtils.isNotEmpty(model.getInvaildFlag())) {
            criteria.andInvaildFlagEqualTo((model.getInvaildFlag()));
        }
        //任务状态(0作废,1待入库,2已入库)
        if (StringUtils.isNotEmpty(model.getFinishedFlag())) {
            criteria.andFinishedFlagEqualTo(model.getFinishedFlag());
        }
        //入库人
        if (StringUtils.isNotEmpty(model.getStkinMan())) {
            criteria.andStkinManLike("%" + model.getStkinMan() + "%");
        }
        //开始时间
        if (StringUtils.isNotEmpty(model.getStartTime())) {
            criteria.andStkinTimeGreaterThanOrEqualTo(DateUtil.parseTimeStr(model.getStartTime(), "yyyyMMddHHmmss"));
        }
        //结束时间
        if (StringUtils.isNotEmpty(model.getEndTime())) {
            criteria.andStkinTimeLessThanOrEqualTo(DateUtil.parseTimeStr(model.getEndTime(), "yyyyMMddHHmmss"));
        }
        example.setOrderByClause("STKIN_TIME DESC");
        List<TStkin> TStkins = tStkinMapper.selectByExample(example);
        List<TStkinModel> resList = new ArrayList<>();
        for (TStkin TStkin : TStkins) {
            TStkinModel resmodel = new TStkinModel();
            BeanUtils.copyProperties(TStkin, resmodel);

            if (StringUtils.isNotEmpty(resmodel.getTaskBatchId())) {
                TaskBatchRemoteModel remoteModel = taskBatchRemoteService.findTaskBatchRemoteByTaskBatchId(resmodel.getTaskBatchId());
                resmodel.setTaskBatchRemoteModel(remoteModel);
            }

            List<TStkinDetailModel> details = tStkinDetailService.findBybillCode(resmodel.getBillCode());
            resmodel.setDetailModels(details);
            resmodel.setStkinNum(details == null ? 0 : details.size());

            resList.add(resmodel);
        }
        resMap.put("total", pageObject.getTotal());
        resMap.put("list", resList);
        return resMap;
    }

    public TStkinModel saveTStkin(TStkinModel model) {
        Date nowdate = new Date();
        String date = DateUtil.formateDate(nowdate, "yyyyMMdd");
        int l = 1 + (int) tStkinMapper.countByExample(null);
        String index = ("000000" + l).substring(("000000" + l).length() - 6);
        model.setBillCode(date + "_" + index);
        model.setDayBillyIndex(Integer.valueOf(index));
        //String devsns = model.getDevsns();
        //String[] split = devsns.split(",");
        //model.setStkinNum(split.length);
        model.setStkinTime(nowdate);
        model.setInvaildFlag("0");
        model.setFinishedFlag("1");
        TStkin TStkin = new TStkin();
        BeanUtils.copyProperties(model, TStkin);
        int insert = tStkinMapper.insert(TStkin);
        model.setId(TStkin.getId());
        addDetails(model);
        //updateDetails(model);//改到确认入库后再更新明细状态
        //updateStkInNum(model);//不在库中记录数量,使用明细的size
/*        for(int i=0;i<model.getDetailModels().size();i++){
            //查找设备
            TStkinDetailModel detail=model.getDetailModels().get(i);
            if(StringUtils.isEmpty(detail.getDeviceSn())) continue;         //前台20条一批次,后面可能是空记录
            //DeviceAccModel deviceAcc = deviceAccService.findDeviceAccBysn(detail.getDeviceSn());
            DeviceAccModel deviceAcc=detail.getDeviceAccModel();//在校验的时候获取台账 2022-11-02 guozhao
            //TStkinDetail detail=new TStkinDetail();
            detail.setDeatilId(model.getBillCode()+"_"+detail.getDeviceSn());
            detail.setBillCode(model.getBillCode());
            //detail.setDeviceSn(split[i]);
            detail.setDeviceType(deviceAcc.getDeviceType());
            detail.setStkroomId(model.getStkroomId());
            detail.setStkroomName(model.getStkroomName());

            TStkinDetail entity=new TStkinDetail();
            BeanUtils.copyProperties(detail,entity);
            tStkinDetailMapper.insert(entity);

            //生成设备状态表记录
            StateChangeLogModel logModel=new StateChangeLogModel();
            logModel.setStateChangeId(DateUtil.formateDate(nowdate,"yyyyMMddHHmmss")+"_"+detail.getDeviceSn()+"_"+DeviceState.Ruku.getFlag());
            logModel.setDeviceSn(detail.getDeviceSn());
            logModel.setStateType(DeviceState.Ruku.getFlag());
            logModel.setCreateTime(nowdate);
            stateChangeLogService.saveStateChangeLog(logModel);
            //更新设备台账设备状态
            deviceAcc.setBatCode(detail.getBatCode());
            deviceAcc.setCurStateType(DeviceState.Ruku.getFlag());
            deviceAccService.updateDeviceAcc(deviceAcc);

            //更新电池台账
            batteryAccService.updateBatteryStatus(detail.getBatCode(),DeviceState.Ruku.getFlag());
        }*/
        return model;
    }

    //根据单据编号查询主表
    public TStkinModel findTStkinByBillCode(String billCode) {
        TStkinExample example = new TStkinExample();
        TStkinExample.Criteria criteria = example.createCriteria();
        criteria.andBillCodeEqualTo(billCode);
        List<TStkin> TStkins = tStkinMapper.selectByExample(example);
        if (TStkins.size() > 0) {
            TStkinModel resModel = new TStkinModel();
            BeanUtils.copyProperties(TStkins.get(0), resModel);
            return resModel;
        } else {
            return null;
        }
    }

    public TStkinModel updateTStkin(TStkinModel model) {
        TStkin tStkin = tStkinMapper.selectByPrimaryKey(model.getId());
        if (!model.getFinishedFlag().equals(tStkin.getFinishedFlag())) {
            if (model.getFinishedFlag().equals("2")) {//确认入库
                model.setFinishedTime(new Date());
                updateDeviceStatus(model);
            }
        }
        BeanUtils.copyProperties(model, tStkin);
        if (tStkinMapper.updateByPrimaryKey(tStkin) > 0 && !tStkin.getStkroomId().equals(model.getStkroomId())) {
            //如果库房发生变更，更新明细库房(这里更新的是之前入库的)
            List<TStkinDetailModel> details = tStkinDetailService.findBybillCode(tStkin.getBillCode());
            for (int i = 0; i < details.size(); i++) {
                TStkinDetailModel tStkinDetailModel = details.get(i);
                tStkinDetailModel.setStkroomId(tStkin.getStkroomId());
                tStkinDetailModel.setStkroomName(tStkin.getStkroomName());
                tStkinDetailService.updateTStkinDetail(tStkinDetailModel);
            }
        }
        //新增方法只可添加明细,因此明细里的是要新增的
        if (model.getDataType() != null && model.getDataType() != 1) {
            addDetails(model);
            //updateDetails(model);//确认后再更新 2022-12-03 guozhao
            //updateStkInNum(model);
        }

        return model;
    }

    public int deleteTStkin(TStkinModel model) {
        TStkin tStkin = tStkinMapper.selectByPrimaryKey(model.getId());
        tStkin.setInvaildFlag("1");
        tStkin.setFinishedFlag("0");//状态统一使用FinishedFlag
        tStkin.setInvalidTime(new Date());
        tStkin.setInvalidMan(model.getInvalidMan());
        tStkin.setInvalidBecause(model.getInvalidBecause());
        int i = tStkinMapper.updateByPrimaryKey(tStkin);
        return i;
    }

    private void addDetails(TStkinModel model) {
        Date nowdate = new Date();
        for (int i = 0; i < model.getDetailModels().size(); i++) {
            //查找设备
            TStkinDetailModel detail = model.getDetailModels().get(i);
            if (StringUtils.isEmpty(detail.getDeviceSn())) continue;         //前台20条一批次,后面可能是空记录
            DeviceAccModel deviceAcc = detail.getDeviceAccModel();//在校验的时候获取台账 2022-11-02 guozhao
            if (deviceAcc == null) {
                deviceAcc = deviceAccService.findDeviceAccBysn(detail.getDeviceSn());
            }
            detail.setDeatilId(model.getBillCode() + "_" + detail.getDeviceSn());
            detail.setBillCode(model.getBillCode());
            //detail.setDeviceSn(split[i]);
            detail.setDeviceType(deviceAcc.getDeviceType());
            detail.setStkroomId(model.getStkroomId());
            detail.setStkroomName(model.getStkroomName());

            TStkinDetail entity = new TStkinDetail();
            BeanUtils.copyProperties(detail, entity);
            tStkinDetailMapper.insert(entity);
        }
    }

    /**
     * 更新明细
     *
     * @param model
     */
    private void updateDeviceStatus(TStkinModel model) {
        if (model.getDetailModels() == null) {
            List<TStkinDetailModel> details = tStkinDetailService.findBybillCode(model.getBillCode());
            if (details == null) return;
            model.setDetailModels(details);
        }
        Date nowdate = new Date();
        for (int i = 0; i < model.getDetailModels().size(); i++) {
            //查找设备
            TStkinDetailModel detail = model.getDetailModels().get(i);
            if (StringUtils.isEmpty(detail.getDeviceSn())) continue;         //前台20条一批次,后面可能是空记录
            //DeviceAccModel deviceAcc = deviceAccService.findDeviceAccBysn(detail.getDeviceSn());
            DeviceAccModel deviceAcc = detail.getDeviceAccModel();//在校验的时候获取台账 2022-11-02 guozhao
            if (deviceAcc == null) {
                deviceAcc = deviceAccService.findDeviceAccBysn(detail.getDeviceSn());
            }

            //生成设备状态表记录
            StateChangeLogModel logModel = new StateChangeLogModel();
            logModel.setStateChangeId(DateUtil.formateDate(nowdate, "yyyyMMddHHmmss") + "_" + detail.getDeviceSn() + "_" + DeviceState.Ruku.getFlag());
            logModel.setDeviceSn(detail.getDeviceSn());
            logModel.setStateType(DeviceState.Ruku.getFlag());
            logModel.setCreateTime(nowdate);
            stateChangeLogService.saveStateChangeLog(logModel);
            //更新设备台账设备状态
            deviceAcc.setBatCode(detail.getBatCode());
            deviceAcc.setCurStateType(DeviceState.Ruku.getFlag());
            deviceAccService.updateDeviceAcc(deviceAcc);

            //更新电池台账
            batteryAccService.updateBatteryStatus(detail.getBatCode(), DeviceState.Ruku.getFlag());
        }
    }

    /**
     * 校验数据合法性
     *
     * @param model
     * @return
     */
    public String checkDataLegitimacy(TStkinModel model) {
        if (StringUtils.isNotEmpty(model.getFinishedFlag()) && model.getFinishedFlag().equals("2")) {//确认完成时数据不需要校验 2022-12-03 guozhao
            return "";
        }
        if (StringUtils.isEmpty(model.getStkroomId())) {
            return "请选择库房";
        }
        if (model.getDataType() != 1 && model.getDetailModels() == null) {
            return "请添加设备";
        }

        List<TStkinDetailModel> addList = model.getDetailModels().stream().filter(s -> StringUtils.isNotEmpty(s.getDeviceSn())).collect(Collectors.toList());
        List<TStkinDetailModel> temps = StringUtils.isEmpty(model.getBillCode()) ? null : tStkinDetailService.findBybillCode(model.getBillCode());
        if (temps != null) {
            addList.addAll(temps);
        }

        List<String> stringList = addList.stream().map(TStkinDetailModel::getDeviceSn)
                .collect(Collectors.toList());
        long count = stringList.stream().distinct().count();

        if (stringList.size() != count) {
            return "设备SN有重复,请检查";
        }

        if (model.getDataType() == 1) return null;//修改主表不判断子表

        List<TStkinDetailModel> list = new ArrayList<>();
        for (TStkinDetailModel detail : model.getDetailModels()) {
            if (StringUtils.isNotEmpty(detail.getDeviceSn())) {
                DeviceAccModel devAcc = deviceAccService.findDeviceAccBysn(detail.getDeviceSn());
                if (devAcc == null) {
                    return "[" + detail.getDeviceSn() + "]不在设备台账中";
                } else {
                    if (devAcc.getCurStateType().equals(DeviceState.Ruku.getFlag())) {
                        return "[" + detail.getDeviceSn() + "]当前为在库状态";
                    }

                    if (StringUtils.isNotEmpty(detail.getBatCode())) {//电池不做强制卡控
                        String batCoce = detail.getBatCode().replaceAll("BAT", "");
                        BatteryAccModel batAcc = batteryAccService.findBatteryAccByBatCode(batCoce);
                        if (batAcc == null) {
                            return "[" + detail.getBatCode() + "]不在电池台账中";
                        }
                        detail.setBatCode(batCoce);
                    }
                    detail.setDeviceAccModel(devAcc);
                    list.add(detail);
                }
            }
        }

        if (list.size() == 0) {
            return "未添加任何有效设备";
        }
        model.setDetailModels(list);
        return null;
    }

    /**
     * 根据单据编号更新入库数量
     * @param billCode
     * @return
     */
/*
    public TStkinModel updateStkInNum(String billCode){
        TStkinModel model=findTStkinByBillCode(billCode);
        if(model!=null){
            List<TStkinDetailModel> details = tStkinDetailService.findBybillCode(billCode);
            model.setStkinNum(details==null?0:details.size());

            TStkin tStkout=new TStkin();
            BeanUtils.copyProperties(model, tStkout);
            tStkinMapper.updateByPrimaryKey(tStkout);
        }
        return model;
    }
*/

    /**
     * 根据TStkinModel更新入库数量(少查一次库)
     * @param model
     * @return
     */
/*    public TStkinModel updateStkInNum(TStkinModel model){
        if(model!=null){
            List<TStkinDetailModel> details = tStkinDetailService.findBybillCode(model.getBillCode());
            model.setStkinNum(details==null?0:details.size());

            TStkin tStkout=new TStkin();
            BeanUtils.copyProperties(model, tStkout);
            tStkinMapper.updateByPrimaryKey(tStkout);
        }
        return model;
    }*/
}
