package com.bonus.sgzb.app.controller;

import cn.hutool.core.collection.CollUtil;
import com.bonus.sgzb.app.domain.BmAgreementInfo;
import com.bonus.sgzb.app.domain.TmTask;
import com.bonus.sgzb.app.service.AppBackApplyService;
import com.bonus.sgzb.app.service.TmTaskService;
import com.bonus.sgzb.base.api.domain.BackApplyInfo;
import com.bonus.sgzb.common.core.utils.DateUtils;
import com.bonus.sgzb.common.core.utils.StringHelper;
import com.bonus.sgzb.common.core.utils.StringUtils;
import com.bonus.sgzb.common.core.web.controller.BaseController;
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.common.log.annotation.Log;
import com.bonus.sgzb.common.log.enums.BusinessType;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
* @description 退料申请--app
* @author hay
* @date   2024/1/22 10:17
*/
@RestController
@RequestMapping("/base/back_apply")
public class AppBackApplyController extends BaseController {

    @Resource
    private AppBackApplyService backApplyService;

    /**
     * 服务对象
     */
    @Resource
    private TmTaskService tmTaskService;

    /**
     * 退料申请列表
     *
     * @param record 查询条件
     * @return AjaxResult对象
     */
    @Log(title = "退料申请列表", businessType = BusinessType.QUERY)
    @PostMapping("getbackList")
    public AjaxResult getbackList(@RequestBody BackApplyInfo record) {
        try {
            record.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
            List<BackApplyInfo> list = backApplyService.getbackList(record);
            return success(list);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取物料列表
     *
     * @param record 查询条件
     * @return AjaxResult对象
     */
    @Log(title = "获取退料物料列表", businessType = BusinessType.QUERY)
    @PostMapping("materialList")
    public AjaxResult materialList(@RequestBody BackApplyInfo record) {
        try {
            List<BackApplyInfo> list = backApplyService.materialList(record);
            return success(list);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 详情查看
     *
     * @param record 查询条件
     * @return AjaxResult对象
     */
    @Log(title = "退料详情查看", businessType = BusinessType.QUERY)
    @PostMapping("view")
    public AjaxResult view(@RequestBody BackApplyInfo record) {
        try {
            List<BackApplyInfo> list = backApplyService.view(record);
            return success(list);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 退料审核明细
     *
     * @param record 查询条件
     * @return AjaxResult对象
     */
    @Log(title = "退料审核明细", businessType = BusinessType.QUERY)
    @PostMapping("examineView")
    public AjaxResult examineView(@RequestBody BackApplyInfo record) {
        try {
            List<BackApplyInfo> list = backApplyService.examineView(record);
            return success(list);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除
     *
     * @param record 查询条件
     * @return AjaxResult对象
     */
    @Log(title = "退料删除", businessType = BusinessType.QUERY)
    @PostMapping("del")
    public AjaxResult del(@RequestBody BackApplyInfo record) {
        try {
            int re = backApplyService.del(record);
            if (re > 0) {
                return AjaxResult.success("删除成功");
            } else {
                return AjaxResult.error("删除失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询退料单位列表
     *
     * @param record 查询条件
     * @return AjaxResult对象
     */
    @Log(title = "退料申请-退料单位", businessType = BusinessType.QUERY)
    @PostMapping("getbackUnit")
    public AjaxResult getbackUnit(@RequestBody BmAgreementInfo record) {
        try {
            List<BmAgreementInfo> list = backApplyService.getbackUnit(record);
            return success(list);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询退料工程列表
     *
     * @param record 查询条件
     * @return AjaxResult对象
     */
    @Log(title = "退料申请-退料工程", businessType = BusinessType.QUERY)
    @PostMapping("getbackPro")
    public AjaxResult getbackPro(@RequestBody BmAgreementInfo record) {
        try {
            List<BmAgreementInfo> list = backApplyService.getbackPro(record);
            return success(list);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 新建退料任务单
     *
     * @return AjaxResult对象
     */
    @Log(title = "退料申请-新增", businessType = BusinessType.INSERT)
    @PostMapping("addBackTask")
    public AjaxResult addBackTask(@RequestBody TmTask task) {
        if (StringUtils.isNull(task)) {
            return AjaxResult.error("参数错误");
        }
        try {
            String code = purchaseCodeRule();
            // 创建任务(tm_task)
            task.setCode(code);
            boolean addTaskResult = backApplyService.insertTask(task) > 0;
            if (addTaskResult) {
                //任务协议表(tm_task_agreement)
                Boolean addTaskAgreementRes = backApplyService.insertTaskAgreement(task) > 0;
                if (addTaskAgreementRes) {
                    //退料任务表(back_apply_info)
                    Boolean addBackApply = backApplyService.insertBackApply(task) > 0;
                    if (addBackApply) {
                        return AjaxResult.success("任务创建成功,已完成");
                    } else {
                        return AjaxResult.error("退料任务创建失败");
                    }
                } else {
                    return AjaxResult.error("创建任务协议失败");
                }
            } else {
                return AjaxResult.error("创建任务失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 提交物料型号及数量
     *
     * @param record 查询条件
     * @return AjaxResult对象
     */
    @Log(title = "提交物料型号及数量", businessType = BusinessType.UPDATE)
    @PostMapping("upload")
    public AjaxResult upload(@RequestBody BackApplyInfo record) {
        try {
            if (CollUtil.isEmpty(record.getBackApplyDetails())) {
                return AjaxResult.error("退料设备明细为空，请重新选择后上传!");
            }
            for (BackApplyInfo backApplyInfo : record.getBackApplyDetails()) {
                backApplyInfo.setParentId(record.getParentId());
                boolean re = backApplyService.upload(backApplyInfo) > 0;
                if (!re) {
                    return AjaxResult.error("退料任务明细插入失败");
                }
            }
            return AjaxResult.success("退料任务明细插入成功,已完成");
        } catch (Exception e) {
            return AjaxResult.error("创建任务失败," + e.getCause().toString() + "," + e.getMessage());
        }
    }

    /**
     * 退料编号生成规则
     */
    private String purchaseCodeRule() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String taskNum = tmTaskService.selectTaskNumByMonths(nowDate, 36);
        if (StringHelper.isNotEmpty(taskNum)){
            // 将字符串转换为整数
            int num = Integer.parseInt(taskNum);
            // 执行加一操作
            num++;
            // 将结果转换回字符串格式，并确保结果是四位数，不足四位则在前面补0
            taskNum = String.format("%04d", num);
        }else {
            taskNum = "0001";
        }
        String code = "T" + format + "-" + taskNum;
        return code;
    }


    /**
     * 退料审核列表
     *
     * @param record 查询条件
     * @return AjaxResult对象
     */
    @Log(title = "获取退料审核列表-app", businessType = BusinessType.QUERY)
    @PostMapping("examineList")
    public AjaxResult examineList(@RequestBody BackApplyInfo record) {
        try {
            if (StringUtils.isNull(record)) {
                return AjaxResult.error("参数错误");
            }

            List<BackApplyInfo> list = backApplyService.examineList(record);
            return success(list);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


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

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