package com.ximai.mes.wm.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximai.common.annotation.Log;
import com.ximai.common.constant.UserConstants;
import com.ximai.common.core.controller.BaseController;
import com.ximai.common.core.domain.AjaxResult;
import com.ximai.common.core.page.TableDataInfo;
import com.ximai.common.enums.BusinessType;
import com.ximai.common.utils.data.StringUtils;
import com.ximai.mes.pro.service.task.IProTaskService;
import com.ximai.mes.wm.domain.*;
import com.ximai.mes.wm.mapper.WmIssueHeaderMapper;
import com.ximai.mes.wm.service.*;
import org.springframework.beans.factory.annotation.Autowired;
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.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 生产领料单头Controller
 *
 * @date 2022-07-14
 */
@RestController
@RequestMapping("/mes/wm/issueheader")
public class WmIssueHeaderController extends BaseController {
    @Autowired
    private IWmIssueHeaderService wmIssueHeaderService;

    @Resource
    private WmIssueHeaderMapper wmIssueHeaderMapper;

    @Autowired
    private IWmIssueLineService wmIssueLineService;

    @Autowired
    private IStorageCoreService storageCoreService;

    @Autowired
    private IWmWarehouseService wmWarehouseService;

    @Autowired
    private IWmStorageLocationService wmStorageLocationService;

    @Autowired
    private IWmStorageAreaService wmStorageAreaService;

    @Autowired
    private IProTaskService proTaskService;


