package com.ximai.mes.md.controller;

import cn.hutool.core.bean.BeanUtil;
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.domain.entity.MdItemType;
import com.ximai.common.core.page.TableDataInfo;
import com.ximai.common.enums.BusinessType;
import com.ximai.common.utils.data.StringUtils;
import com.ximai.common.utils.excel.ExcelWriter;
import com.ximai.mes.aspect.BarcodeGen;
import com.ximai.mes.md.domain.MdItem;
import com.ximai.mes.md.dto.MdItemExcelExport;
import com.ximai.mes.md.dto.MdItemExcelImport;
import com.ximai.mes.md.service.IItemTypeService;
import com.ximai.mes.md.service.IMdItemService;
import com.ximai.mes.md.vo.MdItemVo;
import com.ximai.mes.wm.utils.WmBarCodeUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
@RequestMapping("/mes/md/mditem")
public class MdItemController extends BaseController {

    @Autowired
    private IMdItemService mdItemService;

    @Autowired
    private IItemTypeService iItemTypeService;

    @Autowired
    private WmBarCodeUtil barcodeUtil;

    /**
     * 列表查询
     *
     * @param mdItem
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("物料查询")
    public TableDataInfo<MdItemVo> list(MdItem mdItem) {
        startPage();
        List<MdItemVo> list = mdItemService.selectMdItemList(mdItem);
        return getDataTable(list);
    }


    /**
     * 主键查询
     *
     * @param itemId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('mes:md:mditem:query')")
    @GetMapping(value = "/{itemId}")
    @ApiOperation("物料单表查询")
    public AjaxResult<MdItem> getInfo(@PathVariable Long itemId) {
        return AjaxResult.success(mdItemService.selectMdItemById(itemId));
    }

    /**
     * 新增
     *
     * @param mdItem
     * @return
     */
    @PreAuthorize("@ss.hasPermi('mes:md:mditem:add')")
    @Log(title = "物料管理", businessType = BusinessType.INSERT)
    @BarcodeGen(barcodeType = UserConstants.BARCODE_TYPE_ITEM)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody MdItem mdItem) {
        if (UserConstants.NOT_UNIQUE.equals(mdItemService.checkItemCodeUnique(mdItem))) {
            return AjaxResult.error("新增物料" + mdItem.getItemCode() + "失败，物料编码已存在");
        }
        if (UserConstants.NOT_UNIQUE.equals(mdItemService.checkItemNameUnique(mdItem))) {
            return AjaxResult.error("新增物料" + mdItem.getItemCode() + "失败，物料名称已存在");
        }

        MdItemType type = iItemTypeService.selectItemTypeById(mdItem.getItemTypeId());
        if (StringUtils.isNotNull(type)) {
            mdItem.setItemTypeCode(type.getItemTypeCode());
            mdItem.setItemTypeName(type.getItemTypeName());
            mdItem.setItemOrProduct(type.getItemOrProduct());
        }
        mdItem.setCreateBy(getUsername());
        mdItemService.insertMdItem(mdItem);
        barcodeUtil.generateBarCode(UserConstants.BARCODE_TYPE_ITEM, mdItem.getItemId(), mdItem.getItemCode(), mdItem.getItemName());
        return AjaxResult.success(mdItem.getItemId());
    }

    /**
     * 更新
     *
     * @param mdItem
     * @return
     */
    @ApiOperation("修改物料基础信息")
    @PreAuthorize("@ss.hasPermi('mes:md:mditem:edit')")
    @Log(title = "物料管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody MdItem mdItem) {
        if (UserConstants.NOT_UNIQUE.equals(mdItemService.checkItemCodeUnique(mdItem))) {
            return AjaxResult.error("新增物料" + mdItem.getItemCode() + "失败，物料编码已存在");
        }
        if (UserConstants.NOT_UNIQUE.equals(mdItemService.checkItemNameUnique(mdItem))) {
            return AjaxResult.error("新增物料" + mdItem.getItemCode() + "失败，物料名称已存在");
        }
        MdItemType type = iItemTypeService.selectItemTypeById(mdItem.getItemTypeId());
        if (StringUtils.isNotNull(type)) {
            mdItem.setItemTypeCode(type.getItemTypeCode());
            mdItem.setItemTypeName(type.getItemTypeName());
            mdItem.setItemOrProduct(type.getItemOrProduct());
        }
        if (StringUtils.isNotNull(mdItem.getSafeStockFlag()) && "N".equals(mdItem.getSafeStockFlag())) {
            mdItem.setMinStock(0D);
            mdItem.setMaxStock(0D);
        }

        mdItem.setUpdateBy(getUsername());
        return toAjax(mdItemService.updateMdItem(mdItem));
    }

    @PreAuthorize("@ss.hasPermi('mes:md:mditem:remove')")
    @Log(title = "物料管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{itemIds}")
    public AjaxResult remove(@PathVariable Long[] itemIds) {
        return toAjax(mdItemService.deleteByItemIds(itemIds));
    }

    @PreAuthorize("@ss.hasPermi('mes:md:mditem:becomeFormalProduct')")
    @Log(title = "物料管理", businessType = BusinessType.UPDATE)
    @PutMapping("/becomeFormalProduct/{itemIds}")
    public AjaxResult becomeFormalProduct(@PathVariable Long[] itemIds) {
        mdItemService.becomeFormalProduct(itemIds);
        return AjaxResult.success();
    }

    @Log(title = "物料管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('mes:md:mditem:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdItem mdItem) throws IOException {
        List<MdItemVo> list = mdItemService.selectMdItemList(mdItem);
        List<MdItemExcelExport> listExport = BeanUtil.copyToList(list, MdItemExcelExport.class);
        ExcelWriter.write(response, MdItemExcelExport.class, listExport);
    }

    @Log(title = "物料管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('mes:md:mditem:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        mdItemService.importMdItem(file.getInputStream(), updateSupport);
        return AjaxResult.success();
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelWriter.write(response, MdItemExcelImport.class);
    }

    /**
     * 同步ERP数据
     */
    @PreAuthorize("@ss.hasPermi('mes:md:mditem:sync')")
    @Log(title = "物料同步", businessType = BusinessType.SYNC_DATA)
    @PostMapping("/syncData")
    public AjaxResult syncData() {
        mdItemService.syncErpData();
        return AjaxResult.success();
    }
}
