package com.flossom.system.service.impl;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.flossom.common.core.domain.entity.SysTag;
import com.flossom.common.core.domain.entity.WxInstrument;
import com.flossom.common.core.domain.entity.WxInstrumentFileRelate;
import com.flossom.common.core.domain.entity.WxInstrumentMode;
import com.flossom.common.core.domain.req.WxInstrumentReq;
import com.flossom.common.core.domain.req.WxInstrumentSaveReq;
import com.flossom.common.core.enums.InstrumentFileClassifyEnum;
import com.flossom.common.core.enums.Status;
import com.flossom.common.core.mapper.SysTagMapper;
import com.flossom.common.core.mapper.WxInstrumentFileRelateMapper;
import com.flossom.common.core.mapper.WxInstrumentMapper;
import com.flossom.common.core.mapper.WxInstrumentModeMapper;
import com.flossom.common.core.utils.DateUtils;
import com.flossom.common.core.utils.StringUtils;
import com.flossom.common.security.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.flossom.system.service.IWxInstrumentService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 仪器列Service业务层处理
 *
 * @author flossom
 * @date 2024-01-06
 */
@Service
public class WxInstrumentServiceImpl implements IWxInstrumentService {

    @Autowired
    private WxInstrumentMapper wxInstrumentMapper;

    @Autowired
    private SysTagMapper sysTagMapper;

    @Autowired
    private WxInstrumentFileRelateMapper wxInstrumentFileRelateMapper;

    @Autowired
    private WxInstrumentModeMapper wxInstrumentModeMapper;

    /**
     * 查询仪器列
     *
     * @param id 仪器列主键
     * @return 仪器列
     */
    @Override
    public WxInstrument selectWxInstrumentById(Long id) {
        return wxInstrumentMapper.selectWxInstrumentById(id);
    }

    /**
     * 查询仪器列
     *
     * @param id 仪器列主键
     * @return 仪器列
     */
    @Override
    public WxInstrumentSaveReq selectWxInstrumentReqById(Long id) {
        WxInstrument wxInstrument = wxInstrumentMapper.selectWxInstrumentById(id);
        WxInstrumentSaveReq wxInstrumentSaveReq = new WxInstrumentSaveReq();
        BeanUtils.copyProperties(wxInstrument, wxInstrumentSaveReq);
        // 时间范围
        if (wxInstrument.getStartTime() != null && wxInstrument.getEndTime() != null) {
            wxInstrumentSaveReq.setExtraClockTimeRange(Arrays.asList(wxInstrument.getStartTime(), wxInstrument.getEndTime()));
        }
        // 获取护理弹窗关联
        List<WxInstrumentFileRelate> firstNurseRelate = wxInstrumentFileRelateMapper.
                selectByInstrumentIdAndClassify(wxInstrument.getId(), InstrumentFileClassifyEnum.FIRST_NURSE.getCode());
        wxInstrumentSaveReq.setNurseList(firstNurseRelate);
        // 获取护理弹窗关联
        List<WxInstrumentFileRelate> instructionRelate = wxInstrumentFileRelateMapper.
                selectByInstrumentIdAndClassify(wxInstrument.getId(), InstrumentFileClassifyEnum.INSTRUMENT_INSTRUCTION.getCode());
        wxInstrumentSaveReq.setIntroduceList(instructionRelate);
        // 获取模式关联
        WxInstrumentMode wxInstrumentMode = new WxInstrumentMode();
        wxInstrumentMode.setInstrumentId(id);
        List<WxInstrumentMode> wxInstrumentModes = wxInstrumentModeMapper.selectWxInstrumentModeList(wxInstrumentMode);
        if (wxInstrumentModes != null && wxInstrumentModes.size() > 0) {
            wxInstrumentSaveReq.setModeIdsValue(wxInstrumentModes.stream()
                    .map(WxInstrumentMode::getModeId)
                    .map(Long::intValue)
                    .collect(Collectors.toList()));

            wxInstrumentSaveReq.setNewModeIdList(wxInstrumentModes.stream()
                    .filter(im -> im.getIsNew() == 1)
                    .map(WxInstrumentMode::getModeId)
                    .map(Long::intValue)
                    .collect(Collectors.toList())
            );
        }
        return wxInstrumentSaveReq;
    }

    /**
     * 查询仪器列列表
     *
     * @param wxInstrument 仪器列
     * @return 仪器列
     */
    @Override
    public List<WxInstrument> selectWxInstrumentList(WxInstrument wxInstrument) {
        return wxInstrumentMapper.selectWxInstrumentList(wxInstrument);
    }

    @Override
    public List<WxInstrument> selectWxInstrumentPage(WxInstrumentReq wxInstrumentReq) {
        return wxInstrumentMapper.selectWxInstrumentPage(wxInstrumentReq);
    }

    /**
     * 新增仪器列
     *
     * @param wxInstrument 仪器列
     * @return 结果
     */
    @Override
    public int insertWxInstrument(WxInstrument wxInstrument) {
        wxInstrument.setCreateTime(DateUtils.getNowDate());
        return wxInstrumentMapper.insertWxInstrument(wxInstrument);
    }

