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.alibaba.fastjson.JSONObject;
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.YsEmergencyExpertsDto;
import com.yeejoin.amos.boot.module.ys.api.entity.YsEmergencyExperts;
import com.yeejoin.amos.boot.module.ys.api.mapper.YsEmergencyExpertsMapper;
import com.yeejoin.amos.boot.module.ys.api.service.IYsEmergencyExpertsService;
import com.yeejoin.amos.boot.module.ys.api.vo.ExpertImportVo;
import com.yeejoin.amos.boot.module.ys.api.vo.ExpertVo;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.springframework.beans.BeanUtils;
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;
import java.util.Map;

/**
 * 应急专家库服务实现类
 *
 * @author system_generator
 * @date 2024-09-24
 */
@Service
public class YsEmergencyExpertsServiceImpl extends BaseService<YsEmergencyExpertsDto, YsEmergencyExperts, YsEmergencyExpertsMapper> implements IYsEmergencyExpertsService {
    /**
     * 分页查询
     */
    public Page<Map<String, Object>> queryForYsEmergencyExpertsPage(YsEmergencyExpertsDto dto, Page<Map<String, Object>> page) {
        return this.baseMapper.pageList(page, dto);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdate(Map<String, Object> model, AgencyUserModel userModel) {
        YsEmergencyExperts experts = JSON.parseObject(JSONObject.toJSONString(model), YsEmergencyExperts.class);
        experts.setIsDelete(Boolean.FALSE);
        if (ValidationUtil.isEmpty(experts.getSequenceNbr())) {//新增
            experts.setCreateDate(new Date());
            experts.setCreateUserId(userModel.getUserId());
            experts.setCreateUserName(userModel.getUserName());
        }
        return this.saveOrUpdate(experts);
    }

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

    @Override
    public YsEmergencyExpertsDto queryBySequenceNbr(String sequenceNbr) {
        YsEmergencyExpertsDto expertsDto = new YsEmergencyExpertsDto();
        LambdaQueryWrapper<YsEmergencyExperts> lambda = new QueryWrapper<YsEmergencyExperts>().lambda();
        lambda.eq(YsEmergencyExperts::getSequenceNbr, sequenceNbr);
        YsEmergencyExperts experts = this.baseMapper.selectOne(lambda);
        BeanUtils.copyProperties(experts, expertsDto);
        if (!ValidationUtil.isEmpty(experts.getPhoto())) {
            expertsDto.setPhoto(JSON.parseArray((experts.getPhoto())));
        }
        return expertsDto;
    }

    /**
     * 专家库列表数据导入
     *
     * @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<YsEmergencyExperts> dataList = new ArrayList<>();

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

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

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


}