package com.mvc.service.taizhang;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.constant.DeviceState;
import com.mvc.dao.TStkoutMapper;
import com.mvc.entity.TStkout;
import com.mvc.entity.TStkoutExample;
import com.mvc.model.*;
import com.mvc.service.copy.TAireadService;
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.*;

@Service
@Transactional
public class TStkoutService {

    @Autowired(required = false)
    private TStkoutMapper TStkoutMapper;

//    @Autowired
//    private TStkoutDetailMapper TStkoutDetailMapper;

    @Autowired
    private DeviceAccService deviceAccService;

    @Autowired
    private StateChangeLogService stateChangeLogService;

    @Autowired
    private TaskBatchRemoteService taskBatchRemoteService;

    @Autowired
    private TAireadService tAireadService;

    @Autowired
    private TStkoutDetailService tStkoutDetailService;

    @Autowired
    private BatteryAccService batteryAccService;

    public Map<String, Object> findAllTStkout(TStkoutModel model) {
        Map<String, Object> resMap = new HashMap<>();
        int page = model.getPage();
        int rows = model.getRows();
        Page<Object> pageObject = PageHelper.startPage(page, rows);
        TStkoutExample example = new TStkoutExample();
        TStkoutExample.Criteria criteria = example.createCriteria();
        //根据出库编号
        if (StringUtils.isNotEmpty(model.getBillCode())) {
            criteria.andBillCodeLike(model.getBillCode());
        }
        //单据状态
        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.getStkoutMan())) {
            criteria.andStkoutManLike("%" + model.getStkoutMan() + "%");
        }
        //销售商名称
        if (StringUtils.isNotEmpty(model.getAgentName())) {
            criteria.andAgentNameLike("%" + model.getAgentName() + "%");
        }
        //收货人
        if (StringUtils.isNotEmpty(model.getConsigneeInfo())) {
            criteria.andConsigneeInfoLike("%" + model.getConsigneeInfo() + "%");
        }
        //开始时间
        if (StringUtils.isNotEmpty(model.getStartTime())) {
            criteria.andStkoutTimeGreaterThanOrEqualTo(DateUtil.parseTimeStr(model.getStartTime(), "yyyyMMddHHmmss"));
        }
        //结束时间
        if (StringUtils.isNotEmpty(model.getEndTime())) {
            criteria.andStkoutTimeLessThanOrEqualTo(DateUtil.parseTimeStr(model.getEndTime(), "yyyyMMddHHmmss"));
        }
        example.setOrderByClause("STKOUT_TIME DESC");
        List<TStkout> TStkouts = TStkoutMapper.selectByExample(example);
        List<TStkoutModel> resList = new ArrayList<>();
        for (TStkout TStkout : TStkouts) {
            TStkoutModel resmodel = new TStkoutModel();
            BeanUtils.copyProperties(TStkout, resmodel);

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

            List<TStkoutDetailModel> details = tStkoutDetailService.findTStkoutDetailsBybillCode(resmodel.getBillCode());
            resmodel.setDetailModels(details);
            resmodel.setStkoutNum(details==null?0:details.size());

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

    public TStkoutModel saveTStkout(TStkoutModel model) {
        Date nowdate = new Date();
        String date = DateUtil.formateDate(nowdate, "yyyyMMdd");
        int l = 1 + (int) TStkoutMapper.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.setStkoutNum(split.length);
        model.setStkoutTime(nowdate);
        model.setInvaildFlag("0");
        model.setFinishedFlag("1");
        TStkout TStkout = new TStkout();
        BeanUtils.copyProperties(model, TStkout);
        int insert = TStkoutMapper.insert(TStkout);
        model.setId(TStkout.getId());
        addDetails(model);
        //updateStkoutNum(model);
/*        for(int i=0;i<split.length;i++){
            //查找设备
            DeviceAccModel deviceAcc = deviceAccService.findDeviceAccBysn(split[i]);
            TStkoutDetail detail=new TStkoutDetail();
            detail.setDeatilId(model.getBillCode()+"_"+split[i]);
            detail.setBillCode(model.getBillCode());
            detail.setDeviceSn(split[i]);
            detail.setDeviceType(deviceAcc.getDeviceType());
            TStkoutDetailMapper.insert(detail);

            //生成设备状态表记录
            StateChangeLogModel logModel=new StateChangeLogModel();
            logModel.setStateChangeId(DateUtil.formateDate(nowdate,"yyyyMMddHHmmss")+"_"+split[i]+"_"+ DeviceState.Chuku.getFlag());
            logModel.setDeviceSn(split[i]);
            logModel.setStateType(DeviceState.Chuku.getFlag());
            logModel.setCreateTime(nowdate);
            stateChangeLogService.saveStateChangeLog(logModel);
            //更新设备台账设备状态
            deviceAcc.setCurStateType(DeviceState.Chuku.getFlag());
            deviceAccService.updateDeviceAcc(deviceAcc);
        }*/
        return model;
    }

    private void addDetails(TStkoutModel model) {
        if (model.getDetailModels() == null) return;
        Date nowdate = new Date();
        for (TStkoutDetailModel detail : model.getDetailModels()) {
            DeviceAccModel deviceAcc = detail.getDeviceAccModel();
            detail.setDeatilId(model.getBillCode() + "_" + detail.getDeviceSn());
            detail.setBillCode(model.getBillCode());
            detail.setDeviceSn(detail.getDeviceSn());
            detail.setDeviceType(deviceAcc.getDeviceType());
            tStkoutDetailService.saveTStkoutDetail(detail);
        }
    }

    /**
     * 更新设备台账相关状态
     * @param model
     */
    private void updateDeviceStatus(TStkoutModel model){
        Date nowdate = new Date();
        for (TStkoutDetailModel detail : model.getDetailModels()) {
            DeviceAccModel deviceAcc = detail.getDeviceAccModel();
            if(deviceAcc==null){
                deviceAcc=deviceAccService.findDeviceAccBysn(detail.getDeviceSn());
            }

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

            //有电池则同步更新电池状态 2022-11-02 guozhao
            if (StringUtils.isNotEmpty(deviceAcc.getBatCode())) {
                batteryAccService.updateBatteryStatus(deviceAcc.getBatCode(), DeviceState.Chuku.getFlag());
            }
        }
    }

    //根据单据编号查询主表
    public TStkoutModel findTStkoutByBillCode(String billCode) {
        TStkoutExample example = new TStkoutExample();
        TStkoutExample.Criteria criteria = example.createCriteria();
        criteria.andBillCodeEqualTo(billCode);
        List<TStkout> TStkouts = TStkoutMapper.selectByExample(example);
        if (TStkouts.size() > 0) {
            TStkoutModel resModel = new TStkoutModel();
            BeanUtils.copyProperties(TStkouts.get(0), resModel);
            return resModel;
        } else {
            return null;
        }
    }

    public TStkoutModel updateTStkout(TStkoutModel model) {
        TStkout tStkout = TStkoutMapper.selectByPrimaryKey(model.getId());
        if(!tStkout.getFinishedFlag().equals(model.getFinishedFlag())){
            if(model.getFinishedFlag().equals("2")){
                model.setFinishedTime(new Date());
                updateDeviceStatus(model);
            }
        }

        BeanUtils.copyProperties(model, tStkout);
        int i = TStkoutMapper.updateByPrimaryKey(tStkout);

        if(model.getDataType()!=null&&model.getDataType()!=1){
            addDetails(model);
            //updateStkoutNum(model);
        }

        return model;
    }

    public int deleteTStkout(TStkoutModel model) {
        TStkout tStkout = TStkoutMapper.selectByPrimaryKey(model.getId());
        tStkout.setInvaildFlag("1");
        tStkout.setFinishedFlag("0");//状态统一使用FinishedFlag
        tStkout.setInvalidTime(new Date());
        tStkout.setInvalidMan(model.getInvalidMan());
        tStkout.setInvalidBecause(model.getInvalidBecause());
        int i = TStkoutMapper.updateByPrimaryKey(tStkout);
        return i;
    }

    /**
     * 校验数据合法性
     *
     * @param model
     * @return
     */
    public String checkDataLegitimacy(TStkoutModel model) {
        if(model.getFinishedFlag().equals("2")){//确认完成时数据不需要校验 2022-12-03 guozhao
            return "";
        }
        if (model.getDataType()!=1&&model.getDetailModels() == null) {
            return "请添加设备";
        }
        if(model.getDataType()==1) return null;//修改主表不判断子表
        List<TStkoutDetailModel> list = new ArrayList<>();
        for (TStkoutDetailModel detail : model.getDetailModels()) {
            if (StringUtils.isEmpty(detail.getDeviceSn())) continue;
            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(model.getMcuVersion())) {//有版本号则进行校验
                    TAireadModel aireadModel = tAireadService.findLatestTAireadByDeviceSn(detail.getDeviceSn());
                    if (aireadModel == null) {
                        return "[" + detail.getDeviceSn() + "]未查询到数据,无法校验版本,请先使用设备工作一次";
                    } else if (!aireadModel.getSoftVer().equals(model.getMcuVersion())) {
                        return "[" + detail.getDeviceSn() + "]MCU版本不匹配";
                    }
                }

                detail.setDeviceAccModel(devAcc);
                list.add(detail);
            }
        }

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

    /**
     * 根据单据编号更新出库数量
     * @param billCode
     * @return
     */
/*    public TStkoutModel updateStkoutNum(String billCode){
        TStkoutModel model=findTStkoutByBillCode(billCode);
        if(model!=null){
            List<TStkoutDetailModel> details = tStkoutDetailService.findTStkoutDetailsBybillCode(billCode);
            model.setStkoutNum(details==null?0:details.size());

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

    /**
     * 根据单据编号更新出库数量(少查一次库)
     * @param model
     * @return
     */
/*    public TStkoutModel updateStkoutNum(TStkoutModel model){
        if(model!=null){
            List<TStkoutDetailModel> details = tStkoutDetailService.findTStkoutDetailsBybillCode(model.getBillCode());
            model.setStkoutNum(details==null?0:details.size());

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