    /**
     * 新增仪器列
     *
     * @return 结果
     */
    @Override
    @Transactional
    public int addWxInstrument(WxInstrumentSaveReq wxInstrumentSaveReq) {
        WxInstrument wxInstrument = new WxInstrument();
        BeanUtils.copyProperties(wxInstrumentSaveReq, wxInstrument);
        // 打卡时间处理
        if (wxInstrumentSaveReq.getIsExtraClock() != null && wxInstrumentSaveReq.getIsExtraClock() == 1) {
            wxInstrument.setStartTime(wxInstrumentSaveReq.getExtraClockTimeRange().get(0));
            wxInstrument.setEndTime(wxInstrumentSaveReq.getExtraClockTimeRange().get(1));
        }
        wxInstrument.setCreateBy(SecurityUtils.getUsername());
        wxInstrument.setCreateTime(DateUtils.getNowDate());

        int insertNum = wxInstrumentMapper.insertWxInstrument(wxInstrument);

        // 保存初次护理规则
        List<WxInstrumentFileRelate> nurseList = wxInstrumentSaveReq.getNurseList();
        if (nurseList != null && nurseList.size() > 0) {
            Iterator<WxInstrumentFileRelate> nurseIterator = nurseList.iterator();
            while (nurseIterator.hasNext()) {
                WxInstrumentFileRelate next = nurseIterator.next();
                if (StringUtils.isBlank(next.getFile())) {
                    nurseIterator.remove();
                    continue;
                }
                next.setInstrumentId(wxInstrument.getId());
                next.setClassify(InstrumentFileClassifyEnum.FIRST_NURSE.getCode());
                wxInstrumentFileRelateMapper.insertWxInstrumentFileRelate(next);
            }
        }

        // 保存仪器介绍规则
        List<WxInstrumentFileRelate> introduceList = wxInstrumentSaveReq.getIntroduceList();
        if (introduceList != null && introduceList.size() > 0) {
            Iterator<WxInstrumentFileRelate> introduceIterator = introduceList.iterator();
            while (introduceIterator.hasNext()) {
                WxInstrumentFileRelate next = introduceIterator.next();
                if (StringUtils.isBlank(next.getFile())) {
                    introduceIterator.remove();
                    continue;
                }
                next.setInstrumentId(wxInstrument.getId());
                next.setClassify(InstrumentFileClassifyEnum.INSTRUMENT_INSTRUCTION.getCode());
                wxInstrumentFileRelateMapper.insertWxInstrumentFileRelate(next);
            }
        }

        // 模式关联
        List<Integer> modeIdList = wxInstrumentSaveReq.getModeIdsValue();
        if (modeIdList != null && modeIdList.size() > 0) {
            wxInstrumentModeMapper.deleteByInstrumentId(wxInstrumentSaveReq.getId());
            for (int i = 0; i < modeIdList.size(); i++) {
                WxInstrumentMode wxInstrumentMode = new WxInstrumentMode();
                wxInstrumentMode.setInstrumentId(wxInstrument.getId());
                wxInstrumentMode.setModeId(modeIdList.get(i).longValue());
                wxInstrumentMode.setModeSort(i);
                if (wxInstrumentSaveReq.getNewModeIdList() != null && wxInstrumentSaveReq.getNewModeIdList().size() > 0) {
                    if (wxInstrumentSaveReq.getNewModeIdList().contains(modeIdList.get(i))) {
                        wxInstrumentMode.setIsNew(1);
                    }
                }
                wxInstrumentMode.setStatus(Status.OK.getCode());
                wxInstrumentMode.setCreateBy(SecurityUtils.getUsername());
                wxInstrumentMode.setCreateTime(DateUtils.getNowDate());
                wxInstrumentModeMapper.insertWxInstrumentMode(wxInstrumentMode);
            }
        }
        return insertNum;
    }

