package com.jsh.erp.controller.stocktaking;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jsh.erp.base.AjaxResult;
import com.jsh.erp.base.BaseController;
import com.jsh.erp.base.TableDataInfo;
import com.jsh.erp.datasource.dto.TaskStocktakingDTO;
import com.jsh.erp.datasource.dto.TaskStocktakingItemDTO;
import com.jsh.erp.datasource.dto.TaskStocktakingItemQueryDTO;
import com.jsh.erp.datasource.dto.TaskStocktakingQueryDTO;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.vo.SpinnerVO;
import com.jsh.erp.datasource.vo.TaskStocktakingVO;
import com.jsh.erp.query.LambdaQueryWrapperX;
import com.jsh.erp.service.*;
import com.jsh.erp.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/stocktaking")
@Api(tags = {"盘点接口"})
public class StocktakingController extends BaseController {

    @Resource
    private TaskStocktakingService taskStocktakingService;

    @Resource
    private UserService userService;

    @Resource
    private TaskStocktakingItemService taskStocktakingItemService;

    @Resource
    private MaterialBatchService materialBatchService;


    @ApiOperation("盘点任务列表")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody TaskStocktakingQueryDTO taskStocktakingQueryDTO){
        startPage();
        List<TaskStocktakingVO> list = taskStocktakingService.listBy(taskStocktakingQueryDTO);
        return getDataTable(list);
    }

    @ApiOperation("新增盘点任务")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody TaskStocktakingDTO taskStocktakingDTO) {
        boolean b = taskStocktakingService.add(taskStocktakingDTO);
        if (!b){
            return AjaxResult.error("创建失败，请联系系统管理员");
        }
        return AjaxResult.success();
    }

    @ApiOperation("负责人下拉列表")
    @GetMapping("/creatorSpinnerList")
    public AjaxResult creatorSpinnerList() {
        List<SpinnerVO> spinnerVOList = userService.creatorSpinnerList();
        return AjaxResult.success(spinnerVOList);
    }

    /**
     * 查询任务详情
     * @param id
     * @return
     */
    @ApiOperation("任务详情")
    @GetMapping("/detail/{id}")
    public AjaxResult detail(@PathVariable("id") Long id) throws Exception{
        return AjaxResult.success(taskStocktakingService.detail(id));
    }

    /**
     * 任务详情-商品列表
     * @param taskStocktakingItemQueryDTO 筛选数据
     * @return
     */
    @ApiOperation("任务详情-商品列表")
    @PostMapping("/detailByItemList")
    public AjaxResult detailByItemList(@RequestBody TaskStocktakingItemQueryDTO taskStocktakingItemQueryDTO) {
        if (ObjectUtil.isEmpty(taskStocktakingItemQueryDTO.getTaskStocktakingId())) {
            return AjaxResult.error("请选择盘点任务");
        }
        return AjaxResult.success(taskStocktakingService.listByTaskStocktakingId(taskStocktakingItemQueryDTO));
    }

    @ApiOperation("任务详情-修改")
    @PostMapping("/detailUpdate")
    public AjaxResult detailUpdate(@RequestBody TaskStocktakingDTO taskStocktakingDTO) {
        boolean b = taskStocktakingService.detailUpdate(taskStocktakingDTO);
        if (!b){
            return AjaxResult.error("修改失败，请联系系统管理员");
        }
        return AjaxResult.success();
    }

    /**
     * 任务详情-商品列表-编辑
     * @return
     */
    @ApiOperation("任务详情-商品-编辑")
    @PostMapping("/itemUpdate")
    public AjaxResult itemUpdate(@RequestBody TaskStocktakingItemDTO taskStocktakingItemDTO) throws Exception {
        User currentUser = userService.getCurrentUser();
        taskStocktakingItemService.update(new UpdateWrapper<TaskStocktakingItem>()
                .set("new_inventory", taskStocktakingItemDTO.getNewInventory())
                .set("new_position", taskStocktakingItemDTO.getNewPosition())
                .set("difference_count", taskStocktakingItemDTO.getDifferenceCount())
                .set("difference_reason", taskStocktakingItemDTO.getDifferenceReason())
                .set("creator", currentUser.getId())
                .set("oper_time", DateUtils.getTime())
                .eq("id", taskStocktakingItemDTO.getId()));
        return AjaxResult.success();
    }

    /**
     * 任务详情-商品-删除
     * @param id 商品ID
     * @return
     */
    @ApiOperation("任务详情-商品-删除")
    @GetMapping("/itemDelete/{id}")
    public AjaxResult itemDelete(@PathVariable("id") Long id) {
        taskStocktakingItemService.update(new UpdateWrapper<TaskStocktakingItem>().set("delete_flag", true).eq("id", id));
        return AjaxResult.success();
    }

    @ApiOperation("取消任务")
    @GetMapping("/taskCancel/{ids}")
    public AjaxResult taskCancel(@PathVariable("ids") Long[] ids) {
        Arrays.asList(ids).forEach(id -> {
            taskStocktakingService.update(new UpdateWrapper<TaskStocktaking>().eq("id", id).set("task_status", "4"));
        });
        return AjaxResult.success();
    }

    @ApiOperation("删除任务")
    @GetMapping("/taskDelete/{ids}")
    public AjaxResult taskDelete(@PathVariable("ids") Long[] ids) {
        Arrays.asList(ids).forEach(id -> {
            taskStocktakingService.update(new UpdateWrapper<TaskStocktaking>().eq("id", id).set("delete_flag", true));
        });
        return AjaxResult.success();
    }

    @ApiOperation("开始任务")
    @GetMapping("/startTask/{id}")
    public AjaxResult startTask(@PathVariable("id") Long id) {
        taskStocktakingService.update(new UpdateWrapper<TaskStocktaking>().set("task_status", 2).eq("id", id));
        return AjaxResult.success();
    }

    @ApiOperation("完成任务")
    @GetMapping("/taskComplete/{id}")
    public AjaxResult taskComplete(@PathVariable("id") Long id) throws Exception {
        User currentUser = userService.getCurrentUser();
        taskStocktakingService.update(new UpdateWrapper<TaskStocktaking>().set("task_status", 3)
                .set("oper_time", new Date())
                .set("oper_by", currentUser.getId())
                .eq("id", id));
        return AjaxResult.success();
    }

    @ApiOperation("任务更新库存")
    @GetMapping("/taskUpdateStock/{ids}")
    public AjaxResult updateStock(@PathVariable("ids") Long[] ids) throws Exception {
        for (Long id : ids) {
            taskStocktakingService.update(new UpdateWrapper<TaskStocktaking>().set("task_status", 5).eq("id", id));
            List<TaskStocktakingItem> list = taskStocktakingItemService.list(new LambdaQueryWrapperX<TaskStocktakingItem>().eq(TaskStocktakingItem::getTaskStocktakingId,id));
            for (TaskStocktakingItem taskStocktakingItem : list) {
                MaterialBatch materialBatch = materialBatchService.getById(taskStocktakingItem.getMaterialItemId());
                materialBatch.setInventory(taskStocktakingItem.getNewInventory());
                materialBatch.setPosition(taskStocktakingItem.getNewPosition());
                materialBatchService.updateInventory("盘点",taskStocktakingItem.getId(),materialBatch);
            }
        }
        return AjaxResult.success();
    }


}
