package com.yeejoin.amos.boot.module.ys.biz.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.excel.ExcelUtil;
import com.yeejoin.amos.boot.module.ys.api.dto.YsEmergencyCaseDto;
import com.yeejoin.amos.boot.module.ys.api.entity.YsEmergencyCase;
import com.yeejoin.amos.boot.module.ys.api.mapper.YsEmergencyCaseMapper;
import com.yeejoin.amos.boot.module.ys.api.service.IYsEmergencyCaseService;
import com.yeejoin.amos.boot.module.ys.api.vo.CaseImportVo;
import com.yeejoin.amos.boot.module.ys.api.vo.CaseVo;
import com.yeejoin.amos.boot.module.ys.api.vo.SortVo;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 救援案例管理服务实现类
 *
 * @author system_generator
 * @date 2024-09-24
 */
@Service
public class YsEmergencyCaseServiceImpl extends BaseService<YsEmergencyCaseDto, YsEmergencyCase, YsEmergencyCaseMapper> implements IYsEmergencyCaseService {
    @Autowired
    private YsEmergencyCaseMapper ysEmergencyCaseMapper;
    @Autowired
    private CommonServiceImpl commonService;


    /**
     * 列表查询 示例
     */
    public List<YsEmergencyCaseDto> queryForYsEmergencyCaseList() {
        return this.queryForList("", false);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdate(YsEmergencyCaseDto dto, AgencyUserModel userModel) {
        YsEmergencyCase emergencyCase = new YsEmergencyCase();
        if (ValidationUtil.isEmpty(dto.getSequenceNbr())) {//新增
            dto.setCreateDate(new Date());
            dto.setCreateUserId(userModel.getUserId());
            dto.setCreateUserName(userModel.getUserName());
        }
        emergencyCase.setVideoInfo(JSON.toJSONString(dto.getVideoInfo()));
        emergencyCase.setPicInfo(JSON.toJSONString(dto.getPicInfo()));
        emergencyCase.setFileInfo(JSON.toJSONString(dto.getFileInfo()));
        emergencyCase.setAudioInfo(JSON.toJSONString(dto.getAudioInfo()));
        BeanUtils.copyProperties(dto, emergencyCase);
        return this.saveOrUpdate(emergencyCase);
    }


    @Override
    public Page<YsEmergencyCaseDto> queryForYsEmergencyCasePage(Page<YsEmergencyCaseDto> page, String sort, YsEmergencyCaseDto dto) {
        SortVo sortMap = commonService.sortFieldConversion(sort);
        return ysEmergencyCaseMapper.queryForYsEmergencyCasePage(page, sortMap, dto);
    }


    @Override
    public Boolean deleteById(String sequenceNbr) {
        LambdaUpdateWrapper<YsEmergencyCase> lambda = new UpdateWrapper<YsEmergencyCase>().lambda();
        lambda.eq(YsEmergencyCase::getSequenceNbr, sequenceNbr);
        lambda.set(YsEmergencyCase::getIsDelete, Boolean.TRUE);
        return this.update(lambda);
    }


    @Override
    public YsEmergencyCaseDto queryBySequenceNbr(String sequenceNbr) {
        YsEmergencyCaseDto caseDto = new YsEmergencyCaseDto();
        LambdaQueryWrapper<YsEmergencyCase> lambda = new QueryWrapper<YsEmergencyCase>().lambda();
        lambda.eq(YsEmergencyCase::getSequenceNbr, sequenceNbr);
        YsEmergencyCase emergencyCase = this.baseMapper.selectOne(lambda);
        if (emergencyCase != null) {
            BeanUtils.copyProperties(emergencyCase, caseDto);
            // 如果案例有相关的图片或者其他特殊处理字段，可以在此进行处理
            if (!ValidationUtil.isEmpty(emergencyCase.getPicInfo())) {
                caseDto.setPicInfo(JSON.parseArray(emergencyCase.getPicInfo()));
            }
            if (!ValidationUtil.isEmpty(emergencyCase.getVideoInfo())) {
                caseDto.setVideoInfo(JSON.parseArray(emergencyCase.getVideoInfo()));
            }
            if (!ValidationUtil.isEmpty(emergencyCase.getFileInfo())) {
                caseDto.setFileInfo(JSON.parseArray(emergencyCase.getFileInfo()));
            }
            if (!ValidationUtil.isEmpty(emergencyCase.getAudioInfo())) {
                caseDto.setAudioInfo(JSON.parseArray(emergencyCase.getAudioInfo()));
            }
        }
        return caseDto;
    }

    /**
     * 列表数据导出
     *
     * @param response 响应
     * @param ids      数据id
     */
    @Override
    public void export(HttpServletResponse response, List<String> ids) {
        LambdaQueryWrapper<YsEmergencyCase> lambda = new QueryWrapper<YsEmergencyCase>().lambda();
        lambda.in(YsEmergencyCase::getSequenceNbr, ids);
        List<YsEmergencyCase> experts = this.baseMapper.selectList(lambda);
        List<CaseVo> exportData = JSON.parseArray(JSON.toJSONString(experts), CaseVo.class);
        ExcelUtil.createTemplate(response, "案例列表数据", "案例列表列表", exportData, CaseVo.class, null, false);
    }

    /**
     * 列表数据导入
     *
     * @param file excel 文件
     * @return 导入结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseModel<Object> expertDataImport(MultipartFile file, AgencyUserModel userModel) {
        try {
            InputStream inputStream = file.getInputStream();
            ExcelReader excelReader = EasyExcel.read(inputStream).build();
            List<ReadSheet> sheetList = excelReader.excelExecutor().sheetList();

            ReadSheet sheet = sheetList.get(0);
            if (ValidationUtil.isEmpty(sheet)) {
                throw new BadRequest("Excel导入模板有误，请重写下载导入！");
            }

            ArrayList<YsEmergencyCase> dataList = new ArrayList<>();

            EasyExcel.read(file.getInputStream(), CaseImportVo.class, new AnalysisEventListener<CaseImportVo>() {
                @Override
                public void invoke(CaseImportVo data, AnalysisContext context) {
                    YsEmergencyCase emergencyCase = JSON.parseObject(JSON.toJSONString(data), YsEmergencyCase.class);
                    emergencyCase.setIsDelete(Boolean.FALSE);
                    emergencyCase.setCreateDate(new Date());
                    emergencyCase.setCreateUserName(userModel.getUserName());
                    emergencyCase.setCreateUserId(userModel.getUserId());
                    dataList.add(emergencyCase);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                }
            }).headRowNumber(1).sheet().doRead();

            excelReader.finish();

            // 保存数据
            this.saveOrUpdateBatch(dataList);

            return ResponseHelper.buildResponse("success");
        } catch (Exception e) {
            throw new BadRequest(e.getMessage());
        }
    }
}