package com.bonus.sgzb.material.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.bonus.sgzb.common.core.utils.DateUtils;
import com.bonus.sgzb.common.core.utils.ListPagingUtil;
import com.bonus.sgzb.common.core.utils.ServletUtils;
import com.bonus.sgzb.common.core.utils.StringUtils;
import com.bonus.sgzb.common.core.utils.poi.ExcelUtil;
import com.bonus.sgzb.common.core.web.controller.BaseController;
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.common.core.web.page.TableDataInfo;
import com.bonus.sgzb.common.log.annotation.Log;
import com.bonus.sgzb.common.log.enums.BusinessType;
import com.bonus.sgzb.common.security.annotation.Logical;
import com.bonus.sgzb.common.security.annotation.RequiresPermissions;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.material.domain.BackApplyDto;
import com.bonus.sgzb.base.api.domain.BackApplyInfo;
import com.bonus.sgzb.material.service.BackApplyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

import static com.bonus.sgzb.common.core.web.page.TableSupport.PAGE_NUM;
import static com.bonus.sgzb.common.core.web.page.TableSupport.PAGE_SIZE;

/**
 * @author hay
 * @description 退料申请--后台
 * @date 2023/12/20 11:46
 */
@Api(tags = "退料申请")
@RestController
@RequestMapping("/backApply")
public class BackApplyController extends BaseController {

    @Autowired
    private BackApplyService backApplyService;

    /**
     * 获取退料审核列表
     */
    @ApiOperation(value = "获取退料申请列表-web")
    @GetMapping("/getBackApplyList")
    @RequiresPermissions("return:apply:list")
    public AjaxResult getBackApplyList(BackApplyInfo bean) {
        startPage();
        List<BackApplyInfo> list = backApplyService.getBackApplyList(bean);
        return AjaxResult.success(getDataTable(list));
    }

    @ApiOperation(value = "获取退料审核列表-web")
    @GetMapping("/getBackAuditList")
    public AjaxResult getBackAuditList(BackApplyInfo bean) {
        List<BackApplyInfo> list = backApplyService.getBackAuditList(bean);
        Integer pageIndex = Convert.toInt(ServletUtils.getParameter(PAGE_NUM), 1);
        Integer pageSize = Convert.toInt(ServletUtils.getParameter(PAGE_SIZE), 10);
        return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, list));
    }

 /*   @ApiOperation(value = "退料申请获取当前类型在用量")
    @GetMapping("/getUseNumByTypeId")
    public AjaxResult getUseNumByTypeId(String typeId) {
        return AjaxResult.success(backApplyService.getUseNumByTypeId(typeId));
    }*/

    @ApiOperation(value = "在用设备类型树")
    @PostMapping("/getUseTypeTree")
    public AjaxResult getUseTypeTree(@RequestBody BackApplyInfo bean) {
        return backApplyService.getUseTypeTree(bean);
    }

    /**
     * 获取在用物料列表
     */
    @ApiOperation(value = "获取在用物料列表")
    @GetMapping("/getMaterialList")
    public TableDataInfo getMaterialList(BackApplyInfo bean) {
        startPage();
        List<BackApplyInfo> list = backApplyService.getMaterialList(bean);
        return getDataTable(list);
    }

    /**
     * 退料申请详情
     */
    @ApiOperation(value = "退料申请（查看/退料单）")
    @GetMapping("/getViewByApply")
    @RequiresPermissions(value = {"return:apply:view","return:apply:list"}, logical = Logical.OR)
    public AjaxResult getViewByApply(BackApplyInfo bean) {
        if (bean.getViewWeb() == 1) {
            bean.setFlag(0);
            List<BackApplyInfo> list = backApplyService.getViewByApply(bean);
            return AjaxResult.success(list);
        } else {
            startPage();
            bean.setFlag(0);
            List<BackApplyInfo> list = backApplyService.getViewByApply(bean);
            return AjaxResult.success(getDataTable(list));
        }
    }

    /**
     * 退料申请详情--用于退料单，不带分页
     */
    @ApiOperation(value = "退料申请（驳回提交）")
    @GetMapping("/materialReturnNoteByApply")
    @RequiresPermissions("return:apply:reject:submit")
    public AjaxResult materialReturnNoteByApply(BackApplyInfo bean) {
        bean.setFlag(1);
        List<BackApplyInfo> list = backApplyService.getViewByApply(bean);
        return success(list);
    }

    /**
     * 退料审核详情
     */
    @ApiOperation(value = "退料审核（查看）")
    @GetMapping("/getViewByExamine")
    public TableDataInfo getViewByExamine(BackApplyInfo bean) {
        startPage();
        List<BackApplyInfo> list = backApplyService.getView(bean);
        return getDataTable(list);
    }

    /**
     * 退料审核详情-不带分页
     */
    @ApiOperation(value = "退料审核（审批/退料单）")
    @GetMapping("/materialReturnNoteByExamine")
    @RequiresPermissions("return:receive:list")
    public AjaxResult materialReturnNoteByExamine(BackApplyInfo bean) {
        List<BackApplyInfo> list = backApplyService.getView(bean);
        return success(list);
    }


    /**
     * 退料申请详情修改
     */
