package com.yeejoin.equipmanage.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.excel.ExcelUtil;
import com.yeejoin.equipmanage.common.entity.EquipmentCategory;
import com.yeejoin.equipmanage.common.entity.WlSpareEquipment;
import com.yeejoin.equipmanage.common.entity.vo.WlSpareEquipmentExportVo;
import com.yeejoin.equipmanage.common.enums.SingleEnum;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.mapper.WlSpareEquipmentMapper;
import com.yeejoin.equipmanage.service.IEquipmentCategoryService;
import com.yeejoin.equipmanage.service.WlSpareEquipmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "设备平台备品备件管理api")
@RequestMapping(value = "/wl-spare-equipment", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class WlSpareEquipmentController extends BaseController {

    @Autowired
    WlSpareEquipmentService wlSpareEquipmentService;

    @Autowired
    WlSpareEquipmentMapper wlSpareEquipmentMapper;

    @Autowired
    IEquipmentCategoryService equipmentCategoryService;

    @Value("${equipment.hierarchy}")
    private String hierarchy;

    @RequestMapping(value = "/saveOrUpdateSpareEquipment", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "新增/编辑", notes = "新增/编辑")
    public ResponseModel<WlSpareEquipment> saveOrUpdateSpareEquipment(@RequestBody WlSpareEquipment wlSpareEquipment) {
        WlSpareEquipment data = wlSpareEquipmentService.saveOrUpdateSpareEquipment(wlSpareEquipment, getSelectedOrgInfo());
        return CommonResponseUtil.success(data);
    }

    @RequestMapping(value = "/deleteByIds", method = RequestMethod.DELETE)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "DELETE", value = "删除", notes = "删除")
    public ResponseModel deleteByIds(@RequestBody List<Long> ids) {
        wlSpareEquipmentService.deleteByIds(ids);
        return CommonResponseUtil.success();
    }

    @RequestMapping(value = "/getById", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "详情", notes = "详情")
    public ResponseModel<WlSpareEquipment> getById(@RequestParam Long id) {
        ReginParams selectedOrgInfo = getSelectedOrgInfo();
        WlSpareEquipment wlSpareEquipment = wlSpareEquipmentService.getById(id);
        wlSpareEquipment.setAgencyId(selectedOrgInfo.getPersonIdentity().getCompanyId());
        return CommonResponseUtil.success(wlSpareEquipment);
    }

    @RequestMapping(value = "/listByPage", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "列表分页查询", notes = "列表分页查询")
    public ResponseModel listByPage(@RequestBody WlSpareEquipment wlSpareEquipment) {
        String[] result = hierarchy.split(",");
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < result.length; i++) {
            map.put(i, Integer.valueOf(result[i]));
        }
        if (StringUtil.isNotEmpty(wlSpareEquipment.getEquipmentClassificationCode())) {
            QueryWrapper<EquipmentCategory> equipmentCategoryQueryWrapper = new QueryWrapper<>();
            equipmentCategoryQueryWrapper.eq("code", wlSpareEquipment.getEquipmentClassificationCode());
            equipmentCategoryQueryWrapper.eq("industry_code", wlSpareEquipment.getIndustryCode());
            List<EquipmentCategory> equipmentCategoryList = equipmentCategoryService.list(equipmentCategoryQueryWrapper);
            if (CollectionUtils.isEmpty(equipmentCategoryList)) {
                throw new RuntimeException("装备定义code有误");
            }
            EquipmentCategory equipmentCategory = equipmentCategoryList.get(0);
            int inhierarchy = 1;
            int flag = 0;
            for (int i = 0; i < result.length + 1; i++) {
                //进来先判断是否默认就是空，如果为空第一层
                if (equipmentCategory.getParentId() == null) {
                    //判断是否是最下面的子节点
                    if (i >= 4) {
                        inhierarchy = 8;
                    } else {
                        inhierarchy = map.get(i);
                    }
                    flag = i;
                    break;
                } else {
                    //查找到循环几次为空
                    equipmentCategory = equipmentCategoryService.getById(equipmentCategory.getParentId());
                }
            }
            if (flag == 0) {
                String classificationCode = wlSpareEquipment.getEquipmentClassificationCode().replaceAll("0+$", "");
                return CommonResponseUtil.success(wlSpareEquipmentService.listByPage(wlSpareEquipment, new Page<>(wlSpareEquipment.getPageNum(), wlSpareEquipment.getPageSize()), inhierarchy, classificationCode));
            } else {
                String classificationCode = wlSpareEquipment.getEquipmentClassificationCode().replaceAll("0+$", "");
                return CommonResponseUtil.success(wlSpareEquipmentService.listByPage(wlSpareEquipment, new Page<>(wlSpareEquipment.getPageNum(), wlSpareEquipment.getPageSize()), inhierarchy, classificationCode.length() % 2 == 0 ? classificationCode : classificationCode + "0"));
            }
        }

        Page<WlSpareEquipment> wlSpareEquipmentPage = wlSpareEquipmentService.listByPage(wlSpareEquipment, new Page<>(wlSpareEquipment.getPageNum(), wlSpareEquipment.getPageSize()), 0, null);
        return CommonResponseUtil.success(wlSpareEquipmentPage);
    }

    /**
     * 下载模板
     *
     * @return
     * @Since 2021-3-10
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/downTemplate")
    @ApiOperation(httpMethod = "GET", value = "下载模板", notes = "下载模板")
    public void downTemplate(HttpServletResponse response) {
        // 使用ClassPathResource加载模板文件
        try (InputStream inputStream = new ClassPathResource("template/消防装备备品备件导入模板.xlsx").getInputStream()) {
            // 对文件名进行URL编码
            String encodedFilename = UriUtils.encode("消防装备备品备件导入模板.xlsx", StandardCharsets.UTF_8);
            // 设置响应的内容类型为Excel文件的MIME类型
            response.setContentType(String.valueOf(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")));
            // 设置Content-Disposition头信息，指定文件名
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + encodedFilename);
            // 将输入流的内容复制到响应的输出流
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "数据导出", notes = "数据导出")
    @PostMapping(value = "/export")
    public void export(HttpServletResponse response, @RequestBody WlSpareEquipment dto) {
        List<WlSpareEquipment> exportList = new ArrayList<>();
        String[] result = hierarchy.split(",");
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < result.length; i++) {
            map.put(i, Integer.valueOf(result[i]));
        }
        if (StringUtil.isNotEmpty(dto.getEquipmentClassificationCode())) {
            QueryWrapper<EquipmentCategory> equipmentCategoryQueryWrapper = new QueryWrapper<>();
            equipmentCategoryQueryWrapper.eq("code", dto.getEquipmentClassificationCode());
            equipmentCategoryQueryWrapper.eq("industry_code", dto.getIndustryCode());
            List<EquipmentCategory> equipmentCategoryList = equipmentCategoryService.list(equipmentCategoryQueryWrapper);
            if (CollectionUtils.isEmpty(equipmentCategoryList)) {
                throw new RuntimeException("装备定义code有误");
            }
            EquipmentCategory equipmentCategory = equipmentCategoryList.get(0);
            int inhierarchy = 1;
            int flag = 0;
            for (int i = 0; i < result.length + 1; i++) {
                //进来先判断是否默认就是空，如果为空第一层
                if (equipmentCategory.getParentId() == null) {
                    //判断是否是最下面的子节点
                    if (i >= 4) {
                        inhierarchy = 8;
                    } else {
                        inhierarchy = map.get(i);
                    }
                    flag = i;
                    break;
                } else {
                    //查找到循环几次为空
                    equipmentCategory = equipmentCategoryService.getById(equipmentCategory.getParentId());
                }
            }
            if (flag == 0) {
                String classificationCode = dto.getEquipmentClassificationCode().replaceAll("0+$", "");
                exportList = wlSpareEquipmentService.exportList(dto, inhierarchy, classificationCode);
            } else {
                String classificationCode = dto.getEquipmentClassificationCode().replaceAll("0+$", "");
                exportList =  wlSpareEquipmentService.exportList(dto, inhierarchy, classificationCode.length() % 2 == 0 ? classificationCode : classificationCode + "0");
            }
        } else {
            exportList = wlSpareEquipmentService.exportList(dto, 0, null);
        }
        List<WlSpareEquipmentExportVo> exportVoList = new ArrayList<>();
        exportList.forEach(item -> {
            WlSpareEquipmentExportVo exportVo = new WlSpareEquipmentExportVo();
            BeanUtils.copyProperties(item, exportVo, "single");
            exportVo.setSingle(SingleEnum.DXGL.getKey().equals(item.getSingle()) ? "单项管理" : "批量管理");
            exportVo.setWarehouseStructure(item.getWarehouseStructureCode());
            exportVo.setProductionDate(DateUtil.format(item.getProductionDate(), DatePattern.NORM_DATE_PATTERN));
            exportVo.setPurchaseDate(DateUtil.format(item.getPurchaseDate(), DatePattern.NORM_DATE_PATTERN));
            exportVoList.add(exportVo);
        });
        ExcelUtil.createTemplate(response, "消防装备备品备件", "备品备件信息", exportVoList, WlSpareEquipmentExportVo.class, null, false);
    }

    /**
     * 设备信息导入
     *
     * @return
     */
    @PostMapping(value = "/uploadList")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "导入", notes = "导入")
    public ResponseModel uploadList(MultipartFile file) {
        try {
            // 设置导入参数
            ImportParams params = new ImportParams();
            params.setTitleRows(0); // 标题行数
            params.setHeadRows(1); // 表头行数
            // 导入数据
            List<WlSpareEquipmentExportVo> list = ExcelImportUtil.importExcel(file.getInputStream(), WlSpareEquipmentExportVo.class, params);
            // 处理导入的数据，例如保存到数据库中
            wlSpareEquipmentService.saveImportBatch(list, getSelectedOrgInfo());
            // JSON.toJSONString(list)
            return CommonResponseUtil.success();
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResponseUtil.failure("导入失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResponseUtil.success();
    }


    /**
     * 获取装备类型和统计值
     *
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取装备类型和统计值", notes = "获取装备类型和统计值")
    @GetMapping(value = "/getEquipmentTypeAndCount/tree")
    public ResponseModel getEquipmentTypeAndCount(@RequestParam(required = false) String bizOrgCode) throws Exception {
        if (StrUtil.isEmpty(bizOrgCode)) {
            bizOrgCode = getSelectedOrgInfo().getPersonIdentity().getCompanyBizOrgCode();
        }
        return CommonResponseUtil.success(wlSpareEquipmentService.getEquipmentTypeAndCount(bizOrgCode));
    }

    @RequestMapping(value = "/countSpareEquip", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "卡片 - 根据装备定义分组数量统计", notes = "卡片 - 根据装备定义分组数量统计")
    public ResponseModel<List<Map<String, Object>>> countSpareEquip(@RequestParam(required = false) String bizOrgCode) {
        if (StrUtil.isEmpty(bizOrgCode)) {
            bizOrgCode = getSelectedOrgInfo().getPersonIdentity().getCompanyBizOrgCode();
        }
        List<Map<String, Object>> resultMap = wlSpareEquipmentService.countSpareEquip(bizOrgCode);
        return CommonResponseUtil.success(resultMap);
    }
}
