package com.aucma.base.controller;

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

import com.aucma.common.annotation.Log;
import com.aucma.common.enums.BusinessType;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
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.base.domain.BaseOrderInfo;
import com.aucma.base.service.IBaseOrderInfoService;
import com.aucma.common.utils.poi.ExcelUtil;
import com.aucma.common.core.page.TableDataInfo;

/**
 * 工单信息Controller
 *
 * @author Yinq
 * @date 2023-09-27
 */
@RestController
@RequestMapping("/base/orderInfo")
public class BaseOrderInfoController extends BaseController {
    @Autowired
    private IBaseOrderInfoService baseOrderInfoService;

    /**
     * 查询工单信息列表
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(BaseOrderInfo baseOrderInfo) {
        startPage();
        List<BaseOrderInfo> list = baseOrderInfoService.selectBaseOrderInfoList(baseOrderInfo);
        return getDataTable(list);
    }

    /**
     * 导出工单信息列表
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:export')")
    @Log(title = "工单信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BaseOrderInfo baseOrderInfo) {
        List<BaseOrderInfo> list = baseOrderInfoService.selectBaseOrderInfoList(baseOrderInfo);
        ExcelUtil<BaseOrderInfo> util = new ExcelUtil<BaseOrderInfo>(BaseOrderInfo.class);
        util.exportExcel(response, list, "工单信息数据");
    }

    /**
     * 获取工单信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:query')")
    @GetMapping(value = "/{objId}")
    public AjaxResult getInfo(@PathVariable("objId") Long objId) {
        return success(baseOrderInfoService.selectBaseOrderInfoByObjId(objId));
    }

    /**
     * 新增工单信息
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:add')")
    @Log(title = "工单信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BaseOrderInfo baseOrderInfo) {
        baseOrderInfo.setCreatedBy(getUsername());
        return toAjax(baseOrderInfoService.insertBaseOrderInfo(baseOrderInfo));
    }

    /**
     * 修改工单信息
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:edit')")
    @Log(title = "工单信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BaseOrderInfo baseOrderInfo) {
        baseOrderInfo.setUpdatedBy(getUsername());
        return toAjax(baseOrderInfoService.updateBaseOrderInfo(baseOrderInfo));
    }

    /**
     * 删除工单信息
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:remove')")
    @Log(title = "工单信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{objIds}")
    public AjaxResult remove(@PathVariable Long[] objIds) {
        return toAjax(baseOrderInfoService.deleteBaseOrderInfoByObjIds(objIds));
    }

    /**
     * 根据工单编号查询工单
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:query')")
    @GetMapping("/byCode/{orderCode}")
    public AjaxResult getByOrderCode(@PathVariable("orderCode") String orderCode) {
        return success(baseOrderInfoService.selectBaseOrderInfoByOrderCode(orderCode));
    }

    /**
     * 开始生产
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:start')")
    @Log(title = "工单执行", businessType = BusinessType.UPDATE)
    @PostMapping("/startProduction")
    public AjaxResult startProduction(@RequestParam String orderCode, @RequestParam String operator) {
        int result = baseOrderInfoService.startProduction(orderCode, operator);
        return result > 0 ? success("开始生产成功") : error("工单不存在");
    }

    /**
     * 完工提报
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:complete')")
    @Log(title = "工单执行", businessType = BusinessType.UPDATE)
    @PostMapping("/completeProduction")
    public AjaxResult completeProduction(@RequestParam String orderCode,
                                         @RequestParam Long completeQty,
                                         @RequestParam Long defectQty) {
        int result = baseOrderInfoService.completeProduction(orderCode, completeQty, defectQty);
        return result > 0 ? success("完工提报成功") : error("工单不存在");
    }

    /**
     * 更新完工数量
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:updateQty')")
    @Log(title = "工单执行", businessType = BusinessType.UPDATE)
    @PostMapping("/updateQuantity")
    public AjaxResult updateQuantity(@RequestParam String orderCode,
                                     @RequestParam Long completeQty,
                                     @RequestParam Long defectQty) {
        int result = baseOrderInfoService.updateQuantity(orderCode, completeQty, defectQty);
        return result > 0 ? success("更新数量成功") : error("工单不存在");
    }

    /**
     * 获取正在执行的工单列表
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:list')")
    @GetMapping("/getRunningOrders")
    public AjaxResult getRunningOrders() {
        List<BaseOrderInfo> orders = baseOrderInfoService.getRunningOrders();
        return AjaxResult.success(orders);
    }

    /**
     * 批量开始生产
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:edit')")
    @Log(title = "工单信息", businessType = BusinessType.UPDATE)
    @PutMapping("/batchStart")
    public AjaxResult batchStartProduction(@RequestBody Map<String, Object> params) {
        Long[] objIds = parseObjIds(params.get("objIds"));
        String operator = (String) params.get("operator");
        
        if (objIds == null || objIds.length == 0) {
            return AjaxResult.error("请选择要操作的工单");
        }
        if (operator == null || operator.isEmpty()) {
            return AjaxResult.error("请输入操作员");
        }
        
        return toAjax(baseOrderInfoService.batchStartProduction(objIds, operator));
    }

    /**
     * 批量更新完工数量
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:edit')")
    @Log(title = "工单信息", businessType = BusinessType.UPDATE)
    @PutMapping("/batchUpdateQty")
    public AjaxResult batchUpdateQuantity(@RequestBody Map<String, Object> params) {
        Long[] objIds = parseObjIds(params.get("objIds"));
        Long completeQty = parseLong(params.get("completeQty"));
        Long defectQty = parseLong(params.get("defectQty"));
        
        if (objIds == null || objIds.length == 0) {
            return AjaxResult.error("请选择要操作的工单");
        }
        
        return toAjax(baseOrderInfoService.batchUpdateQuantity(objIds, completeQty, defectQty));
    }

    /**
     * 批量完工提报
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:edit')")
    @Log(title = "工单信息", businessType = BusinessType.UPDATE)
    @PutMapping("/batchComplete")
    public AjaxResult batchCompleteProduction(@RequestBody Map<String, Object> params) {
        Long[] objIds = parseObjIds(params.get("objIds"));
        Long completeQty = parseLong(params.get("completeQty"));
        Long defectQty = parseLong(params.get("defectQty"));
        
        if (objIds == null || objIds.length == 0) {
            return AjaxResult.error("请选择要操作的工单");
        }
        
        return toAjax(baseOrderInfoService.batchCompleteProduction(objIds, completeQty, defectQty));
    }

    /**
     * 解析objIds参数
     */
    private Long[] parseObjIds(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj instanceof List) {
            List<?> list = (List<?>) obj;
            Long[] result = new Long[list.size()];
            for (int i = 0; i < list.size(); i++) {
                Object item = list.get(i);
                if (item instanceof Number) {
                    result[i] = ((Number) item).longValue();
                } else {
                    result[i] = Long.parseLong(item.toString());
                }
            }
            return result;
        }
        return null;
    }

    /**
     * 解析Long类型参数
     */
    private Long parseLong(Object obj) {
        if (obj == null) {
            return 0L;
        }
        if (obj instanceof Number) {
            return ((Number) obj).longValue();
        }
        try {
            return Long.parseLong(obj.toString());
        } catch (NumberFormatException e) {
            return 0L;
        }
    }

    /**
     * 获取指定设备正在执行的工单
     */
    @PreAuthorize("@ss.hasPermi('base:orderInfo:query')")
    @GetMapping("/running/{deviceCode}")
    public AjaxResult getRunningOrderByDevice(@PathVariable String deviceCode) {
        return success(baseOrderInfoService.getRunningOrderByDevice(deviceCode));
    }
}
