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.WebsitPurchaseRetBean;
import com.gree.mall.manager.bean.material.manage.WebsitPurchaseRetVO;
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.WebsitPurchaseRetLogic;
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/ret", produces = "application/json; charset=utf-8")
public class WebsitPurchaseRetController {

    @Resource
    WebsitPurchaseRetLogic websitPurchaseRetLogic;
    @Resource
    RedisLockRegistry redisLockRegistry;

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

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

    @PostMapping("/detail")
    @ApiOperation(value = "网点采购退货-详情")
    public ResponseHelper<WebsitPurchaseRetBean> detail(
            @ApiParam(value = "purchaseRetId", required = true) @RequestParam String purchaseRetId
    ) throws RemoteServiceException {
        WebsitPurchaseRetBean bean = websitPurchaseRetLogic.detail(purchaseRetId);
        return ResponseHelper.success(bean);
    }

    @PostMapping("/add")
    @ApiOperation(value = "网点采购退货-添加")
    public ResponseHelper add(
            @Valid @RequestBody WebsitPurchaseRetBean bean
    ) throws Exception {
        websitPurchaseRetLogic.add(bean);
        return ResponseHelper.success();
    }

    @PostMapping("/edit")
    @ApiOperation(value = "网点采购退货-编辑")
    public ResponseHelper edit(
            @Valid @RequestBody WebsitPurchaseRetBean bean
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.MATERIAL_PURCHASE + bean.getPurchaseRetId());
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                websitPurchaseRetLogic.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 purchaseRetId,
            @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 + purchaseRetId);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                websitPurchaseRetLogic.confirm(purchaseRetId, 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(websitPurchaseRetLogic.importData(file, goodsType));
    }
}
