package com.kcim.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelVerifyHandlerResult;
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kcim.common.constants.NumberConstant;
import com.kcim.common.exception.CostException;
import com.kcim.common.util.BeanUtil;
import com.kcim.common.util.PageUtils;
import com.kcim.common.util.UserContext;
import com.kcim.common.util.excel.ExcelStyleUtil;
import com.kcim.common.util.excel.entity.EquipmentImportEntity;
import com.kcim.dao.model.EmpCostType;
import com.kcim.dao.model.Equipment;
import com.kcim.dao.repository.EquipmentRepository;
import com.kcim.service.EquipmentService;
import com.kcim.vo.CodeAndNameVO;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @program: CostAccount
 * @description: 设备成本管理接口实现类
 * @author: Wang.YS
 * @create: 2023-11-07 15:54
 **/
@Service("EquipmentService")
@Slf4j
@AllArgsConstructor
public class EquipmentServiceImpl implements EquipmentService {
    EquipmentRepository repository;
    /**
     * 获取设备成本信息列表
     * @param current 当前页
     * @param pageSize 页容量
     * @param name 项目名称
     * @param stop 是否停用 0启用 1停用 默认 0
     * @return 设备成本信息列表
     */
    @Override
    public Object getEquipmentList(Integer current, Integer pageSize, String name, Integer stop) {
        Page<Equipment> page = repository.getPage(current, pageSize, name, stop);
        List<Equipment> records = page.getRecords();
        if(CollectionUtils.isEmpty(records)){
            return new PageUtils(new ArrayList<>(), NumberConstant.ZERO,pageSize,current);
        }

        return new PageUtils(records, Math.toIntExact(page.getTotal()),pageSize,current);    }

    /**
     * 新增设备成本信息
     * @param request 新增入参
     */
    @Override
    public void addEquipment(Equipment request) {
        List<Equipment> equipment = repository.getByCode(request.getCode());
        if(!CollectionUtils.isEmpty(equipment)){
            throw new CostException("当前设备代码已存在，请修改后再保存");
        }

        request.setHospId(UserContext.getCurrentLoginHospId());
        request.setCreateTime(new Date());
        request.setCreateUser(String.valueOf(UserContext.getCurrentUser().getId()));
        if(request.getStatus() != null &&request.getStatus().equals(NumberConstant.ONE)){
            Date stopTime = request.getStopTime();
            if(stopTime == null){
                throw new CostException("当前设备停用标志为停用，停用时间必填");
            }
        }else {
            request.setStatus(NumberConstant.ZERO);
        }
        if(request.getPrice() != null&& request.getDepreciationYear() != null && request.getDepreciationYear().compareTo(BigDecimal.ZERO) != 0) {
            //计算每年折旧 每年折旧＝采购价格/折旧年限
            request.setCostPerYear(calculateCostPerYear(request.getPrice(),request.getDepreciationYear()));
            //每分钟成本＝每年折旧/（365*24*60）
            request.setCostPerMinute(calculateCostPerMinute(request.getCostPerYear()));
        }
        repository.save(request);
    }

    /**
     * 编辑设备成本信息
     * @param request 入参
     */
    @Override
    public void editEquipment(Equipment request) {
        Integer id = request.getId();
        if(id ==null){
            throw new CostException("编辑设备时，主键必填");
        }
        Equipment equipment = repository.getById(id);
        Equipment equipmentOne = repository.getOneByCode(request.getCode());
        if(Objects.nonNull(equipment)){
            if(Objects.isNull(equipmentOne)||equipmentOne.getId().equals(id)){
                BeanUtil.convertObj(request,equipment);
                equipment.setUpdateTime(new Date());
                equipment.setUpdateUser(String.valueOf(UserContext.getCurrentUser().getId()));
                if(equipment.getStatus() != null &&equipment.getStatus().equals(NumberConstant.ONE)){
                    Date stopTime = request.getStopTime();
                    if(stopTime == null){
                        throw new CostException("当前设备停用标志为停用，停用时间必填");
                    }
                }else {
                    equipment.setStopTime(null);
                }
                if(equipment.getPrice() != null&& equipment.getDepreciationYear() != null && equipment.getDepreciationYear().compareTo(BigDecimal.ZERO) != 0) {
                    //计算每年折旧 每年折旧＝采购价格/折旧年限
                    equipment.setCostPerYear(calculateCostPerYear(equipment.getPrice(),equipment.getDepreciationYear()));
                    //每分钟成本＝每年折旧/（365*24*60）
                    equipment.setCostPerMinute(calculateCostPerMinute(equipment.getCostPerYear()));
                }
                repository.updateById(equipment);
            }else {
                throw new CostException("当前设备代码已存在，请修改后再保存");
            }
        }
    }

    /**
     * 删除设备成本信息
     * @param id 主键
     */
    @Override
    public void deleteEquipment(Integer id) {
        repository.deleteEquipment(id);

    }