    /**
     * 修改仪器列
     *
     * @param wxInstrumentSaveReq 仪器列
     * @return 结果
     */
    @Override
    public int updateWxInstrument(WxInstrumentSaveReq wxInstrumentSaveReq) {
        WxInstrument wxInstrument = new WxInstrument();
        BeanUtils.copyProperties(wxInstrumentSaveReq, wxInstrument);

        // 处理小程序标签和外部标签
        if (wxInstrumentSaveReq.getMiniTagIds() != null) {
            List<String> tagIdList = Arrays.asList(wxInstrumentSaveReq.getMiniTagIds().split(","));
            StringBuilder tagNames = new StringBuilder();
            for (int i = 0; i < tagIdList.size(); i++) {
                SysTag sysTag = sysTagMapper.selectDeptById(Long.valueOf(tagIdList.get(i)));
                tagNames.append(sysTag.getTagName());
                if (i < tagIdList.size() - 1) {
                    tagNames.append(",");
                }
            }
            wxInstrument.setMiniTagNames(tagNames.toString());
        } else {
            wxInstrument.setMiniTagNames(null);
        }

        if (wxInstrumentSaveReq.getWecomTagIds() != null) {
            List<String> tagIdList = Arrays.asList(wxInstrumentSaveReq.getWecomTagIds().split(","));
            StringBuilder tagNames = new StringBuilder();
            for (int i = 0; i < tagIdList.size(); i++) {
                SysTag sysTag = sysTagMapper.selectDeptById(Long.valueOf(tagIdList.get(i)));
                tagNames.append(sysTag.getTagName());
                if (i < tagIdList.size() - 1) {
                    tagNames.append(",");
                }
            }
            wxInstrument.setWecomTagNames(tagNames.toString());
        } else {
            wxInstrument.setWecomTagNames(null);
        }
        wxInstrument.setUpdateTime(DateUtils.getNowDate());

        // 打卡时间处理
        // 打卡时间处理
        if (wxInstrumentSaveReq.getIsExtraClock() != null && wxInstrumentSaveReq.getIsExtraClock() == 1) {
            wxInstrument.setStartTime(wxInstrumentSaveReq.getExtraClockTimeRange().get(0));
            wxInstrument.setEndTime(wxInstrumentSaveReq.getExtraClockTimeRange().get(1));
        }

        // 保存初次护理规则
        List<WxInstrumentFileRelate> nurseList = wxInstrumentSaveReq.getNurseList();
        wxInstrumentFileRelateMapper.deleteByInstrumentIdAndClassify(wxInstrumentSaveReq.getId(),
                InstrumentFileClassifyEnum.FIRST_NURSE.getCode());
        if (nurseList != null && nurseList.size() > 0) {
            Iterator<WxInstrumentFileRelate> nurseIterator = nurseList.iterator();
            while (nurseIterator.hasNext()) {
                WxInstrumentFileRelate next = nurseIterator.next();
                if (StringUtils.isBlank(next.getFile())) {
                    nurseIterator.remove();
                    continue;
                }
                next.setInstrumentId(wxInstrument.getId());
                next.setClassify(InstrumentFileClassifyEnum.FIRST_NURSE.getCode());
                wxInstrumentFileRelateMapper.insertWxInstrumentFileRelate(next);
            }
        }

        // 保存仪器介绍规则
        wxInstrumentFileRelateMapper.deleteByInstrumentIdAndClassify(wxInstrumentSaveReq.getId(),
                InstrumentFileClassifyEnum.INSTRUMENT_INSTRUCTION.getCode());
        List<WxInstrumentFileRelate> introduceList = wxInstrumentSaveReq.getIntroduceList();
        Iterator<WxInstrumentFileRelate> introduceIterator = introduceList.iterator();
        while (introduceIterator.hasNext()) {
            WxInstrumentFileRelate next = introduceIterator.next();
            if (StringUtils.isBlank(next.getFile())) {
                introduceIterator.remove();
                continue;
            }
            next.setInstrumentId(wxInstrument.getId());
            next.setClassify(InstrumentFileClassifyEnum.INSTRUMENT_INSTRUCTION.getCode());
            wxInstrumentFileRelateMapper.insertWxInstrumentFileRelate(next);
        }

        // 模式关联
        List<Integer> modeIdList = wxInstrumentSaveReq.getModeIdsValue();
        if (modeIdList != null && modeIdList.size() > 0) {
            wxInstrumentModeMapper.deleteByInstrumentId(wxInstrumentSaveReq.getId());
            for (int i = 0; i < modeIdList.size(); i++) {
                WxInstrumentMode wxInstrumentMode = new WxInstrumentMode();
                wxInstrumentMode.setInstrumentId(wxInstrumentSaveReq.getId());
                wxInstrumentMode.setModeId(modeIdList.get(i).longValue());
                wxInstrumentMode.setModeSort(i);
                if (wxInstrumentSaveReq.getNewModeIdList() != null && wxInstrumentSaveReq.getNewModeIdList().size() > 0) {
                    if (wxInstrumentSaveReq.getNewModeIdList().contains(modeIdList.get(i))) {
                        wxInstrumentMode.setIsNew(1);
                    }
                }
                wxInstrumentMode.setStatus(Status.OK.getCode());
                wxInstrumentMode.setCreateBy(SecurityUtils.getUsername());
                wxInstrumentMode.setCreateTime(DateUtils.getNowDate());
                wxInstrumentModeMapper.insertWxInstrumentMode(wxInstrumentMode);
            }
        }
        return wxInstrumentMapper.updateWxInstrument(wxInstrument);
    }

    /**
     * 批量删除仪器列
     *
     * @return 结果
     */
    @Override
    public int deleteWxInstrumentByIds(Long id) {
        return wxInstrumentMapper.deleteWxInstrumentByIds(id);
    }

    /**
     * 删除仪器列信息
     *
     * @param id 仪器列主键
     * @return 结果
     */
    @Override
    public int deleteWxInstrumentById(Long id) {
        return wxInstrumentMapper.deleteWxInstrumentById(id);
    }
}
