package cn.ezhizao.project.business.controller;

import cn.ezhizao.common.utils.SecurityUtils;
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.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.domain.*;
import cn.ezhizao.project.business.service.*;
import cn.ezhizao.project.system.domain.SysDept;
import cn.ezhizao.project.system.domain.SysDeptUser;
import cn.ezhizao.project.system.service.ISysDeptService;
import cn.ezhizao.project.system.service.ISysDeptUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

/**
 * 生产子计划明细Controller
 *
 * @author ezhizao
 * @date 2023-11-15
 */
@RestController
@RequestMapping("/business/planDetailSubDetail")
public class BizProductionPlanDetailSubDetailController extends BaseController {
    @Resource
    private IBizLotService bizLotService;
    @Resource
    private IBizProductionPlanDetailService bizProductionPlanDetailService;
    @Resource
    private IBizProductionPlanDetailSubDetailService bizProductionPlanDetailSubDetailService;

    @Resource
    private IBizProductionResourceGroupSubPlanService bizProductionResourceGroupSubPlanService;

    @Resource
    private IBizProductionResourceGroupService bizProductionResourceGroupService;

    @Resource
    private ISysDeptUserService deptUserService;
    @Resource
    private ISysDeptService deptService;
    @Resource
    private IBizDayworkService dayworkService;
    @Resource
    HttpServletRequest request;



    /**
     * 查询生产子计划明细列表
     */
//    @PreAuthorize("@ss.hasPermi('business:productionBatch:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizProductionPlanDetailSubDetail bizProductionPlanDetailSubDetail) throws NoSuchFieldException, IllegalAccessException {
//        String tenantId = request.getHeader("tenantId");
//        bizProductionPlanDetailSubDetail.setTenantId(Long.valueOf(tenantId));
        startPage();
        List<BizProductionPlanDetailSubDetail> list = bizProductionPlanDetailSubDetailService.getList(bizProductionPlanDetailSubDetail);
        return getDataTable(list);
    }


    /**
     * 查询当前工段
     */
//    @PreAuthorize("@ss.hasPermi('business:planDetailSubDetail:list')")
    @GetMapping("/getDept")
    public AjaxResult getDept() throws NoSuchFieldException, IllegalAccessException {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        String tenantId = request.getHeader("tenantId");

        QueryWrapper<SysDeptUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("deleted",0);
        queryWrapper.eq("is_formman",1);
//        if (!"0".equals(tenantId)) {
//            queryWrapper.eq("tenant_id", Long.valueOf(tenantId));
//        }
        List<SysDeptUser> deptUserList = deptUserService.list(queryWrapper);
        List<Long> ids = new ArrayList<>();
        for (SysDeptUser item : deptUserList) {
            ids.add(item.getDeptId());
        }
        List<SysDept> deptOptions = new ArrayList<>();
        if (ids.size() > 0) {
            deptOptions = deptService.getDeptOptions(ids);
        }

        return success(deptOptions);
    }

    /**
     * 导出生产子计划明细列表
     */
    @PreAuthorize("@ss.hasPermi('business:planDetailSubDetail:export')")
    @Log(title = "生产子计划明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizProductionPlanDetailSubDetail bizProductionPlanDetailSubDetail) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizProductionPlanDetailSubDetail);
        List<BizProductionPlanDetailSubDetail> list = bizProductionPlanDetailSubDetailService.getList(bizProductionPlanDetailSubDetail);
        ExcelUtil<BizProductionPlanDetailSubDetail> util = new ExcelUtil<BizProductionPlanDetailSubDetail>(BizProductionPlanDetailSubDetail.class);
        util.exportExcel(response, list, "生产子计划明细数据");
    }

    /**
     * 获取生产子计划明细详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:planDetailSubDetail:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        BizProductionPlanDetailSubDetail bizProductionPlanDetailSubDetail = new BizProductionPlanDetailSubDetail();
        bizProductionPlanDetailSubDetail.setId(id);
        List<BizProductionPlanDetailSubDetail> list = bizProductionPlanDetailSubDetailService.getList(bizProductionPlanDetailSubDetail);
        if (list.size() > 1) {
            return error();
        }
        return success(list.get(0));
    }

    /**
     * 获取生产子计划明细尾批状态
     */