/*    @ApiOperation(value = "退料申请详情修改")
    @PostMapping("/setModify")
    public AjaxResult setModify(@RequestBody List<BackApplyInfo> bean) {
        return backApplyService.setModify(bean);
    }*/

    /**
     * 退料申请删除
     */
    @ApiOperation(value = "退料申请删除")
    @GetMapping("/del")
    @RequiresPermissions("return:apply:del")
    public AjaxResult del(BackApplyInfo bean) {
        return backApplyService.del(bean);
    }


    @Log(title = "退料申请提交", businessType = BusinessType.INSERT)
    @PostMapping("/submitBackApply")
    public AjaxResult submitBackApply(@RequestBody BackApplyInfo bean) {
        boolean addLeaseTaskResult = false;
        Long backApplyInfoId = 0L;
        if (StringUtils.isNull(bean)) {
            return AjaxResult.error("参数错误");
        }
        try {
            //生成退料编码
            String code = backApplyService.genderBackCode();
            if (StringUtils.isEmpty(code)) {
                return AjaxResult.error("后台退料编号生成异常，请重试!");
            }
            bean.setCode(code);
            bean.setTaskType(36);
            bean.setTaskStatus("37");
            // 创建任务
            boolean addTaskResult = backApplyService.insertSelective(bean) > 0;
            if (addTaskResult && bean.getTaskId() != null) {
                //任务协议表(tm_task_agreement)
                Boolean addTaskAgreementRes = backApplyService.insertTaskAgreement(bean) > 0;
                if (addTaskAgreementRes && bean.getBackApplyInfo() != null) {
                    if (CollUtil.isEmpty(bean.getBackApplyDetails())) {
                        return AjaxResult.error("退料设备明细为空，请重新选择后上传!");
                    }
                    if (StringUtils.isNull(bean.getBackApplyInfo())) {
                        return AjaxResult.error("退料任务信息为空，请重新选择后上传!");
                    }

                    Integer taskId = bean.getTaskId();
                    // 根据设备所属分公司拆分集合
                    List<List<BackApplyInfo>> backApplyInfoList = CollUtil.groupByField(bean.getBackApplyDetails(), "companyId");
                    // 判断拆分后的集合内是否有数据
                    if (CollUtil.isNotEmpty(backApplyInfoList)) {
                        // 对拆分后的集合进行each遍历
                        for (List<BackApplyInfo> leaseApplyDetailsList : backApplyInfoList) {
                            BackApplyInfo backApplyInfo1 = leaseApplyDetailsList.get(0);
                            // 对领料任务表的对象做数据处理
                            BackApplyInfo backApplyInfo = bean.getBackApplyInfo();
                            /* 创建领料单号*/
                            backApplyInfo.setCode(code);
                            /*设置任务ID*/
                            backApplyInfo.setTaskId(taskId);
                            /*设置设备所属分公司,用于交给哪家审核*/
                            backApplyInfo.setCompanyId(backApplyInfo1.getCompanyId());
                            // 创建领料任务，返回领料任务编号
                            addLeaseTaskResult = backApplyService.insertBackApply(backApplyInfo) > 0;
                            // 领料任务编号
                            backApplyInfoId = backApplyInfo.getId();

                            // 领料任务创建完成，进行领料任务明细插入
                            if (addLeaseTaskResult) {
                                if (StringUtils.isNotNull(backApplyInfoId)) {
                                    for (BackApplyInfo leaseApplyDetails : leaseApplyDetailsList) {
                                        /*  设置领料任务ID*/
                                        leaseApplyDetails.setId(backApplyInfoId);
                                        // 插入领料任务明细
                                        boolean addLeaseTaskDetailsResult = backApplyService.upload(leaseApplyDetails) > 0;
                                        if (!addLeaseTaskDetailsResult) {
                                            return AjaxResult.error("退料任务创建成功，但退料任务明细插入失败");
                                        }
                                    }

                                } else {
                                    return AjaxResult.error("退料任务编号为空");
                                }
                            } else {
                                return AjaxResult.error("创建退料任务失败,或退料明细为空");
                            }
                        }
                    } else {
                        return AjaxResult.error("创建任务失败，缺少数据");
                    }
                } else {
                    return AjaxResult.error("创建任务失败");
                }
            } else {
                return AjaxResult.error("创建任务失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("创建任务失败," + e.getCause().toString() + "," + e.getMessage());
        }
        return AjaxResult.success("退料任务创建成功");
    }

    @ApiOperation(value = "退料无需审批接口，如需审批请勿使用")
    @Log(title = "退料申请提交--by重庆", businessType = BusinessType.INSERT)
    @PostMapping("/submitBackApplyByCq")
    public AjaxResult submitBackApplyByCq(@RequestBody BackApplyInfo bean) {
        boolean addLeaseTaskResult;
        Long backApplyInfoId;
        if (StringUtils.isNull(bean)) {
            return AjaxResult.error("参数错误");
        }
        try {
            //生成退料编码
            String code = backApplyService.genderBackCode();
            if (StringUtils.isEmpty(code)) {
                return AjaxResult.error("后台退料编号生成异常，请重试!");
            }
            bean.setCode(code);
            bean.setTaskType(36);
            bean.setTaskStatus("38");
            bean.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
            // 创建任务
            boolean addTaskResult = backApplyService.insertSelective(bean) > 0;
            if (addTaskResult && bean.getTaskId() != null) {
                //任务协议表(tm_task_agreement)
                boolean addTaskAgreementRes = backApplyService.insertTaskAgreement(bean) > 0;
                if (addTaskAgreementRes && bean.getBackApplyInfo() != null) {
                    if (CollUtil.isEmpty(bean.getBackApplyDetails())) {
                        return AjaxResult.error("退料设备明细为空，请重新选择后上传!");
                    }
                    if (StringUtils.isNull(bean.getBackApplyInfo())) {
                        return AjaxResult.error("退料任务信息为空，请重新选择后上传!");
                    }

                    Integer taskId = bean.getTaskId();
                    // 根据设备所属分公司拆分集合
                    List<List<BackApplyInfo>> backApplyInfoList = CollUtil.groupByField(bean.getBackApplyDetails(), "companyId");
                    // 判断拆分后的集合内是否有数据
                    if (CollUtil.isNotEmpty(backApplyInfoList)) {
                        // 对拆分后的集合进行each遍历
                        for (List<BackApplyInfo> leaseApplyDetailsList : backApplyInfoList) {
                            BackApplyInfo backApplyInfo1 = leaseApplyDetailsList.get(0);
                            // 对领料任务表的对象做数据处理
                            BackApplyInfo backApplyInfo = bean.getBackApplyInfo();
                            /* 创建领料单号*/
                            backApplyInfo.setCode(code);
                            // -----重庆机具专属-----
                            backApplyInfo.setStatus("1");
                            backApplyInfo.setDirectAuditBy(1);
                            backApplyInfo.setDirectAuditTime(DateUtils.getNowDate());
                            backApplyInfo.setDirectAuditRemark("系统自动审批");
                            /*设置任务ID*/
                            backApplyInfo.setTaskId(taskId);
                            /*设置设备所属分公司,用于交给哪家审核*/
                            backApplyInfo.setCompanyId(backApplyInfo1.getCompanyId());
                            // 创建领料任务，返回领料任务编号
                            addLeaseTaskResult = backApplyService.insertBackApply(backApplyInfo) > 0;
                            // 领料任务编号
                            backApplyInfoId = backApplyInfo.getId();

                            // 领料任务创建完成，进行领料任务明细插入
                            if (addLeaseTaskResult) {
                                if (StringUtils.isNotNull(backApplyInfoId)) {
                                    for (BackApplyInfo leaseApplyDetails : leaseApplyDetailsList) {
                                        /*  设置领料任务ID*/
                                        leaseApplyDetails.setId(backApplyInfoId);
                                        leaseApplyDetails.setUpdateBy("admin");
                                        leaseApplyDetails.setRemark("系统自动审核");
                                        // 插入领料任务明细
                                        boolean addLeaseTaskDetailsResult = backApplyService.uploadByCq(leaseApplyDetails) > 0;
                                        if (!addLeaseTaskDetailsResult) {
                                            return AjaxResult.error("退料任务创建成功，但退料任务明细插入失败");
                                        }
                                    }
                                } else {
                                    return AjaxResult.error("退料任务编号为空");
                                }
                            } else {
                                return AjaxResult.error("创建退料任务失败,或退料明细为空");
                            }
                        }
                    } else {
                        return AjaxResult.error("创建任务失败，缺少数据");
                    }
                } else {
                    return AjaxResult.error("创建任务失败");
                }
            } else {
                return AjaxResult.error("创建任务失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("创建任务失败," + e.getCause().toString() + "," + e.getMessage());
        }
        // 重庆无需审批，创建成功后自动调用审核通过service
        // backApplyService.audit(bean);

        return AjaxResult.success("退料任务创建成功");
    }


    @Log(title = "退料申请提交", businessType = BusinessType.INSERT)
    @PostMapping("/submitRefuseBackApply")
    public AjaxResult submitRefuseBackApply(@RequestBody BackApplyInfo bean) {
        boolean addLeaseTaskResult = false;
        Long backApplyInfoId = 0L;
        if (StringUtils.isNull(bean)) {
            return AjaxResult.error("参数错误");
        }
        //先删除tm_task、tm_task_agreement、back_apply_details、back_apply_info
        backApplyService.delApply(bean);
        try {
            //生成退料编码
            String code = backApplyService.genderBackCode();
            if (StringUtils.isEmpty(code)) {
                return AjaxResult.error("后台退料编号生成异常，请重试!");
            }
            bean.setCode(code);
            bean.setTaskType(36);
            bean.setTaskStatus("37");
            boolean addTaskResult = backApplyService.insertSelective(bean) > 0;
            // 创建任务
            if (addTaskResult && bean.getTaskId() != null) {
                //任务协议表(tm_task_agreement)
                Boolean addTaskAgreementRes = backApplyService.insertTaskAgreement(bean) > 0;
                if (addTaskAgreementRes && bean.getBackApplyInfo() != null) {
                    if (CollUtil.isEmpty(bean.getBackApplyDetails())) {
                        return AjaxResult.error("退料设备明细为空，请重新选择后上传!");
                    }
                    if (StringUtils.isNull(bean.getBackApplyInfo())) {
                        return AjaxResult.error("退料任务信息为空，请重新选择后上传!");
                    }

                    Integer taskId = bean.getTaskId();
                    // 根据设备所属分公司拆分集合
                    List<List<BackApplyInfo>> backApplyInfoList = CollUtil.groupByField(bean.getBackApplyDetails(), "companyId");
                    // 判断拆分后的集合内是否有数据
                    if (CollUtil.isNotEmpty(backApplyInfoList)) {
                        // 对拆分后的集合进行each遍历
                        for (List<BackApplyInfo> leaseApplyDetailsList : backApplyInfoList) {
                            BackApplyInfo backApplyInfo1 = leaseApplyDetailsList.get(0);
                            // 对领料任务表的对象做数据处理
                            BackApplyInfo backApplyInfo = bean.getBackApplyInfo();
                            /* 创建领料单号*/
                            backApplyInfo.setCode(code);
                            /*设置任务ID*/
                            backApplyInfo.setTaskId(taskId);
                            /*设置设备所属分公司,用于交给哪家审核*/
                            backApplyInfo.setCompanyId(backApplyInfo1.getCompanyId());
                            // 创建领料任务，返回领料任务编号
                            addLeaseTaskResult = backApplyService.insertBackApply(backApplyInfo) > 0;
                            // 领料任务编号
                            backApplyInfoId = backApplyInfo.getId();

                            // 领料任务创建完成，进行领料任务明细插入
                            if (addLeaseTaskResult) {
                                if (StringUtils.isNotNull(backApplyInfoId)) {
                                    for (BackApplyInfo leaseApplyDetails : leaseApplyDetailsList) {
                                        /*  设置领料任务ID*/
                                        leaseApplyDetails.setId(backApplyInfoId);
                                        // 插入领料任务明细
                                        boolean addLeaseTaskDetailsResult = backApplyService.upload(leaseApplyDetails) > 0;
                                        if (!addLeaseTaskDetailsResult) {
                                            return AjaxResult.error("退料任务创建成功，但退料任务明细插入失败");
                                        }
                                    }

                                } else {
                                    return AjaxResult.error("退料任务编号为空");
                                }
                            } else {
                                return AjaxResult.error("创建退料任务失败,或退料明细为空");
                            }
                        }
                    } else {
                        return AjaxResult.error("创建任务失败，缺少数据");
                    }
                } else {
                    return AjaxResult.error("创建任务失败");
                }
            } else {
                return AjaxResult.error("创建任务失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("创建任务失败," + e.getCause().toString() + "," + e.getMessage());
        }
        return AjaxResult.success("退料任务创建成功");
    }

    @ApiOperation("退料审核-审核(web)")
    @Log(title = "退料审核列表-审核(web)", businessType = BusinessType.UPDATE)
    @PostMapping("/audit")
    public AjaxResult audit(@RequestBody BackApplyInfo record) {
        return backApplyService.audit(record);
    }


    @ApiOperation("退料批量审核-审核(web)")
    @Log(title = "退料批量审核-审核(web)", businessType = BusinessType.UPDATE)
    @PostMapping("/auditAll")
    public AjaxResult auditAll(@RequestBody BackApplyDto dto) {
        return backApplyService.auditAll(dto);
    }

    @ApiOperation("退料审核-驳回(web)")
    @Log(title = "退料审核列表-驳回(web)", businessType = BusinessType.UPDATE)
    @PostMapping("/refuse")
    public AjaxResult refuse(@RequestBody BackApplyInfo record) {
        return backApplyService.refuse(record);
    }


    /**
     * 退料申请导出
     */
    @ApiOperation("退料申请列表导出")
    @Log(title = "退料申请列表导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void exportApply(HttpServletResponse response, BackApplyInfo bean) {
        List<BackApplyInfo> list = backApplyService.getBackApplyList(bean);
        ExcelUtil<BackApplyInfo> util = new ExcelUtil<BackApplyInfo>(BackApplyInfo.class);
        util.exportExcel(response, list, "退料申请数据");
    }

    /**
     * 退料审核导出
     */
    @ApiOperation("退料审核列表导出")
    @Log(title = "退料审核列表导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportExamine")
    public void exportExamine(HttpServletResponse response, BackApplyInfo bean) {
        List<BackApplyInfo> list = backApplyService.getBackAuditList(bean);
        ExcelUtil<BackApplyInfo> util = new ExcelUtil<BackApplyInfo>(BackApplyInfo.class);
        util.exportExcel(response, list, "退料申请数据");
    }
}