    /**
     * 查询生产领料单头列表
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:issueheader:list')")
    @GetMapping("/list")
    public TableDataInfo list(WmIssueHeader wmIssueHeader) {
        startPage();
        QueryWrapper<WmIssueHeader> wmIssueHeaderQueryWrapper = new QueryWrapper<>();
        wmIssueHeaderQueryWrapper.eq(StringUtils.isNotEmpty(wmIssueHeader.getIssueCode()), "wih.issue_code", wmIssueHeader.getIssueCode());
        wmIssueHeaderQueryWrapper.eq(StringUtils.isNotEmpty(wmIssueHeader.getStatus()), "wih.status", wmIssueHeader.getStatus());
        Map<String, Object> params = wmIssueHeader.getParams();
        if (CollectionUtil.isNotEmpty(params)) {
            Object startKey = params.get("beginPurchaseDate");
            Object endKey = params.get("endPurchaseDate");
            wmIssueHeaderQueryWrapper.between(StringUtils.isNotEmpty(startKey) && StringUtils.isNotEmpty(endKey), "wih.issue_date", startKey, endKey);
        }

        List<WmIssueHeader> list = wmIssueHeaderMapper.selectListByQw(wmIssueHeaderQueryWrapper);
        return getDataTable(list);
    }

    /**
     * 获取生产领料单头详细信息
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:issueheader:query')")
    @GetMapping(value = "/{issueId}")
    public AjaxResult getInfo(@PathVariable("issueId") Long issueId) {
        return AjaxResult.success(wmIssueHeaderService.selectWmIssueHeaderByIssueId(issueId));
    }

    /**
     * 新增生产领料单头
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:issueheader:add')")
    @Log(title = "生产领料单头", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WmIssueHeader wmIssueHeader) {
        if (UserConstants.NOT_UNIQUE.equals(wmIssueHeaderService.checkIssueCodeUnique(wmIssueHeader))) {
            return AjaxResult.error("领料单编号已存在");
        }
        //根据领料单头上的仓库、库区、库位ID设置对应的编号和名称
        if (StringUtils.isNotNull(wmIssueHeader.getWarehouseId())) {
            WmWarehouse warehouse = wmWarehouseService.selectWmWarehouseByWarehouseId(wmIssueHeader.getWarehouseId());
            wmIssueHeader.setWarehouseCode(warehouse.getWarehouseCode());
            wmIssueHeader.setWarehouseName(warehouse.getWarehouseName());
        }

        if (StringUtils.isNotNull(wmIssueHeader.getLocationId())) {
            WmStorageLocation location = wmStorageLocationService.selectWmStorageLocationByLocationId(wmIssueHeader.getLocationId());
            wmIssueHeader.setLocationCode(location.getLocationCode());
            wmIssueHeader.setLocationName(location.getLocationName());
        }

        if (StringUtils.isNotNull(wmIssueHeader.getAreaId())) {
            WmStorageArea area = wmStorageAreaService.selectWmStorageAreaByAreaId(wmIssueHeader.getAreaId());
            wmIssueHeader.setAreaCode(area.getAreaCode());
            wmIssueHeader.setAreaName(area.getAreaName());
        }
        wmIssueHeader.setCreateBy(getUsername());
        return toAjax(wmIssueHeaderService.insertWmIssueHeader(wmIssueHeader));
    }

    /**
     * 修改生产领料单头
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:issueheader:edit')")
    @Log(title = "生产领料单头", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WmIssueHeader wmIssueHeader) {
        if (UserConstants.NOT_UNIQUE.equals(wmIssueHeaderService.checkIssueCodeUnique(wmIssueHeader))) {
            return AjaxResult.error("领料单编号已存在");
        }

        //根据领料单头上的仓库、库区、库位ID设置对应的编号和名称
        if (StringUtils.isNotNull(wmIssueHeader.getWarehouseId())) {
            WmWarehouse warehouse = wmWarehouseService.selectWmWarehouseByWarehouseId(wmIssueHeader.getWarehouseId());
            wmIssueHeader.setWarehouseCode(warehouse.getWarehouseCode());
            wmIssueHeader.setWarehouseName(warehouse.getWarehouseName());
        }

        if (StringUtils.isNotNull(wmIssueHeader.getLocationId())) {
            WmStorageLocation location = wmStorageLocationService.selectWmStorageLocationByLocationId(wmIssueHeader.getLocationId());
            wmIssueHeader.setLocationCode(location.getLocationCode());
            wmIssueHeader.setLocationName(location.getLocationName());
        }

        if (StringUtils.isNotNull(wmIssueHeader.getAreaId())) {
            WmStorageArea area = wmStorageAreaService.selectWmStorageAreaByAreaId(wmIssueHeader.getAreaId());
            wmIssueHeader.setAreaCode(area.getAreaCode());
            wmIssueHeader.setAreaName(area.getAreaName());
        }
        return toAjax(wmIssueHeaderService.updateWmIssueHeader(wmIssueHeader));
    }

    /**
     * 删除生产领料单头
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:issueheader:remove')")
    @Log(title = "生产领料单头", businessType = BusinessType.DELETE)
    @Transactional
    @DeleteMapping("/{issueIds}")
    public AjaxResult remove(@PathVariable Long[] issueIds) {
        for (long issueId : issueIds
        ) {
            WmIssueHeader header = wmIssueHeaderService.selectWmIssueHeaderByIssueId(issueId);
            if (!UserConstants.ORDER_STATUS_PREPARE.equals(header.getStatus())) {
                return AjaxResult.error("只能删除草稿状态的单据!");
            }

            wmIssueLineService.deleteByIssueHeaderId(issueId);
        }

        return toAjax(wmIssueHeaderService.deleteWmIssueHeaderByIssueIds(issueIds));
    }

    /**
     * 执行出库
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:issueheader:edit')")
    @Log(title = "生产领料单头", businessType = BusinessType.UPDATE)
    @Transactional
    @PutMapping("/{issueId}")
    public AjaxResult execute(@PathVariable Long issueId) {
        WmIssueHeader header = wmIssueHeaderService.selectWmIssueHeaderByIssueId(issueId);
        WmIssueLine param = new WmIssueLine();
        param.setIssueId(issueId);
        List<WmIssueLine> lines = wmIssueLineService.selectWmIssueLineList(param);
        if (CollUtil.isEmpty(lines)) {
            return AjaxResult.error("请指定领出的物资");
        }

        // TODO 从SAP执行领料获取仓库数据后再写
//        List<IssueTxBean> beans = wmIssueHeaderService.getTxBeans(issueId);

        //调用库存核心
//        storageCoreService.processIssue(beans);

        //更新单据状态
        header.setStatus(UserConstants.ORDER_STATUS_FINISHED);
//        //  修改任务单状态 -- 生产中
        Long taskId = header.getTaskId();
        proTaskService.setStatus(taskId, UserConstants.ORDER_STATUS_PRODUCIONG);
//        //  修改工单状态 -- 生产中
        wmIssueHeaderService.updateWmIssueHeader(header);
        return AjaxResult.success();
    }


}