//    @PreAuthorize("@ss.hasPermi('business:planDetailSubDetail:query')")
    @GetMapping(value = "/getLastLotStatus/{id}")
    public AjaxResult getLastLotStatus(@PathVariable("id") Long id) {
        QueryWrapper<BizProductionPlanDetailSubDetail> queryWrapper = new QueryWrapper<>();
          queryWrapper.eq("production_plan_detail_id", id)
                .eq("deleted", 0)
                .eq("last_lot_status", 1);
          Boolean lastLotStat = bizProductionPlanDetailSubDetailService.list(queryWrapper).size()>0?true:false;
        return success(lastLotStat);
    }

    /**
     * 新增生产子计划明细
     */

    @Log(title = "生产子计划明细", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/save")
    public AjaxResult add(@RequestBody BizProductionPlanDetailSubDetail bizProductionPlanDetailSubDetail) throws NoSuchFieldException, IllegalAccessException {
        String tenantId = request.getHeader("tenantId");
        bizProductionPlanDetailSubDetail.setTenantId(Long.valueOf(tenantId));

        /*
         * 德迈仕生产批号生成规则
         * 数据表mrp10201关键字段
         *
         * cpart: 产品编码字段
         * prver: 工艺版本字段（目前mrp10201表中没有该字段，需要德迈仕新增）
         * zzqty: 制造量（支），产品制造支数
         * phsl:  生成总批数
         * phsl1: 单个批次的产品支数
         * phsl2: 尾批次的产品支数
         *
         * 通过cpart、prver从产品工艺表sfc10401获取产品加工工艺后，根据phsl、phsl1、phsl2生成对应数量的批号。
         * 验证公式：zzqty=phsl1 * (phsl - 1) + phsl2
         *
         * 举例：
         * zzqty = 15000
         * phsl  = 273
         * phsl1 = 55
         * phsl2 = 40
         * 生成272批 支数为55的批次，再生成1批 支数为40的批次
         * 总计273个批次，15000产品支数
         *
         * 批号12位规则：
         * 第一位:       D表示德迈仕，J表示金华德
         * 第二三位:     年份后两位
         * 第四位:      月份（10月、11月、12月分别用A、B、C表示）
         * 第五至八位:   生产计划单流水号
         * 第九至十二位: 生产计划单下属批次流水号，
         *
         * D23727410070: 以这个批号为例
         * D    -德迈仕
         * 23   -2023年
         * 7    -7月
         * 2741 -生成计划单号（流水号）
         * 007  -批次流水号，这是第7个批次
         * 0    -用于分批，也就是一个批号，最多可以分9批
         *
         * 批次号生成规则
         * docno    docseq
         * D239096  1
         * D239096: D    --德迈仕
         *          23   --2023年
         *          9    --月份
         *          096  --序号的一部分
         *          1    --序号的另外一部分
         *          0961 --批次号中的“生产计划单流水号”部分
         */

        /* 获取生成计划明细 */
        final BizProductionPlanDetail planDetail = bizProductionPlanDetailService.getById(bizProductionPlanDetailSubDetail.getProductionPlanDetailId());
        final int lotNumber = planDetail.getTotalLotNumber();
        final int oneLotQuantity = planDetail.getOneLotQuantity();
        final int lastLotQuantity = planDetail.getLastLotQuantity();
        final String baseCode = planDetail.getProductionPlanNo().substring(0, 4);
        final String baseCodeSeq = planDetail.getProductionPlanNo().substring(4, 7) + planDetail.getLineNumber().toString();
        List<BizLot> productionPlanDetailId = bizLotService.query().eq("production_plan_detail_id", planDetail.getId()).eq("deleted",0).list();
        if (productionPlanDetailId.size()==0){
            List<BizLot> bizLotList = new ArrayList<>();
            for (int i = 0; i < lotNumber; ++i) {
                BizLot bizLot = new BizLot();
                /* 将i转换为3位字符串，位数不够，前面补0 */
                String lotSeq = String.format("%03d", i + 1);
                bizLot.setLotCode(baseCode + baseCodeSeq + lotSeq + "0");
                bizLot.setProductionPlanDetailId(planDetail.getId());
                bizLot.setTechnologicalProcessId(bizProductionPlanDetailSubDetail.getTechnologicalProcessId());
                bizLot.setTechnologyVersion(bizProductionPlanDetailSubDetail.getTechnologyVersion());
                bizLot.setProductId(bizProductionPlanDetailSubDetail.getProductId());
                bizLot.setProductDescription(bizProductionPlanDetailSubDetail.getProductDescription());
                bizLot.setProductionQuantity(oneLotQuantity);
                bizLot.setTenantId(bizProductionPlanDetailSubDetail.getTenantId());
                if (i == lotNumber - 1) {
                    bizLot.setProductionQuantity(lastLotQuantity);
                    bizLot.setIsLast(1);
                }
                bizLotList.add(bizLot);
            }
            if (bizLotList.size() > 0) {
                bizLotService.saveOrUpdateBatch(bizLotList);
            }
        }

        SysDept dept =deptService.selectDeptById(bizProductionPlanDetailSubDetail.getDeptId());
        //判断是否自动分配
        if(dept.getAutoAllocation()==1){

            //查询资源组数据
            BizProductionResourceGroup group=new BizProductionResourceGroup();
            group.setDeptId(dept.getDeptId());
            group.setIsDeactivate(0);
            List<BizProductionResourceGroup>  groupList =bizProductionResourceGroupService.getList(group);

            //查询是否分配过
            BizProductionResourceGroupSubPlan subPlan=new BizProductionResourceGroupSubPlan();
            subPlan.setProductionPlanDetailId(bizProductionPlanDetailSubDetail.getProductionPlanDetailId());
            subPlan.setDeptId(dept.getDeptId());
            List<BizProductionResourceGroupSubPlan>  list= bizProductionResourceGroupSubPlanService.getAotList(subPlan);
            //如果有数据代表分配过
            if(list.size()==0){
                //当没有分配过时，分配给所有资源组
                List<BizProductionResourceGroupSubPlan> planList=new ArrayList<>();
                for (BizProductionResourceGroup item: groupList) {
                    BizProductionResourceGroupSubPlan plan=new BizProductionResourceGroupSubPlan();
                    plan.setProductionPlanDetailId(bizProductionPlanDetailSubDetail.getProductionPlanDetailId());
                    plan.setProductId(bizProductionPlanDetailSubDetail.getProductId());
                    plan.setTechnologicalProcessId(bizProductionPlanDetailSubDetail.getTechnologicalProcessId());
                    plan.setDeptId(dept.getDeptId());
                    plan.setResourceGroupId(item.getId());
                    plan.setResourceGroupCode(item.getCode());
                    plan.setTenantId(bizProductionPlanDetailSubDetail.getTenantId());
                    plan.setCreatorId(getUserId());
                    planList.add(plan);
                }
                //保存
                bizProductionResourceGroupSubPlanService.saveBatch(planList);
            }
        }
        return toAjax(bizProductionPlanDetailSubDetailService.saveOrUpdate(bizProductionPlanDetailSubDetail));
    }

    /**
     * 修改生产子计划明细
     */

    @Log(title = "生产子计划明细", businessType = BusinessType.UPDATE)
    @PutMapping("/save")
    public AjaxResult edit(@RequestBody BizProductionPlanDetailSubDetail bizProductionPlanDetailSubDetail) throws NoSuchFieldException, IllegalAccessException {
//        String tenantId = request.getHeader("tenantId");
//        bizProductionPlanDetailSubDetail.setTenantId(Long.valueOf(tenantId));
        return toAjax(bizProductionPlanDetailSubDetailService.updateById(bizProductionPlanDetailSubDetail));
    }

    /**
     * 删除生产子计划明细
     */

    @Log(title = "生产子计划明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        //如果已经投产的生产子计划已经生成批次，则不能删除
        QueryWrapper<BizProductionPlanDetailSubDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",ids.get(0));
        BizProductionPlanDetailSubDetail bizProductionPlanDetailSubDetail = bizProductionPlanDetailSubDetailService.list(queryWrapper).get(0);
        QueryWrapper<BizDaywork> query = new QueryWrapper<>();
        query.eq("production_plan_detail_id",bizProductionPlanDetailSubDetail.getProductionPlanDetailId());
        query.eq("deleted",0);
        List<BizDaywork> list = dayworkService.list(query);
        if(list.size()>0) {
           return error("该批次已经生成就不能删除子计划");
        }
        return toAjax(bizProductionPlanDetailSubDetailService.removeBatchByIds(ids));
    }
}
