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.common.StringUtil;
import com.yeejoin.amos.boot.module.ys.api.dto.YsEmergencyUnitDto;
import com.yeejoin.amos.boot.module.ys.api.entity.YsEmergencyUnit;
import com.yeejoin.amos.boot.module.ys.api.mapper.YsEmergencyUnitMapper;
import com.yeejoin.amos.boot.module.ys.api.service.IYsEmergencyUnitService;
import com.yeejoin.amos.boot.module.ys.api.vo.ExportYsEmergencyUnitVo;
import com.yeejoin.amos.boot.module.ys.api.vo.ImportYsEmergencyUnitVo;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.apache.commons.lang.StringUtils;
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;

/**
 * 应急联动单位管理服务实现类
 *
 * @author system_generator
 * @date 2024-09-24
 */
@Service
public class YsEmergencyUnitServiceImpl extends BaseService<YsEmergencyUnitDto, YsEmergencyUnit, YsEmergencyUnitMapper> implements IYsEmergencyUnitService {
    /**
     * 分页查询
     */
    public Page<YsEmergencyUnitDto> queryForYsEmergencyUnitPage(Page<YsEmergencyUnitDto> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<YsEmergencyUnitDto> queryForYsEmergencyUnitList() {
        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);
    //    }

    /**
     * @author chang xiangyu
     * @param ysEmergencyUnitDto
     * @param userModel
     * @return
     */
    @Override
    public Boolean saveOrUpdate(YsEmergencyUnitDto ysEmergencyUnitDto, AgencyUserModel userModel) {
        YsEmergencyUnit ysEmergencyUnit = new YsEmergencyUnit();
        //新增
        if (ValidationUtil.isEmpty(ysEmergencyUnitDto.getSequenceNbr())) {
            ysEmergencyUnitDto.setCreateDate(new Date());
            ysEmergencyUnitDto.setCreateUserId(userModel.getUserId());
            ysEmergencyUnitDto.setCreateUserName(userModel.getUserName());
        }
        ysEmergencyUnit.setPicture(JSON.toJSONString(ysEmergencyUnitDto.getPicture()));
        BeanUtils.copyProperties(ysEmergencyUnitDto, ysEmergencyUnit);
        return this.saveOrUpdate(ysEmergencyUnit);
    }

    /**
     * @author chang xiangyu
     * @param sequenceNbr
     * @return
     */
    @Override
    public Boolean deleteBySeq(String sequenceNbr) {
        LambdaUpdateWrapper<YsEmergencyUnit> lambda = new UpdateWrapper<YsEmergencyUnit>().lambda();
        lambda.eq(YsEmergencyUnit::getSequenceNbr, sequenceNbr);
        lambda.set(YsEmergencyUnit::getIsDelete, Boolean.TRUE);
        return this.update(lambda);
    }

    /**
     * @author chang xiangyu
     * @param sequenceNbr
     * @return
     */
    @Override
    public YsEmergencyUnitDto querySafeUnitBySeq(Long sequenceNbr) {
        LambdaQueryWrapper<YsEmergencyUnit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YsEmergencyUnit::getSequenceNbr,sequenceNbr);
        queryWrapper.eq(YsEmergencyUnit::getIsDelete,Boolean.FALSE);
        YsEmergencyUnit unSafeOne = this.getOne(queryWrapper);
        YsEmergencyUnitDto safeYsEmergencyUnitDto = new YsEmergencyUnitDto();
        BeanUtils.copyProperties(unSafeOne,safeYsEmergencyUnitDto);
        if(!ValidationUtil.isEmpty(unSafeOne.getPicture())){
            safeYsEmergencyUnitDto.setPicture(JSON.parseArray(unSafeOne.getPicture()));
        }
        return safeYsEmergencyUnitDto;
    }

    /**
     * @author chang xiangyu
     * @param page
     * @return
     */
    @Override
    public Page<YsEmergencyUnitDto> querySafeUnitsByPage(Page<YsEmergencyUnit> page, String sort, YsEmergencyUnitDto ysEmergencyUnitDto) {
        LambdaQueryWrapper<YsEmergencyUnit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YsEmergencyUnit::getIsDelete, Boolean.FALSE);
        // 条件查询 -> 根据名称查询
        if (StringUtil.isNotEmpty(ysEmergencyUnitDto.getName())) {
            queryWrapper.like(YsEmergencyUnit::getName, ysEmergencyUnitDto.getName());
        }
        // 条件查询 -> 根据应急服务内容查询
        if (StringUtils.isNotEmpty(ysEmergencyUnitDto.getEmergencyService())) {
            queryWrapper.like(YsEmergencyUnit::getEmergencyService, ysEmergencyUnitDto.getEmergencyService());
        }
        // 条件查询 -> 根据关联消防队查询
        if (ysEmergencyUnitDto.getTeamId() != null) {
            queryWrapper.like(YsEmergencyUnit::getTeamId, ysEmergencyUnitDto.getTeamId());
        }
        if (StringUtils.isNotBlank(sort)) {
            String[] split = sort.split(",");
            String field = split[0];
            String sortDirection = split[1];
            // 使用switch匹配字段, 确保字段类型安全
            switch (field) {
                case "name":
                    if (sortDirection.startsWith("asc")) {
                        queryWrapper.orderByAsc(YsEmergencyUnit::getName);
                    } else {
                        queryWrapper.orderByDesc(YsEmergencyUnit::getName);
                    }
                    break;
                default:
                    break;
            }
        }
        this.page(page, queryWrapper);
        // 数据脱敏
        Page<YsEmergencyUnitDto> ysEmergencyUnitDtoPage = new Page<YsEmergencyUnitDto>();
        BeanUtils.copyProperties(page, ysEmergencyUnitDtoPage);
        return ysEmergencyUnitDtoPage;
    }

    /**
     * 列表数据导出
     *
     * @param response 响应
     * @param ids      数据id
     */
    @Override
    public void export(HttpServletResponse response, List<String> ids) {
        LambdaQueryWrapper<YsEmergencyUnit> lambda = new QueryWrapper<YsEmergencyUnit>().lambda();
        lambda.in(YsEmergencyUnit::getSequenceNbr, ids);
        lambda.eq(YsEmergencyUnit::getIsDelete,Boolean.FALSE);
        List<YsEmergencyUnit> experts = this.baseMapper.selectList(lambda);
        List<ExportYsEmergencyUnitVo> exportData = JSON.parseArray(JSON.toJSONString(experts), ExportYsEmergencyUnitVo.class);
        ExcelUtil.createTemplate(response, "联动单位信息列表数据", "联动单位信息列表", exportData, ExportYsEmergencyUnitVo.class, null, false);
    }

    /**
     * 列表数据导入
     *
     * @param file excel 文件
     * @return 导入结果
     * @author chang xiangyu
     */
    @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<YsEmergencyUnit> dataList = new ArrayList<>();

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

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