package com.gci.boot.modules.vehicles.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gci.boot.annotation.Query.handle.QueryGenerator;
import com.gci.boot.common.dict.excel.MyExcelDictHandleImpl;
import com.gci.boot.common.validated.UpdateValidated;
import com.gci.boot.modules.system.vo.LoginUser;
import com.gci.boot.modules.vehicles.entity.TbConsumablesTemplateOutPart;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gci.boot.annotation.permission.DataPermission;
import com.gci.boot.common.log.annotation.AddSysLog;
import com.gci.boot.common.validated.SaveValidated;
import com.gci.boot.common.vo.Result;
import com.gci.boot.modules.vehicles.entity.TbConsumablesTemplatePart;
import com.gci.boot.modules.vehicles.service.ITbConsumablesTemplatePartService;

/**
 * <p>
 * 耗材详情 前端控制器
 * </p>
 *
 * @author 2464
 * @since 2023-09-12
 */
@RestController
@RequestMapping("/vehicles/consumablesPart")
public class TbConsumablesTemplatePartController {
    @Autowired
    private ITbConsumablesTemplatePartService iTbConsumablesTemplatePartService;

    @GetMapping("/init")
    public Result<?> init() {
        iTbConsumablesTemplatePartService.init();
        return Result.ok();
    }

    /**
     * 分页列表查询
     *
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AddSysLog(value = "耗材详情-分页列表查询")
    @GetMapping(value = "/list")
    @DataPermission(item = "tb_consumables_template_part.projectId",
        sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbConsumablesTemplatePartMapper.selectPage"})
    public Result<?> queryPageList(TbConsumablesTemplatePart query,
        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Page<TbConsumablesTemplatePart> page = new Page<TbConsumablesTemplatePart>(pageNo, pageSize);
        LambdaQueryWrapper<TbConsumablesTemplatePart> lambdaQueryWrapper =
            QueryGenerator.initQueryWrapper(TbConsumablesTemplatePart.class, query);
        IPage<TbConsumablesTemplatePart> pageList =
            iTbConsumablesTemplatePartService.pageBuild(page, lambdaQueryWrapper,false);
        return Result.ok(pageList);
    }

    @AddSysLog(value = "耗材详情-分页列表查询")
    @GetMapping(value = "/listHadQuantity")
    @DataPermission(item = "tb_consumables_template_part.projectId",
            sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbConsumablesTemplatePartMapper.selectPage"})
    public Result<?> listHadQuantity(TbConsumablesTemplatePart query,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Page<TbConsumablesTemplatePart> page = new Page<TbConsumablesTemplatePart>(pageNo, pageSize);
        LambdaQueryWrapper<TbConsumablesTemplatePart> lambdaQueryWrapper =
                QueryGenerator.initQueryWrapper(TbConsumablesTemplatePart.class, query);
        IPage<TbConsumablesTemplatePart> pageList =
                iTbConsumablesTemplatePartService.pageBuild(page, lambdaQueryWrapper,true);
        return Result.ok(pageList);
    }

    /**
     * 入库
     */
    @AddSysLog(value = "耗材详情-入库")
    @PostMapping(value = "/inStorage")
    public Result<?> addInStorage(@RequestBody @Validated(SaveValidated.class) List<TbConsumablesTemplatePart> partList) {
        iTbConsumablesTemplatePartService.inStorage(partList);
        return Result.ok("入库成功！");
    }

    /**
     * 出库
     */
    @AddSysLog(value = "耗材详情-出库")
    @PostMapping(value = "/outStorage")
    public Result<?> addOutStorage(@RequestBody @Validated(SaveValidated.class) List<TbConsumablesTemplateOutPart> outPartList) {
        iTbConsumablesTemplatePartService.outStorage(outPartList);
        return Result.ok("出库成功！");
    }

    /**
     * 同时更新入库或者出库
     */
    @AddSysLog(value = "耗材详情-出库")
    @PostMapping(value = "/inAndOutStorage")
    public Result<?> editInAndOutStorage(@RequestBody @Validated(UpdateValidated.class) TbConsumablesTemplatePart partList) {
        iTbConsumablesTemplatePartService.inAndOutStorage(partList);
        return Result.ok("更新库存成功！");
    }

    /**
     * 导出
     */
    @AddSysLog(value = "耗材详情-导出")
    @GetMapping(value = "/export")
    @DataPermission(item = "tb_consumables_template_part.projectId",
            sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbConsumablesTemplatePartMapper.selectPage"})
    public Result<?> export(HttpServletResponse response, TbConsumablesTemplatePart query) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        try (OutputStream output = response.getOutputStream()) {
            String fileName = "耗材管理.xlsx";
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);
            Page<TbConsumablesTemplatePart> page = new Page<TbConsumablesTemplatePart>(1, -1);
            LambdaQueryWrapper<TbConsumablesTemplatePart> lambdaQueryWrapper =
                    QueryGenerator.initQueryWrapper(TbConsumablesTemplatePart.class, query);
            IPage<TbConsumablesTemplatePart> pageList =
                    iTbConsumablesTemplatePartService.pageBuild(page, lambdaQueryWrapper,false);

            List<TbConsumablesTemplatePart> records = pageList.getRecords();
            ArrayList<TbConsumablesTemplateOutPart> outParts = new ArrayList<>();
            for (TbConsumablesTemplatePart record : records) {
                if (ObjectUtil.isNotEmpty(record.getOutPartList())) {
                    outParts.addAll(record.getOutPartList());
                }
            }


            //创建总的集合存放每一页的数据集合
            List<Map<String, Object>> sheetsList = new ArrayList<>();
            // 使用map 创建sheet1
            Map<String, Object> sheetMap1 = new HashMap<>();
            ExportParams exportParams1 = new ExportParams();
            exportParams1.setDictHandler(new MyExcelDictHandleImpl());
            exportParams1.setSheetName("总览");
            exportParams1.setTitle("查询时间：" + new DateTime().toString() + " 查询人:" + sysUser.getRealname());
            sheetMap1.put("title",exportParams1);
            sheetMap1.put("entity",TbConsumablesTemplatePart.class);
            sheetMap1.put("data",records);
            // 使用map 创建sheet2
            Map<String, Object> sheetMap2 = new HashMap<>();
            ExportParams exportParams2 = new ExportParams();
            exportParams2.setDictHandler(new MyExcelDictHandleImpl());
            exportParams2.setSheetName("出库");
            sheetMap2.put("title",exportParams2);
            sheetMap2.put("entity",TbConsumablesTemplateOutPart.class);
            sheetMap2.put("data",outParts);
            sheetsList.add(sheetMap1);
            sheetsList.add(sheetMap2);

            Workbook sheets = ExcelExportUtil.exportExcel(sheetsList, ExcelType.XSSF);
            sheets.write(output);
        } catch (IOException e) {
            return Result.error("导出错误！");
        }
        return Result.ok();
    }
}
