package com.gree.mall.manager.controller.material.manage;

import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gree.mall.manager.annotation.ZfireList;
import com.gree.mall.manager.bean.material.manage.WebsitMPurchaseBean;
import com.gree.mall.manager.bean.material.manage.WebsitPurchaseBean;
import com.gree.mall.manager.bean.material.manage.WebsitPurchaseOrderVO;
import com.gree.mall.manager.bean.material.manage.WebsitPurchaseVO;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.enums.material.MaterialFlagEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.helper.ResponseHelper;
import com.gree.mall.manager.logic.material.manage.WebsitMPurchaseLogic;
import com.gree.mall.manager.logic.material.manage.WebsitPurchaseLogic;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@Api(value = "网点采购入库API", tags ={"网点采购入库API"} )
@Validated
@RequestMapping(value = "/websit/purchase/in", produces = "application/json; charset=utf-8")
public class WebsitPurchaseController {

    @Resource
    WebsitPurchaseLogic websitPurchaseLogic;
    @Resource
    RedisLockRegistry redisLockRegistry;
    @Resource
    WebsitMPurchaseLogic websitMPurchaseLogic;

    @ZfireList
    @PostMapping("/list")
    @ApiOperation(value = "网点采购入库-列表")
    public ResponseHelper<IPage<WebsitPurchaseVO>> page(
            @RequestBody ZfireParamBean zfireParamBean
    ) {
        IPage<WebsitPurchaseVO> page = websitPurchaseLogic.page(zfireParamBean);
        return ResponseHelper.success(page, new TypeReference<WebsitPurchaseVO>() {});
    }

    @PostMapping("/list/export")
    @ApiOperation("网点采购入库-导出")
    public void listExport(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //2.查询要导出的内容
        IPage<WebsitPurchaseVO> baseVOIPage = websitPurchaseLogic.page(zfireParamBean);
        //3.导出
        FieldUtils.exportData(baseVOIPage.getRecords(), zfireParamBean.getExportFields(), request, response);
    }

    @PostMapping("/detail")
    @ApiOperation(value = "网点采购入库-详情")
    public ResponseHelper<WebsitPurchaseBean> detail(
            @ApiParam(value = "purchaseId", required = true) @RequestParam String purchaseId
    ) throws RemoteServiceException {
        WebsitPurchaseBean bean = websitPurchaseLogic.detail(purchaseId);
        return ResponseHelper.success(bean);
    }

    @PostMapping("/add")
    @ApiOperation(value = "网点采购入库-添加")
    public ResponseHelper add(
            @Valid @RequestBody WebsitPurchaseBean bean
    ) throws Exception {
        websitPurchaseLogic.add(bean);
        return ResponseHelper.success();
    }

    @PostMapping("/edit")
    @ApiOperation(value = "网点采购入库-编辑")
    public ResponseHelper edit(
            @Valid @RequestBody WebsitPurchaseBean bean
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.MATERIAL_PURCHASE + bean.getPurchaseId());
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                websitPurchaseLogic.edit(bean);
            }
        } catch(Exception e) {
            log.error("【采购入库处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/confirm")
    @ApiOperation(value = "网点采购入库-审核")
    public ResponseHelper confirm(
            @ApiParam(value = "单号", required = true) @NotBlank(message = "单号不能为空") @RequestParam String purchaseId,
            @ApiParam(value = "审核结果 OK=通过 FAIL=失败", required = true) @NotNull(message = "审核结果不能为空") @RequestParam MaterialFlagEnum flag,
            @ApiParam(value = "仓储id") @RequestParam(required = false) String storageId
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.MATERIAL_PURCHASE + purchaseId);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                websitPurchaseLogic.confirm(purchaseId, flag, storageId);
            }
        } catch(Exception e) {
            log.error("【采购入库处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/import")
    @ApiOperation(value = "采购入库-导入(下载模板:采购入库模板.xlsx)")
    public ResponseHelper<String> importData(
            @RequestPart("file") MultipartFile file,
            @ApiParam(value = "类型 M=辅材 P=配件", required = true) @RequestParam String goodsType
    ) throws Exception {
        return ResponseHelper.success(websitPurchaseLogic.importData(file, goodsType));
    }

    @ZfireList
    @PostMapping("/order/list")
    @ApiOperation(value = "网点采购订单-列表")
    public ResponseHelper<IPage<WebsitPurchaseOrderVO>> orderPage(
            @RequestBody ZfireParamBean zfireParamBean
    ) {
        IPage<WebsitPurchaseOrderVO> page = websitPurchaseLogic.orderPage(zfireParamBean);
        return ResponseHelper.success(page, new TypeReference<WebsitPurchaseOrderVO>() {});
    }

    @PostMapping("/order/list/export")
    @ApiOperation("网点采购订单-导出")
    public void orderListExport(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //2.查询要导出的内容
        IPage<WebsitPurchaseOrderVO> baseVOIPage = websitPurchaseLogic.orderPage(zfireParamBean);
        //3.导出
        FieldUtils.exportData(baseVOIPage.getRecords(), zfireParamBean.getExportFields(), request, response);
    }

    @PostMapping("/order/detail")
    @ApiOperation(value = "网点采购订单-详情")
    public ResponseHelper<WebsitMPurchaseBean> orderDetail(
            @ApiParam(value = "purchaseId", required = true) @RequestParam String purchaseId
    ) throws RemoteServiceException {
        final WebsitMPurchaseBean bean = websitMPurchaseLogic.detail(purchaseId);
        return ResponseHelper.success(bean);
    }

    @PostMapping("/order/update")
    @ApiOperation(value = "网点采购订单-修改")
    public ResponseHelper update(@RequestBody WebsitMPurchaseBean bean) throws RemoteServiceException {
        websitMPurchaseLogic.orderUpdate(bean);
        return ResponseHelper.success();
    }

    @PostMapping("/order/revoke")
    @ApiOperation(value = "网点采购订单-作废")
    public ResponseHelper orderRevoke(@ApiParam(value = "采购申请单id",required = true) @RequestParam String purchaseId)
            throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_MATERIAL_PURCHASE + purchaseId);
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("系统繁忙，请稍后再尝试");
        }
        try {
            websitMPurchaseLogic.orderRevoke(purchaseId);
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/order/confirm")
    @ApiOperation(value = "网点采购订单-审核")
    public ResponseHelper orderConfirm(@ApiParam(value = "采购申请单id",required = true) @RequestParam String purchaseId)
            throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_MATERIAL_PURCHASE + purchaseId);
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("系统繁忙，请稍后再尝试");
        }
        try {
            websitMPurchaseLogic.orderConfirm(purchaseId);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }
}
