package com.aucma.production.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.aucma.common.utils.DateUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.aucma.common.annotation.Log;
import com.aucma.common.core.controller.BaseController;
import com.aucma.common.core.domain.AjaxResult;
import com.aucma.common.enums.BusinessType;
import com.aucma.production.domain.MrpProdWeeklyPlan;
import com.aucma.production.service.IMrpProdWeeklyPlanService;
import com.aucma.common.utils.poi.ExcelUtil;
import com.aucma.common.core.page.TableDataInfo;

/**
 * 周排产计划Controller
 *
 * @author Yinq
 * @date 2026-01-05
 */
@RestController
@RequestMapping("/production/plan" )
public class MrpProdWeeklyPlanController extends BaseController {
    @Autowired
    private IMrpProdWeeklyPlanService mrpProdWeeklyPlanService;

    /**
     * 查询周排产计划列表
     */
    @PreAuthorize("@ss.hasPermi('production:plan:list')" )
    @GetMapping("/list" )
    public TableDataInfo list(MrpProdWeeklyPlan mrpProdWeeklyPlan) {
        startPage();
        List<MrpProdWeeklyPlan> list = mrpProdWeeklyPlanService.selectMrpProdWeeklyPlanList(mrpProdWeeklyPlan);
        return getDataTable(list);
    }

    /**
     * 导出周排产计划列表
     */
    @PreAuthorize("@ss.hasPermi('production:plan:export')" )
    @Log(title = "周排产计划" , businessType = BusinessType.EXPORT)
    @PostMapping("/export" )
    public void export(HttpServletResponse response, MrpProdWeeklyPlan mrpProdWeeklyPlan) {
        List<MrpProdWeeklyPlan> list = mrpProdWeeklyPlanService.selectMrpProdWeeklyPlanList(mrpProdWeeklyPlan);
        ExcelUtil<MrpProdWeeklyPlan> util = new ExcelUtil<MrpProdWeeklyPlan>(MrpProdWeeklyPlan. class);
        util.exportExcel(response, list, "周排产计划数据" );
    }

    /**
     * 获取周排产计划详细信息
     */
    @PreAuthorize("@ss.hasPermi('production:plan:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult getInfo(@PathVariable("id" ) Long id) {
        return success(mrpProdWeeklyPlanService.selectMrpProdWeeklyPlanById(id));
    }

    /**
     * 新增周排产计划
     */
    @PreAuthorize("@ss.hasPermi('production:plan:add')" )
    @Log(title = "周排产计划" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MrpProdWeeklyPlan mrpProdWeeklyPlan) {
        mrpProdWeeklyPlan.setCreatedAt(DateUtils.getNowDate());
        return toAjax(mrpProdWeeklyPlanService.insertMrpProdWeeklyPlan(mrpProdWeeklyPlan));
    }

    /**
     * 修改周排产计划
     */
    @PreAuthorize("@ss.hasPermi('production:plan:edit')" )
    @Log(title = "周排产计划" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MrpProdWeeklyPlan mrpProdWeeklyPlan) {
        mrpProdWeeklyPlan.setUpdatedAt(DateUtils.getNowDate());
        return toAjax(mrpProdWeeklyPlanService.updateMrpProdWeeklyPlan(mrpProdWeeklyPlan));
    }

    /**
     * 删除周排产计划
     */
    @PreAuthorize("@ss.hasPermi('production:plan:remove')" )
    @Log(title = "周排产计划" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(mrpProdWeeklyPlanService.deleteMrpProdWeeklyPlanByIds(ids));
    }

    /**
     * 批量更新周排产计划
     */
    @PreAuthorize("@ss.hasPermi('production:plan:edit')" )
    @Log(title = "周排产计划" , businessType = BusinessType.UPDATE)
    @PutMapping("/batchUpdate" )
    public AjaxResult batchUpdate(@RequestBody List<MrpProdWeeklyPlan> list) {
        int count = 0;
        for (MrpProdWeeklyPlan item : list) {
            item.setUpdatedAt(DateUtils.getNowDate());
            count += mrpProdWeeklyPlanService.updateMrpProdWeeklyPlan(item);
        }
        return success("成功更新 " + count + " 条数据");
    }

    /**
     * 导入周排产计划
     * @param file Excel文件
     * @param updateSupport 是否更新已存在数据
     * @param weekStartDate 周一日期（yyyy-MM-dd格式）
     */
    @PreAuthorize("@ss.hasPermi('production:plan:import')" )
    @Log(title = "周排产计划" , businessType = BusinessType.IMPORT)
    @PostMapping("/importData" )
    public AjaxResult importData(MultipartFile file, boolean updateSupport, String weekStartDate) throws Exception {
        System.out.println("========== 开始导入周排产计划 ==========");
        System.out.println("weekStartDate: " + weekStartDate);
        System.out.println("file name: " + file.getOriginalFilename());
        System.out.println("file size: " + file.getSize());
        
        ExcelUtil<MrpProdWeeklyPlan> util = new ExcelUtil<MrpProdWeeklyPlan>(MrpProdWeeklyPlan.class);
        List<MrpProdWeeklyPlan> list = null;
        try {
            list = util.importExcel(file.getInputStream());
            System.out.println("解析Excel成功，共 " + list.size() + " 条数据");
            if (list.size() > 0) {
                MrpProdWeeklyPlan first = list.get(0);
                System.out.println("第一条数据: seqNo=" + first.getSeqNo() + ", itemCode=" + first.getItemCode() + ", itemDesc=" + first.getItemDesc());
            }
        } catch (Exception e) {
            System.out.println("解析Excel失败: " + e.getMessage());
            System.out.println("异常类型: " + e.getClass().getName());
            if (e.getCause() != null) {
                System.out.println("根本原因: " + e.getCause().getMessage());
                System.out.println("根本原因类型: " + e.getCause().getClass().getName());
                e.getCause().printStackTrace();
            } else {
                e.printStackTrace();
            }
            throw e;
        }
        
        String message = mrpProdWeeklyPlanService.importData(list, updateSupport, getUsername(), weekStartDate);
        System.out.println("导入完成: " + message);
        return success(message);
    }

    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate" )
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<MrpProdWeeklyPlan> util = new ExcelUtil<MrpProdWeeklyPlan>(MrpProdWeeklyPlan.class);
        util.importTemplateExcel(response, "周排产计划模板" );
    }
}
