package com.mvc.service.taizhang;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.constant.BaseConstant;
import com.mvc.constant.TaskStatus;
import com.mvc.dao.TaskSpecialCfgMapper;
import com.mvc.entity.DicProductionPart;
import com.mvc.entity.TaskSpecialCfg;
import com.mvc.entity.TaskSpecialCfgExample;
import com.mvc.model.DeviceAccModel;
import com.mvc.model.ResPageModel;
import com.mvc.model.TaskRemoteCfgModel;
import com.mvc.model.TaskSpecialCfgModel;
import com.mvc.model.produce.DicProductionPartModel;
import com.mvc.model.produce.TDeviceSnManagementModel;
import com.mvc.model.produce.TProductionPlanDetailModel;
import com.mvc.model.produce.TProductionPlanModel;
import com.mvc.service.produce.DicProductionPartService;
import com.mvc.service.produce.TDeviceSnManagementService;
import com.mvc.service.produce.TProductionPlanService;
import com.mvc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class TaskSpecialCfgService {
    @Resource
    private TaskSpecialCfgMapper taskSpecialCfgMapper;

    @Resource
    private TaskRemoteCfgService taskRemoteCfgService;

    @Resource
    private DeviceAccService deviceAccService;

    @Resource
    private TDeviceSnManagementService deviceSnManagementService;

    @Resource
    private TProductionPlanService productionPlanService;

    @Resource
    private DicProductionPartService dicProductionPartService;

    public ResPageModel findAllTaskSpecialCfg(TaskSpecialCfgModel queryModel) {
        TaskSpecialCfgExample example = new TaskSpecialCfgExample();
        TaskSpecialCfgExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(queryModel.getImei())) {
            criteria.andImeiEqualTo(queryModel.getImei());
        }
        if (StringUtils.isNotEmpty(queryModel.getDeviceSn())) {
            criteria.andDeviceSnEqualTo(queryModel.getDeviceSn());
        }
        if (StringUtils.isNotEmpty(queryModel.getSubDeviceAddress())) {
            criteria.andSubDeviceAddressEqualTo(queryModel.getSubDeviceAddress());
        }
        if (StringUtils.isNotEmpty(queryModel.getFinishedFlag())) {
            criteria.andFinishedFlagEqualTo(queryModel.getFinishedFlag());
        }
        if (StringUtils.isNotEmpty(queryModel.getCreateMan())) {
            criteria.andCreateManLike(StringUtil.getLikeFormat(queryModel.getCreateMan()));
        }
        example.setOrderByClause("id desc");
        Page<Object> pageObject = PageHelper.startPage(queryModel.getPageNum(), queryModel.getPageSize());
        List<TaskSpecialCfgModel> resList = selectByExample(example);
        ResPageModel pageModel = new ResPageModel(resList, pageObject);
        return pageModel;
    }

    /**
     * 根据IMEI查询未执行的任务
     *
     * @param imei
     * @return
     */
    public TaskSpecialCfgModel findTaskSpecialCfgsByImei(String imei) {
        if (StringUtils.isEmpty(imei)) {
            return null;
        }
        TaskSpecialCfgExample example = new TaskSpecialCfgExample();
        TaskSpecialCfgExample.Criteria criteria = example.createCriteria();
        criteria.andFinishedFlagEqualTo(TaskStatus.NOT_EXECUTED.getCode());
        criteria.andImeiEqualTo(imei);
        example.setOrderByClause("id desc");
        List<TaskSpecialCfgModel> list = selectByExample(example);
        return list.size() > 0 ? list.get(0) : null;
    }

    private List<TaskSpecialCfgModel> selectByExample(TaskSpecialCfgExample example) {
        List<TaskSpecialCfg> taskSpecialCfgs = taskSpecialCfgMapper.selectByExample(example);
        List<TaskSpecialCfgModel> resList = new ArrayList<>();
        for (TaskSpecialCfg TaskSpecialCfg : taskSpecialCfgs) {
            TaskSpecialCfgModel model = new TaskSpecialCfgModel();
            BeanUtils.copyProperties(TaskSpecialCfg, model);
            resList.add(model);
        }
        return resList;
    }

    /**
     * 保存专项配置任务(批量)
     *
     * @param model
     * @return
     */
    public String saveTaskSpecialCfg(TaskSpecialCfgModel model) {
        StringBuilder builder = new StringBuilder();
        int succNum = 0;
        int failNum = 0;
        List<String> imeiList = new ArrayList<>();
        List<String> snList = new ArrayList<>();

        int currentDeviceSnManagementId = -1;//当前设备SN管理ID,为了避免重复查询
        String cpuVersion = "";

        for (TaskSpecialCfgModel detail : model.getDetails()) {
            if (StringUtils.isEmpty(detail.getImei()) && StringUtils.isEmpty(detail.getDeviceSn())) {//都为空不计数
                continue;
            }
            if (imeiList.contains(detail.getImei()) || snList.contains(detail.getDeviceSn())) {
                builder.append(String.format("IMEI:%s,设备SN:%s : 重复%s", detail.getImei(), detail.getDeviceSn(), BaseConstant.HTML_NEW_LINE));
                failNum++;
                continue;
            }

            imeiList.add(detail.getImei());
            snList.add(detail.getDeviceSn());

            String checkInfo = checkTaskSpecialCfg(detail);
            if (StringUtils.isNotEmpty(checkInfo)) {
                builder.append(String.format("IMEI:%s,设备SN:%s : %s%s", detail.getImei(), detail.getDeviceSn(), checkInfo, BaseConstant.HTML_NEW_LINE));
                failNum++;
                continue;
            }
            detail.setCreateMan(model.getCreateMan());
            detail.setCreateTime(new Date());
            detail.setFinishedFlag(BaseConstant.INVALID_FLAG);
            TaskSpecialCfg taskSpecialCfg = new TaskSpecialCfg();
            BeanUtils.copyProperties(detail, taskSpecialCfg);
            if (taskSpecialCfgMapper.insert(taskSpecialCfg) > 0) {
                succNum++;
                //初始化设备参数 2024-12-21 guozhao
                //1.开始找生产计划中的CPU版本
                DeviceAccModel accModel = deviceAccService.findDeviceAccBysn(detail.getDeviceSn());
                if (accModel != null && accModel.getDeviceSnManagementId() != null && currentDeviceSnManagementId != accModel.getDeviceSnManagementId()) {
                    currentDeviceSnManagementId = accModel.getDeviceSnManagementId();
                    cpuVersion = getCpuVersionByDeviceSnManagementId(currentDeviceSnManagementId);
                }
                initDeviceParam(taskSpecialCfg, cpuVersion);
            } else {
                failNum++;
                builder.append(String.format("IMEI:%s,设备SN:%s : 失败%s", detail.getImei(), detail.getDeviceSn(), BaseConstant.HTML_NEW_LINE));
            }
        }

        builder.insert(0, String.format("共%d条数据,成功%d条,失败%d条%s", succNum + failNum, succNum, failNum, BaseConstant.HTML_NEW_LINE));

        return builder.toString();
    }

    /**
     * 初始化设备参数
     *
     * @param specialCfg
     * @param cpuVersion
     */
    private TaskRemoteCfgModel initDeviceParam(TaskSpecialCfg specialCfg, String cpuVersion) {
        TaskRemoteCfgModel remoteCfgModel = new TaskRemoteCfgModel();
        remoteCfgModel.setSpecialCfgId(specialCfg.getId());
        remoteCfgModel.setDeviceSn(specialCfg.getDeviceSn());
        //初始化站码为SN的后10位
        remoteCfgModel.setStationCode(specialCfg.getDeviceSn().substring(1));
        //默认不上传红色指针
        remoteCfgModel.setIsUploadRedPointer("0");
        //初始化CPU版本号
        if (StringUtils.isNotEmpty(cpuVersion)) {
            remoteCfgModel.setCpuVersion(StringUtils.leftPad(cpuVersion, 4, "0"));
        }
        remoteCfgModel.setCreateMan("专项配置");
        return taskRemoteCfgService.saveTaskRemoteCfg(remoteCfgModel);
    }

    //更新专项配置任务
    //已不使用,有了从IMEI同步过来的任务后,有导致数据不同步的可以(下行任务表)
    public TaskSpecialCfgModel updateTaskSpecialCfg(TaskSpecialCfgModel model) {
        TaskSpecialCfg taskSpecialCfg = taskSpecialCfgMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model, taskSpecialCfg);
        if (taskSpecialCfgMapper.updateByPrimaryKey(taskSpecialCfg) > 0) {
            //同步更新远程配置任务
            taskRemoteCfgService.updateTaskRemoteCfgByTaskSpecialCfg(model);
        }
        return model;
    }

    public int deleteTaskSpecialCfg(int id) {
        int i = taskSpecialCfgMapper.deleteByPrimaryKey(id);
        if (i > 0) {
            //同步删除远程配置任务
            taskRemoteCfgService.deleteTaskRemoteCfgBySpecialCfgId(id);
        }
        return i;
    }

    /**
     * 根据ID获取Model
     *
     * @param id
     * @return
     */
    public TaskSpecialCfgModel findTaskSpecialCfgModelById(int id) {
        TaskSpecialCfg taskSpecialCfg = taskSpecialCfgMapper.selectByPrimaryKey(id);
        if (taskSpecialCfg != null) {
            TaskSpecialCfgModel model = new TaskSpecialCfgModel();
            BeanUtils.copyProperties(taskSpecialCfg, model);
            return model;
        }
        return null;
    }

    /**
     * 检查任务是否合法
     *
     * @param model
     * @return
     */
    public String checkTaskSpecialCfg(TaskSpecialCfgModel model) {
        if (!StringUtils.isNumeric(model.getImei())) {
            return "IMEI格式不正确";
        }
        if (!StringUtils.isNumeric(model.getDeviceSn())) {
            return "设备SN格式不正确";
        }
        return null;
    }

    /**
     * 根据设备SN管理ID获取CPU版本
     *
     * @param deviceSnManagementId
     * @return
     */
    public String getCpuVersionByDeviceSnManagementId(int deviceSnManagementId) {
        //查询SN生成管理对象
        TDeviceSnManagementModel deviceSnModel = deviceSnManagementService.findTDeviceSnManagementModelById(deviceSnManagementId);
        //查询对应的生产计划
        TProductionPlanModel productionPlanModel = productionPlanService.getTProductionPlanById(deviceSnModel.getProducttionId());
        if (productionPlanModel != null && productionPlanModel.getDetails() != null) {
            //此处暂用固定值-10053
            Optional<TProductionPlanDetailModel> optional = productionPlanModel.getDetails().stream().filter(s -> s.getDicPartParentId() == 10053).findFirst();
            if (optional.isPresent()) {
                DicProductionPartModel partModel = dicProductionPartService.getDicProductionPartById(optional.get().getDicPartId());
                if (partModel == null || partModel.getPartName().length() < 4) {
                    return null;
                }
                String cpuVersion = partModel.getPartName().substring(partModel.getPartName().length() - 4);
                if (StringUtils.isNumeric(cpuVersion)) {
                    return cpuVersion;
                }
            }
        }
        return null;
    }
}
