package com.flossom.system.service.impl;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.flossom.common.core.domain.entity.SysUser;
import com.flossom.common.core.domain.entity.WxInstrument;
import com.flossom.common.core.domain.entity.WxInstrumentSerial;
import com.flossom.common.core.domain.req.WxInstrumentSerialExportVm;
import com.flossom.common.core.domain.req.WxInstrumentSerialImportVm;
import com.flossom.common.core.exception.ServiceException;
import com.flossom.common.core.mapper.WxInstrumentMapper;
import com.flossom.common.core.mapper.WxInstrumentSerialMapper;
import com.flossom.common.core.utils.DateUtils;
import com.flossom.common.core.utils.StringUtils;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.flossom.system.service.IWxInstrumentSerialService;
import org.springframework.util.CollectionUtils;

/**
 * 仪器序列号关联Service业务层处理
 *
 * @author flossom
 * @date 2024-01-10
 */
@Service
public class WxInstrumentSerialServiceImpl implements IWxInstrumentSerialService
{
    private static final Logger log = LoggerFactory.getLogger(WxInstrumentSerialServiceImpl.class);

    @Autowired
    private WxInstrumentSerialMapper wxInstrumentSerialMapper;
    @Autowired
    private WxInstrumentMapper wxInstrumentMapper;

    /**
     * 查询仪器序列号关联
     *
     * @param id 仪器序列号关联主键
     * @return 仪器序列号关联
     */
    @Override
    public WxInstrumentSerial selectWxInstrumentSerialById(Long id)
    {
        return wxInstrumentSerialMapper.selectWxInstrumentSerialById(id);
    }

    /**
     * 查询仪器序列号关联列表
     *
     * @param wxInstrumentSerial 仪器序列号关联
     * @return 仪器序列号关联
     */
    @Override
    public List<WxInstrumentSerial> selectWxInstrumentSerialList(WxInstrumentSerial wxInstrumentSerial)
    {
        // 处理仪器字段
        if (!CollectionUtils.isEmpty(wxInstrumentSerial.getInstrumentIdArray())) {
            String instrumentIds = wxInstrumentSerial.getInstrumentIdArray().stream().map(String::valueOf).collect(Collectors.joining(","));
            wxInstrumentSerial.setQueryInstrumentIds(instrumentIds);
        }
        return wxInstrumentSerialMapper.selectWxInstrumentSerialList(wxInstrumentSerial);
    }

    /**
     * 新增仪器序列号关联
     *
     * @param wxInstrumentSerial 仪器序列号关联
     * @return 结果
     */
    @Override
    public int insertWxInstrumentSerial(WxInstrumentSerial wxInstrumentSerial)
    {
        wxInstrumentSerial.setCreateTime(DateUtils.getNowDate());
        if (Objects.nonNull(wxInstrumentSerial.getInstrumentId())) {
            WxInstrument wxInstrument = wxInstrumentMapper.selectWxInstrumentById(wxInstrumentSerial.getInstrumentId());
            if (Objects.nonNull(wxInstrument)) {
                wxInstrumentSerial.setInstrumentName(wxInstrument.getName());
            }
        }
        WxInstrumentSerial instrumentSerial = new WxInstrumentSerial();
        instrumentSerial.setSerial(wxInstrumentSerial.getSerial());
        List<WxInstrumentSerial> wxInstrumentSerials = wxInstrumentSerialMapper.selectWxInstrumentSerialList(instrumentSerial);
        if (!CollectionUtils.isEmpty(wxInstrumentSerials)) {
            throw new ServiceException("序列号已经存在，请确定后再新增！");
        }
        return wxInstrumentSerialMapper.insertWxInstrumentSerial(wxInstrumentSerial);
    }

    /**
     * 修改仪器序列号关联
     *
     * @param wxInstrumentSerial 仪器序列号关联
     * @return 结果
     */
    @Override
    public int updateWxInstrumentSerial(WxInstrumentSerial wxInstrumentSerial)
    {
        return wxInstrumentSerialMapper.updateWxInstrumentSerial(wxInstrumentSerial);
    }

    /**
     * 批量删除仪器序列号关联
     *
     * @param ids 需要删除的仪器序列号关联主键
     * @return 结果
     */
    @Override
    public int deleteWxInstrumentSerialByIds(Long[] ids)
    {
        return wxInstrumentSerialMapper.deleteWxInstrumentSerialByIds(ids);
    }

    /**
     * 删除仪器序列号关联信息
     *
     * @param id 仪器序列号关联主键
     * @return 结果
     */
    @Override
    public int deleteWxInstrumentSerialById(Long id)
    {
        return wxInstrumentSerialMapper.deleteWxInstrumentSerialById(id);
    }

    @Override
    public int deleteAll() {
        return wxInstrumentSerialMapper.deleteAll();
    }

