package com.shinsoft.sto.controller.record;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.shinsoft.sto.model.record.ImportModel;
import com.shinsoft.sto.model.system.ResultJSON;
import com.shinsoft.sto.service.record.InrecordService;
import com.shinsoft.sto.tools.ExcelExportTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/InRecord")
public class InRecordController {

    @Autowired
    private ExcelExportTools excelExportTools;

    @Autowired
    private InrecordService inrecordService;

    @RequestMapping("/query")
    public ResultJSON query(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "50") int rows, String params, HttpServletRequest request) {
        try {
            Map<String, Object> map = buildQueryParams(params, request);
            return inrecordService.query(page, rows, map);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultJSON.error("查询失败：" + ex.getMessage());
        }
    }

    @GetMapping("/statistics")
    public ResultJSON statistics(String params, HttpServletRequest request) {
        try {
            Map<String, Object> map = buildQueryParams(params, request);
            return inrecordService.statistics(map);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultJSON.error("统计失败：" + ex.getMessage());
        }
    }

    private String resolveBelongId(HttpServletRequest request) {
        String belongId = (String) request.getHeader("belongId");
        if (belongId == null) {
            belongId = (String) request.getAttribute("belongId");
        }
        return belongId;
    }

    private String resolveUserId(HttpServletRequest request) {
        String userId = (String) request.getHeader("userId");
        if (userId == null) {
            userId = (String) request.getAttribute("userId");
        }
        return userId;
    }

    private String resolveUserName(HttpServletRequest request) {
        String userId = (String) request.getHeader("userName");
        if (userId == null) {
            userId = (String) request.getAttribute("userName");
        }
        return userId;
    }

    @SuppressWarnings("unchecked")
    private Map<String, Object> buildQueryParams(String params, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        if (params != null && !params.trim().isEmpty()) {
            map.putAll(JSON.parseObject(params, Map.class));
        }
//        map.put("belongId", resolveBelongId(request));
        return map;
    }

    /**
     * 下载导入模板
     */
    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) {
        try {
            List<ImportModel> list = new ArrayList<>();
            excelExportTools.exportExcel(response, list, "入库模板", "入库模板", ImportModel.class);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @RequestMapping("/exportInRecode")
    public void exportInRecode(HttpServletResponse response,@RequestBody List<ImportModel> list) {
        try {
            excelExportTools.exportExcel(response, list, "入库记录", "入库记录", ImportModel.class);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Excel文件上传
     */
    @RequestMapping("/uploadExcel")
    public ResultJSON uploadExcel(MultipartFile file, HttpServletRequest request) {
        try {
            if (file == null || file.isEmpty()) {
                return ResultJSON.error("请选择要上传的文件");
            }

            // 验证文件类型
            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))) {
                return ResultJSON.error("请上传Excel文件(.xls 或 .xlsx)");
            }

            // 解析Excel文件
            List<ImportModel> dataList = excelExportTools.parseExcelFile(file);
            return ResultJSON.success(dataList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultJSON.error("文件上传失败：" + ex.getMessage());
        }
    }

    /**
     * 批量入库
     */
    @PostMapping("/batchInStore")
    public ResultJSON batchInStore( @RequestParam("dataList") String json, HttpServletRequest request) {
        try {
            List<ImportModel> dataList = JSON.parseArray(json, ImportModel.class);
            String userId = resolveUserId(request);
            String belongId = resolveBelongId(request);
            String userName = resolveUserName(request);
            return inrecordService.batchInStore(userId, dataList, belongId,userName);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultJSON.error("入库失败：" + ex.getMessage());
        }
    }

    /**
     * 取消入库
     */
    @PostMapping("/cancelInStore")
    public ResultJSON cancelInStore(String params, HttpServletRequest request) {
        try {
            String userId = resolveUserId(request);
            String belongId = resolveBelongId(request);
            Map<String, Object> map = buildQueryParams(params, request);
            return inrecordService.cancelInStore(map,userId,belongId);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultJSON.error("取消入库失败：" + ex.getMessage());
        }
    }

}

