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.MaterialImportEntity;
import com.kcim.dao.model.Material;
import com.kcim.dao.model.OrderItemMap;
import com.kcim.dao.repository.MaterialRepository;
import com.kcim.service.MaterialService;
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.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 14:21
 **/
@Service("MaterialService")
@Slf4j
@AllArgsConstructor
public class MaterialServiceImpl implements MaterialService {
    MaterialRepository repository;

    /**
     * 获取列表数据
     * @param current 当前页
     * @param pageSize 页容量
     * @param name 项目名称
     * @param itemType 项目类型
     * @param stop 是否停用 0启用 1停用 默认 0
     * @return 列表
     */
    @Override
    public Object getMaterialList(Integer current, Integer pageSize, String name, Integer itemType, Integer stop) {
        Page<Material> page = repository.getPage(current, pageSize, name, itemType, stop);
        List<Material> records = page.getRecords();
        if(CollectionUtils.isEmpty(records)){
            return new PageUtils(new ArrayList<>(), NumberConstant.ZERO,pageSize,current);
        }
        for (Material record : records) {
            // 1 不计价材料 2高值材料 3 低值材料
            Integer type = record.getType();
            if(type.equals(NumberConstant.ONE)){
                record.setTypeName("不计价材料");
            } else if (type.equals(NumberConstant.TWO)) {
                record.setTypeName("高值材料");
            } else if (type.equals(NumberConstant.THREE)) {
                record.setTypeName("低值材料");

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

    /**
     * 新增材料
     * @param request 新增入参
     */
    @Override
    public void addMaterial(Material request) {
        List<Material> materials = repository.getByCode(request.getCode());
        if(!CollectionUtils.isEmpty(materials)){
            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);
        }
        repository.save(request);
    }

    /**
     * 编辑材料
     * @param request 入参
     */
    @Override
    public void editMaterial(Material request) {
        Integer id = request.getId();
        if(id ==null){
            throw new CostException("编辑材料时，主键必填");
        }
        Material material = repository.getById(id);
        Material materialOne = repository.getOneByCode(request.getCode());

        if(Objects.nonNull(material)){
            if(Objects.isNull(materialOne)||materialOne.getId().equals(id)){
                BeanUtil.convertObj(request,material);
                material.setUpdateTime(new Date());
                material.setUpdateUser(String.valueOf(UserContext.getCurrentUser().getId()));
                if(material.getStatus() != null &&material.getStatus().equals(NumberConstant.ONE)){
                    Date stopTime = request.getStopTime();
                    if(stopTime == null){
                        throw new CostException("当前材料停用标志为停用，停用时间必填");
                    }
                }else {
                    material.setStopTime(null);
                }
                repository.updateById(material);
            }else {
                throw new CostException("当前材料代码已存在，请修改后再保存");
            }

        }

    }

    /**
     * 删除材料
     * @param id 主键
     */
    @Override
    public void deleteMaterial(Integer id) {
        repository.deleteMaterial(id);
    }

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

            params.setTitle("说明：1、为了保证成功导入，请勿修改模板格式\n" +
                    "      2、项目类型、停用字段为下拉选择字段，不可填写选项外的内容\n" +
                    "      3、停用字段为是时，必须填写对应的停用时间，格式：yyyy-MM-dd HH:mm:ss");
            //设置导出样式
            params.setStyle(ExcelStyleUtil.class);
            //设置sheetName
            params.setTitleHeight((short) 15);
            params.setSheetName("材料项目");
//            FileOutputStream outputStream = new FileOutputStream("E:\\材料项目成本导入模版.xlsx");
            Workbook workbook = ExcelExportUtil.exportExcel(params, MaterialImportEntity.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();
    }

    /**
     * 导入材料excel
     * @param file excel 文件
     */
    @Override
    public void importMaterial(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<MaterialImportEntity> 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<MaterialImportEntity> materialImportEntities  = ExcelImportUtil.importExcel(stream, MaterialImportEntity.class,params);
            if(!CollectionUtils.isEmpty(materialImportEntities)){
                List<Material> saveList = new ArrayList<>();
                Material materialCost = new Material();
                materialCost.setHospId(UserContext.getHospId());
                materialCost.setCreateTime(new Date());
                materialCost.setCreateUser(String.valueOf(UserContext.getCurrentUser().getId()));
                for (MaterialImportEntity entity : materialImportEntities) {
                    Material material = BeanUtil.convertObj(materialCost, Material.class);
                    material.setCode(entity.getCode());
                    material.setName(entity.getName());
                    material.setType(entity.getType());
                    material.setStatus(entity.getStatus());
                    material.setStopTime(entity.getStopTime());
                    material.setPrice(entity.getPrice());
                    material.setCost(entity.getCost());
                    saveList.add(material);
                }
                if(!CollectionUtils.isEmpty(saveList)){
                    check();
                    repository.saveBatch(saveList,50);
                }
            }
        } catch (Exception e) {
            throw new CostException(e.getMessage());
        }
    }

    @Override
    public List<OrderItemMap>  getItemDict(String name) {
        List<Material> list = repository.getList(name);
        if(CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        List<OrderItemMap> returnList = new ArrayList<>();
        for (Material item : list) {
            OrderItemMap orderItemMap = new OrderItemMap();
            orderItemMap.setItemCode(item.getCode());
            orderItemMap.setItemName(item.getName());
            orderItemMap.setItemType(String.valueOf(NumberConstant.TWO));
            returnList.add(orderItemMap);
        }
        return returnList;
    }

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