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.YsEmergencyRehearsalDto;
import com.yeejoin.amos.boot.module.ys.api.entity.YsEmergencyRehearsal;
import com.yeejoin.amos.boot.module.ys.api.mapper.YsEmergencyRehearsalMapper;
import com.yeejoin.amos.boot.module.ys.api.service.IYsEmergencyRehearsalService;
import com.yeejoin.amos.boot.module.ys.api.vo.RehearsalImportVo;
import com.yeejoin.amos.boot.module.ys.api.vo.RehearsalVo;
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 YsEmergencyRehearsalServiceImpl extends BaseService<YsEmergencyRehearsalDto, YsEmergencyRehearsal, YsEmergencyRehearsalMapper> implements IYsEmergencyRehearsalService {

    @Autowired
    YsEmergencyRehearsalMapper ysEmergencyRehearsalMapper;

    /**
     * 分页查询
     */
    public Page<YsEmergencyRehearsalDto> queryForYsEmergencyRehearsalPage(Page<YsEmergencyRehearsalDto> page) {
        return this.queryForPage(page, null, false);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdate(YsEmergencyRehearsalDto dto, AgencyUserModel userModel) {
        YsEmergencyRehearsal emergencyRehearsal = new YsEmergencyRehearsal();
        if (ValidationUtil.isEmpty(dto.getSequenceNbr())) {//新增
            dto.setCreateDate(new Date());
            dto.setCreateUserId(userModel.getUserId());
            dto.setCreateUserName(userModel.getUserName());
        }
        emergencyRehearsal.setRehearsalFile(JSON.toJSONString(dto.getRehearsalFile()));
        BeanUtils.copyProperties(dto, emergencyRehearsal);
        return this.saveOrUpdate(emergencyRehearsal);
    }

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

    @Override
    public YsEmergencyRehearsalDto detailBySeq(String sequenceNbr) {
        YsEmergencyRehearsalDto emergencyRehearsalDto = new YsEmergencyRehearsalDto();
        YsEmergencyRehearsal emergencyRehearsal = this.baseMapper.selectById(sequenceNbr);
        BeanUtils.copyProperties(emergencyRehearsal, emergencyRehearsalDto);
        emergencyRehearsalDto.setRehearsalFile(JSON.parseArray(emergencyRehearsal.getRehearsalFile()));
        return emergencyRehearsalDto;
    }

    @Override
    public Page<YsEmergencyRehearsalDto> queryForYsEmergencyRehearsalPage(Page<YsEmergencyRehearsalDto> page, YsEmergencyRehearsalDto dto) {
        return ysEmergencyRehearsalMapper.queryForYsEmergencyRehearsalPage(page, dto);
    }

    /**
     * 列表数据导出
     *
     * @param response 响应
     * @param ids      数据id
     */
    @Override
    public void export(HttpServletResponse response, List<String> ids) {
        LambdaQueryWrapper<YsEmergencyRehearsal> lambda = new QueryWrapper<YsEmergencyRehearsal>().lambda();
        lambda.in(YsEmergencyRehearsal::getSequenceNbr, ids);
        List<YsEmergencyRehearsal> experts = this.baseMapper.selectList(lambda);
        List<RehearsalVo> exportData = JSON.parseArray(JSON.toJSONString(experts), RehearsalVo.class);
        ExcelUtil.createTemplate(response, "演练记录列表数据", "演练记录列表", exportData, RehearsalVo.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<YsEmergencyRehearsal> dataList = new ArrayList<>();

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

                @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());
        }
    }
}