package com.ruoyi.web.controller.business;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.service.*;
import com.ruoyi.business.utils.OrderCodeFactory;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 退货Controller
 *
 * @author wms
 * @date 2022-05-29
 */
@Controller
@RequestMapping("/business/returnGoods")
public class ReturnGoodsController extends BaseController
{
    private String prefix = "business/returnGoods";

    @Autowired
    private ITMiStockService tMiStockService;

    @Autowired
    private ITCkPickingwavegoodsService tCkPickingwavegoodsService;

    @Autowired
    private ITCkOrderdetailService tCkOrderdetailService;

    @Autowired
    private ITBaseStorageAreaLocationService locationService;

    @RequiresPermissions("business:returnGoods:view")
    @GetMapping()
    public String main(ModelMap mmap)
    {
        // 获取当前用户
        SysUser sysUser = ShiroUtils.getCurrentUser();
        mmap.put("sysUser", sysUser);
        mmap.put("tCkPickingwavegoods", new TCkPickingwavegoods());
        return prefix + "/returnGoods";
    }

    /**
     * 查询退货信息列表
     */
    @RequiresPermissions("business:returnGoods:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TCkPickingwavegoods tCkPickingwavegoods)
    {
        startPage();
        List<TCkPickingwavegoods> list = tCkPickingwavegoodsService.selectTCkPickingwavegoodsList(tCkPickingwavegoods);
        return getDataTable(list);
    }

    /**
     * 添加不合格品出库任务
     */
    @RequiresPermissions("business:returnGoods:add")
    @Log(title = "不合格品退货", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    public AjaxResult addSave(TCkPickingwavegoods tCkPickingwavegoods)
    {
        logger.info("接收到退货请求：{}", JSON.toJSONString(tCkPickingwavegoods));
        try {
            TMiStock tMiStock = new TMiStock();
            tMiStock.setGoodsId(tCkPickingwavegoods.getGoodId());
            tMiStock.setProduclotid(tCkPickingwavegoods.getProduclotid());
            tMiStock.setCtl(tCkPickingwavegoods.getCtl());
            List<TMiStock> list = tMiStockService.selectTMiStockList(tMiStock);
            if (list.size() > 0) {
                TMiStock stock = list.get(0);
                stock.setFlag("1");
                tMiStockService.updateTMiStock(stock);
                logger.info("更新库存状态成功");
                // 填写库存信息
                TCkPickingwavegoods temp = new TCkPickingwavegoods();
                temp.setGoodId(tCkPickingwavegoods.getGoodId());
                temp.setProduclotid(tCkPickingwavegoods.getProduclotid());
                temp.setGoodsName(stock.getGoodsName());
                temp.setMistockNum(stock.getShelvesNum());
                temp.setPickingNum(tCkPickingwavegoods.getPickingNum());
                temp.setLocId(stock.getLocationId());
                temp.setProductionDate(stock.getProductionDate());
                temp.setExpiryDate(stock.getExpirationDate());
                temp.setCtl(stock.getCtl());
                temp.setPickingid(OrderCodeFactory.getOrderCode("TH", ""));
                temp.setPutinId(stock.getPutinId());
                temp.setOutstatus("0");
                temp.setSts("0");
                // 获取用户名
                SysUser sysUser = ShiroUtils.getCurrentUser();
                temp.setUserName(sysUser.getUserName());
                temp.setCreateTime(new Date());
                temp.setOutstand(selectOutStand(stock.getLocationId()));
                temp.setCkType("6");
                logger.info("插入入库任务表");
                if (tCkPickingwavegoodsService.insertTCkPickingwavegoods(temp) < 1) {
                    stock.setFlag("0");
                    tMiStockService.updateTMiStock(stock);
                    return error("生成出库任务失败，请重试");
                }
                return success("出库成功");
            } else {
                return error("无对应库存");
            }

        } catch (Exception e) {
            logger.error("错误：{}", JSON.toJSONString(e));
            return error("错误");
        }
    }

    /**
     * 判断哪个站台
     * @param locationId 库位编号
     * @return 对应的出库站台
     */
    public String selectOutStand(String locationId){
        TBaseStorageAreaLocation location = locationService.selectTBaseStorageAreaLocationByLocationId(locationId);
        if (location.getAbcId().equals("2")) {
            return "D58400";
        } else if (location.getAbcId().equals("1")) {
            return "D58300";
        }
        return "null";
    }

    /**
     * 弹框表格
     */
    @GetMapping("/modalPage")
    public String table()
    {
        return prefix + "/badStockModal";
    }

    /**
     * 查询出库用库存列表
     */
    @RequiresPermissions("business:returnGoods:list")
    @PostMapping("/query")
    @ResponseBody
    public TableDataInfo query(TMiStock tMiStock)
    {
        startPage();
        List<TMiStock> list = tMiStockService.selectStock(tMiStock);
        return getDataTable(list);
    }

    /**
     * 回库
     */
    @Log(title = "返库", businessType = BusinessType.UPDATE)
    @PostMapping("/backStock")
    @ResponseBody
    public AjaxResult backStock(TCkPickingwavegoods tCkPickingwavegoods)
    {
        tCkPickingwavegoods.setOutstatus("4");
        List<TCkPickingwavegoods> waitForBackTaskList = tCkPickingwavegoodsService.selectTCkPickingwavegoodsList(tCkPickingwavegoods);
        if (waitForBackTaskList.size() < 1) {
            return success("0");
        }
        TCkPickingwavegoods backTask = waitForBackTaskList.get(0);
        backTask.setOutstatus("2");
        return toAjax(tCkPickingwavegoodsService.updateGoodsOutResult(backTask));
    }
}