    @Override
    public int updateRecordStatus(WxInstrumentSerial wxInstrumentSerial) {
        if(CollectionUtils.isEmpty(wxInstrumentSerial.getInstrumentSerialIdList())) {
            // 全量更新数据
            int i = wxInstrumentSerialMapper.updateAll(wxInstrumentSerial);
        } else {
            List<Long> instrumentSerialIdList = wxInstrumentSerial.getInstrumentSerialIdList();
            for (Long id : instrumentSerialIdList) {
                WxInstrumentSerial updateRecord = new WxInstrumentSerial();
                updateRecord.setId(id);
                updateRecord.setValidStatus(wxInstrumentSerial.getValidStatus());
                wxInstrumentSerialMapper.updateWxInstrumentSerial(updateRecord);
            }
        }
        return 1;
    }

    @Override
    public List<WxInstrumentSerialExportVm> handleExportData(WxInstrumentSerial wxInstrumentSerial) {
        List<WxInstrumentSerialExportVm> resultList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(wxInstrumentSerial.getInstrumentSerialIdList())) {
            // 全量搜素
            List<WxInstrumentSerial> wxInstrumentSerials = this.selectWxInstrumentSerialList(wxInstrumentSerial);
            if (!CollectionUtils.isEmpty(wxInstrumentSerials)) {
                for (WxInstrumentSerial instrumentSerial : wxInstrumentSerials) {
                    WxInstrumentSerialExportVm entity = new WxInstrumentSerialExportVm();
                    BeanUtils.copyProperties(instrumentSerial,entity);
                    entity.setValidStatus(instrumentSerial.getValidStatus() == 1 ? "有效": "无效");
                    resultList.add(entity);
                }
            }
        } else {
            List<Long> instrumentSerialIdList = wxInstrumentSerial.getInstrumentSerialIdList();
            for (Long id: instrumentSerialIdList) {
                WxInstrumentSerial instrumentSerial = wxInstrumentSerialMapper.selectWxInstrumentSerialById(id);
                WxInstrumentSerialExportVm entity = new WxInstrumentSerialExportVm();
                BeanUtils.copyProperties(instrumentSerial,entity);
                entity.setValidStatus(instrumentSerial.getValidStatus() == 1 ? "有效": "无效");
                resultList.add(entity);
            }
        }
        return resultList;
    }

    @Override
    public String handleImportData(List<WxInstrumentSerialImportVm> wxInstrumentSerialImportVmList) {
        if (StringUtils.isNull(wxInstrumentSerialImportVmList) || wxInstrumentSerialImportVmList.size() == 0)
        {
            throw new ServiceException("导入的仪器序列号数据不能为空！");
        }
        // 初始化计数器
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (WxInstrumentSerialImportVm instrumentSerialImport : wxInstrumentSerialImportVmList) {
            try {
                // 先判断仪器ID是否存在
                if (Objects.isNull(instrumentSerialImport.getInstrumentId()) || Objects.isNull(instrumentSerialImport.getSerial())){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、仪器ID/序列号不能为空");
                } else {
                    WxInstrument wxInstrument = wxInstrumentMapper.selectWxInstrumentById(instrumentSerialImport.getInstrumentId());
                    if (Objects.isNull(wxInstrument)) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、仪器不存在,请先维护后再导入");
                    }
                    WxInstrumentSerial instrumentSerial = new WxInstrumentSerial();
                    instrumentSerial.setSerial(instrumentSerialImport.getSerial());
                    List<WxInstrumentSerial> wxInstrumentSerialList = wxInstrumentSerialMapper.selectWxInstrumentSerialList(instrumentSerial);
                    if (CollectionUtils.isEmpty(wxInstrumentSerialList)) {
                        if(Objects.nonNull(wxInstrument)) {
                            // 开始插入数据
                            WxInstrumentSerial insertRecord = new WxInstrumentSerial();
                            insertRecord.setCreateTime(DateUtils.getNowDate());
                            insertRecord.setInstrumentName(wxInstrument.getName());
                            insertRecord.setSerial(instrumentSerialImport.getSerial());
                            insertRecord.setSource(instrumentSerialImport.getSource());
                            insertRecord.setInstrumentId(wxInstrument.getId());
                            if (StringUtils.isEmpty(instrumentSerialImport.getValidStatus())) {
                                instrumentSerialImport.setValidStatus("有效") ;
                            }
                            insertRecord.setValidStatus(instrumentSerialImport.getValidStatus().trim().equals("有效")?1:0);
                            wxInstrumentSerialMapper.insertWxInstrumentSerial(insertRecord);
                            successNum++;
                            successMsg.append("<br/>" + successNum + "、序列号 " + insertRecord.getSerial() + " 导入成功");
                        }
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、序列号已经存在");
                    }
                }

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、仪器ID " + instrumentSerialImport.getInstrumentId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条：");
        }
        if (StringUtils.isNotEmpty(successMsg.toString()) && !"null".equals(successMsg.toString())) {
            return successMsg.toString();
        } else {
            return failureMsg.toString();
        }
    }
}