    /**
     * 导出设备成本信息模版
     * @param response 出参
     * @return excel
     */
    @SneakyThrows
    @Override
    public Object exportEquipment(HttpServletResponse response) {
        try {
            //配置excel 文件信息
            ExportParams params = new ExportParams();

            params.setTitle("说明：1、为了保证成功导入，请勿修改模板格式\n" +
                    "      2、设备型号为非必填项，可以为空\n" +
                    "      3、停用字段为下拉选择字段，不可填写选项外的内容\n" +
                    "      4、停用字段为是时，必须填写对应的停用时间，格式：yyyy-MM-dd HH:mm:ss");
            //设置导出样式
            params.setStyle(ExcelStyleUtil.class);
            //设置sheetName
            params.setTitleHeight((short) 20);
            params.setSheetName("设备成本项目");
//            FileOutputStream outputStream = new FileOutputStream("E:\\设备成本项目导入模版.xlsx");
            Workbook workbook = ExcelExportUtil.exportExcel(params, EquipmentImportEntity.class,new ArrayList<>());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            String fileName ="设备成本项目导入模版";
            response.setHeader("Content-Disposition",  URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
//                workbook.write(outputStream);
//                outputStream.close();
            workbook.close();
            log.info("导出文件：{}",fileName);
        } catch (FileNotFoundException e) {
            throw new CostException(e.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return response.getOutputStream();
    }

    /**
     * 导入设备成本信息
     * @param file 导入文件
     */
    @Override
    public void importEquipment(MultipartFile file) {
        try {
            if (ObjectUtils.isEmpty(file) || file.getSize() == 0){
                throw new CostException("未获取到导入的excel文件内容");
            }
            log.info("接收到文件：{}",file.getOriginalFilename());
            // 参数1：文件流
            InputStream stream = file.getInputStream();
            // 参数2：导入类型
            ImportParams params = new ImportParams();
            //校验Excel 去掉空行
            params.setNeedVerify(true);
            IExcelVerifyHandler<EquipmentImportEntity> handler = val ->{
                if(StringUtils.isEmpty(val.getCode())){
                    return new ExcelVerifyHandlerResult(false,"设备项目代码不能为空");
                }
                if(StringUtils.isEmpty(val.getName())){
                    return new ExcelVerifyHandlerResult(false,"设备名称不能为空");
                }
                return new ExcelVerifyHandlerResult(true);
            };
            params.setVerifyHandler(handler);
            // 标题占用多少行
            params.setTitleRows(1);
            // 头部属性占用多少行
            params.setHeadRows(1);
            List<EquipmentImportEntity> equipmentImportEntities  = ExcelImportUtil.importExcel(stream, EquipmentImportEntity.class,params);
            if(!CollectionUtils.isEmpty(equipmentImportEntities)){
                List<Equipment> saveList = new ArrayList<>();
                Equipment equipmentCost =new Equipment();
                equipmentCost.setHospId(UserContext.getHospId());
                equipmentCost.setCreateTime(new Date());
                equipmentCost.setCreateUser(String.valueOf(UserContext.getCurrentUser().getId()));
                for (EquipmentImportEntity entity : equipmentImportEntities) {
                    Equipment equipment = BeanUtil.convertObj(equipmentCost, Equipment.class);
                    equipment.setCode(entity.getCode());
                    equipment.setName(entity.getName());
                    equipment.setType(entity.getType());
                    equipment.setStatus(entity.getStatus());
                    equipment.setStopTime(entity.getStopTime());
                    equipment.setPrice(entity.getPrice());
                    equipment.setDepreciationYear(entity.getDepreciationYear());
                    if(equipment.getPrice() != null&& equipment.getDepreciationYear() != null && equipment.getDepreciationYear().compareTo(BigDecimal.ZERO) != 0){
                        //计算每年折旧 每年折旧＝采购价格/折旧年限
                        equipment.setCostPerYear(calculateCostPerYear(equipment.getPrice(),equipment.getDepreciationYear()));
                        //每分钟成本＝每年折旧/（365*24*60）
                        equipment.setCostPerMinute(calculateCostPerMinute(equipment.getCostPerYear()));
                    }else {
                        equipment.setCostPerYear(BigDecimal.ZERO);
                        equipment.setCostPerMinute(BigDecimal.ZERO);
                    }
                    saveList.add(equipment);
                }
                if(!CollectionUtils.isEmpty(saveList)){
                    check();
                    repository.saveBatch(saveList,50);
                }
            }
        } catch (Exception e) {
            throw new CostException(e.getMessage());
        }
    }

    @Override
    public List<CodeAndNameVO> getItemDict() {
        List<Equipment> list = repository.getList();

        if(!CollectionUtils.isEmpty(list)){
            List<CodeAndNameVO> returnList = new ArrayList<>();
            for (Equipment type : list) {
                CodeAndNameVO vo = new CodeAndNameVO();
                vo.setCode(type.getCode());
                vo.setName(type.getName());
                returnList.add(vo);
            }
            //添加全部
            CodeAndNameVO vo = new CodeAndNameVO();
            vo.setCode(NumberConstant.ZERO_S);
            vo.setName("全部");
            returnList.add(vo);
            return returnList;
        }
        return new ArrayList<>();
    }

    private void check() {
        List<Equipment> list = repository.getList();
        if(!CollectionUtils.isEmpty(list)){
            repository.removeList(list);
        }
    }

    private BigDecimal calculateCostPerYear(BigDecimal price,BigDecimal depreciationYear){
        return price.divide(depreciationYear, 4, RoundingMode.HALF_UP);

    }
    private BigDecimal calculateCostPerMinute(BigDecimal costYear){
        int minute = 365 * 24 * 60;

        return costYear.divide(BigDecimal.valueOf(minute), 4, RoundingMode.HALF_UP);

    }

}
