package cn.ezhizao.project.business.controller;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.task.RyTask;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.domain.BizTransferCode;
import cn.ezhizao.project.system.domain.SysDept;
import cn.ezhizao.project.system.mapper.SysDeptMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.security.access.prepost.PreAuthorize;
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 cn.ezhizao.project.business.domain.BizTransferCode;
import cn.ezhizao.project.business.service.IBizTransferCodeService;


/**
 * 转运码Controller
 *
 * @author ezhizao
 * @date 2025-05-19
 */
@RestController
@RequestMapping("/business/transferCode")
public class BizTransferCodeController extends BaseController
{
    @Resource
    private IBizTransferCodeService bizTransferCodeService;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    HttpServletRequest request;
    @Resource
    private RyTask task;

    /**
     * 查询转运码列表
     */
    @GetMapping("/list")
    public TableDataInfo list(BizTransferCode bizTransferCode) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
        startPage();
        String tenantId = request.getHeader("tenantId");
        if(!tenantId.equals("0")){
            bizTransferCode.setTenantId(Long.valueOf(tenantId));
        }
        List<BizTransferCode> list = bizTransferCodeService.getList(bizTransferCode);
        for (BizTransferCode item : list
        ) {
            if (item.getQcCode().equals("")) {
                task.GenerateQcCode(item);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出转运码列表
     */
    @PreAuthorize("@ss.hasPermi('business:transferCode:export')")
    @Log(title = "转运码", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizTransferCode bizTransferCode) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizTransferCode);
        List<BizTransferCode> list = bizTransferCodeService.getList(bizTransferCode);
        ExcelUtil<BizTransferCode> util = new ExcelUtil<BizTransferCode>(BizTransferCode.class);
        util.exportExcel(response, list, "转运码数据");
    }

    /**
     * 获取转运码详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:transferCode:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizTransferCodeService.getById(id));
    }

    /**
     * 新增转运码
     */
    @Log(title = "转运码", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizTransferCode bizTransferCode) throws NoSuchFieldException, IllegalAccessException
    {
        //厂别
        String tenantId = request.getHeader("tenantId");
        if(tenantId.equals("0")){
            tenantId = "1";
        }
        //判断起始编号是否使用
        List<BizTransferCode> startCodeList = bizTransferCodeService.query().eq("start_code", bizTransferCode.getStartCode()).ne("dept_id",bizTransferCode.getDeptId()).list();
        if(!startCodeList.isEmpty()){
            SysDept sysDept = sysDeptMapper.selectDeptById(startCodeList.get(0).getDeptId());
            return error("该起始编码已被"+sysDept.getDeptName()+"工段占用");
        }
        //判断当前工段起始编码的流水号
        List<BizTransferCode> list = bizTransferCodeService.query().eq("dept_id", bizTransferCode.getDeptId()).eq("start_code", bizTransferCode.getStartCode())
                .orderByDesc("serial_number").list();
        List<BizTransferCode> transferCodeList = new ArrayList<>();
        if(list.size() > 0){
            //当前工段起始编码存过值
            Long serialNumber = list.get(0).getSerialNumber();
            //超过三位
            if(serialNumber + bizTransferCode.getNum() > 999){
                return error("超过三位流水号，请重新生成");
            }
            for(int i = 0; i <  bizTransferCode.getNum(); i++){
                BizTransferCode code = new BizTransferCode();
                code.setTenantId(Long.valueOf(tenantId));
                code.setDeptId(bizTransferCode.getDeptId());
                code.setStartCode(bizTransferCode.getStartCode());
                ++serialNumber;
                code.setSerialNumber(serialNumber);
                String serialStr = String.format("%03d", serialNumber);
                // 拼接生成QcCode
                String codeStr = bizTransferCode.getStartCode() + serialStr;
                code.setCode(codeStr);
                transferCodeList.add(code);
            }
        }else{
            Long serialNumber = 0L;
            //当前年份没有存过值
            for(int i = 0; i <  bizTransferCode.getNum(); i++){
                BizTransferCode code = new BizTransferCode();
                code.setTenantId(Long.valueOf(tenantId));
                code.setDeptId(bizTransferCode.getDeptId());
                code.setStartCode(bizTransferCode.getStartCode());
                ++serialNumber;
                code.setSerialNumber(serialNumber);
                String serialStr = String.format("%03d", serialNumber);
                // 拼接生成QcCode
                String codeStr = bizTransferCode.getStartCode() + serialStr;
                code.setCode(codeStr);
                transferCodeList.add(code);
            }
        }
        return toAjax(bizTransferCodeService.saveBatch(transferCodeList));
    }

    /**
     * 修改转运码
     */
    @PreAuthorize("@ss.hasPermi('business:transferCode:edit')")
    @Log(title = "转运码", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizTransferCode bizTransferCode) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizTransferCode);
        return toAjax(bizTransferCodeService.updateById(bizTransferCode));
    }

    /**
     * 删除转运码
     */
    @PreAuthorize("@ss.hasPermi('business:transferCode:remove')")
    @Log(title = "转运码", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        return toAjax(bizTransferCodeService.removeBatchByIds(ids));
    }
}
