package com.gree.mall.manager.controller.goods;

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.admin.AdminUserCom;
import com.gree.mall.manager.bean.goods.*;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.enums.ExamineStatusEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.helper.ResponseHelper;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.goods.GoodsPurchaseRetLogic;
import com.gree.mall.manager.zfire.bean.WebsitGoodsParamBean;
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.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@Api(value = "商品采购退货API", tags ={"商品采购退货API"} )
@RequestMapping(value = "/goods/purchase/ret", produces = "application/json; charset=utf-8")
public class GoodsPurchaseRetController {

    @Resource
    GoodsPurchaseRetLogic goodsPurchaseRetLogic;
    @Resource
    RedisLockRegistry redisLockRegistry;
    @Resource
    CommonLogic commonLogic;

    @ZfireList
    @PostMapping("/list")
    @ApiOperation(value = "商品采购退货-列表")
    public ResponseHelper<IPage<GoodsPurchaseRetVO>> page(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws Exception {
        IPage<GoodsPurchaseRetVO> page = goodsPurchaseRetLogic.page(zfireParamBean);
        return ResponseHelper.success(page, new TypeReference<GoodsPurchaseRetVO>() {});
    }

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

    @ZfireList
    @PostMapping("/item/list")
    @ApiOperation(value = "商品采购退货-明细列表")
    public ResponseHelper<IPage<GoodsPurchaseRetItemVO>> itemPage(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws Exception {
        IPage<GoodsPurchaseRetItemVO> page = goodsPurchaseRetLogic.itemPage(zfireParamBean);
        return ResponseHelper.success(page, new TypeReference<GoodsPurchaseRetItemVO>() {});
    }

    @PostMapping("/item/list/export")
    @ApiOperation("商品采购退货-明细导出")
    public void itemListExport(
            @RequestBody WebsitGoodsParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //2.查询要导出的内容
        IPage<GoodsPurchaseRetItemVO> baseVOIPage = goodsPurchaseRetLogic.itemPage(zfireParamBean);
        //3.导出
        FieldUtils.exportData(baseVOIPage.getRecords(), zfireParamBean.getExportFields(), request, response);
    }

    @ZfireList
    @PostMapping("/code/list")
    @ApiOperation(value = "商品采购退货-条码列表")
    public ResponseHelper<IPage<GoodsPurchaseRetCodeVO>> codePage(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws Exception {
        IPage<GoodsPurchaseRetCodeVO> page = goodsPurchaseRetLogic.codePage(zfireParamBean);
        return ResponseHelper.success(page, new TypeReference<GoodsPurchaseRetCodeVO>() {});
    }

    @PostMapping("/code/list/export")
    @ApiOperation("商品采购退货-条码导出")
    public void codeListExport(
            @RequestBody WebsitGoodsParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //2.查询要导出的内容
        IPage<GoodsPurchaseRetCodeVO> baseVOIPage = goodsPurchaseRetLogic.codePage(zfireParamBean);
        //3.导出
        FieldUtils.exportData(baseVOIPage.getRecords(), zfireParamBean.getExportFields(), request, response);
    }

    @PostMapping("/detail")
    @ApiOperation(value = "商品采购退货-详情")
    public ResponseHelper<GoodsPurchaseRetBean> detail(
            @ApiParam(value = "id",required = true) @RequestParam String id
    ) throws RemoteServiceException {
        GoodsPurchaseRetBean detail = goodsPurchaseRetLogic.detail(id);
        return ResponseHelper.success(detail);
    }

    @PostMapping("get/purchase/detail")
    @ApiOperation(value = "商品采购退货-获取入库单详情")
    public ResponseHelper<GoodsPurchaseBean> getPurchaseDetail(
            @ApiParam(value = "入库单id",required = true) @RequestParam String purchaseId
    ) throws RemoteServiceException {
        GoodsPurchaseBean detail = goodsPurchaseRetLogic.getPurchaseDetail(purchaseId);
        return ResponseHelper.success(detail);
    }

    @PostMapping("/add")
    @ApiOperation(value = "商品采购退货-新增")
    public ResponseHelper add(
            @ApiParam(value = "object",required = true) @RequestBody GoodsPurchaseRetBean bean
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.GOODS_MATERIAL_PURCHASE_RET + bean.getGoodsPurchaseId());
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                goodsPurchaseRetLogic.add(bean);
            }
        } catch(Exception e) {
            log.error("【商品采购退货新增处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success(bean);
    }

    @PostMapping("/update")
    @ApiOperation(value = "商品采购退货-修改")
    public ResponseHelper update(
            @ApiParam(value = "object",required = true) @RequestBody GoodsPurchaseRetBean bean
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String lockKey = "";
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            lockKey = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.GOODS_MATERIAL_PURCHASE_RET + bean.getGoodsPurchaseId());
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                goodsPurchaseRetLogic.update(bean, adminUser);
            }
        } catch(Exception e) {
            log.error("【商品采购退货修改处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/item/import/code")
    @ApiOperation(value = "商品采购退货-商品明细导入条码(下载模板:商品采购条码模板.xlsx)")
    public ResponseHelper itemImportCode(
            @RequestPart("file") MultipartFile file,
            @ApiParam(value = "退货单id",required = true) @RequestParam String id,
            @ApiParam(value = "采购商品明细id",required = true) @RequestParam String purchaseRetItemId
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String lockKey = "";
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            lockKey = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.GOODS_MATERIAL_PURCHASE_RET + id);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                goodsPurchaseRetLogic.itemImportCode(file, id, purchaseRetItemId, adminUser);
            }
        } catch(Exception e) {
            log.error("【商品采购退货商品明细导入条码处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/item/add/code")
    @ApiOperation(value = "商品采购退货-商品明细添加条码")
    public ResponseHelper itemAddCode(
            @ApiParam(value = "object",required = true) @RequestBody GoodsPurchaseRetItemBean itemBean
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String lockKey = "";
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            lockKey = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.GOODS_MATERIAL_PURCHASE_RET + itemBean.getGoodsPurchaseRetId());
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                goodsPurchaseRetLogic.itemAddCode(itemBean, adminUser);
            }
        } catch(Exception e) {
            log.error("【商品采购退货商品明细添加条码处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/item/del/code")
    @ApiOperation(value = "商品采购退货-商品明细删除条码")
    public ResponseHelper itemDelCode(
            @ApiParam(value = "退货单id", required = true) @RequestParam String id,
            @ApiParam(value = "条码记录id", required = true) @RequestParam String codeId
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String lockKey = "";
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            lockKey = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.GOODS_MATERIAL_PURCHASE_RET + id);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                goodsPurchaseRetLogic.itemDelCode(id, codeId, adminUser);
            }
        } catch(Exception e) {
            log.error("【商品采购退货商品明细删除条码处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/submit")
    @ApiOperation(value = "商品采购退货-提交")
    public ResponseHelper submit(
            @ApiParam(value = "id",required = true) @RequestParam String id
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String lockKey = "";
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            lockKey = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.GOODS_MATERIAL_PURCHASE_RET + id);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                goodsPurchaseRetLogic.submit(id);
            }
        } catch(Exception e) {
            log.error("【商品采购退货提交处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/confirm")
    @ApiOperation(value = "商品采购退货-审核")
    public ResponseHelper confirm(
            @ApiParam(value = "id",required = true) @RequestParam String id,
            @ApiParam(value = "FAIL=驳回 OK=审核通过", required = true) @RequestParam ExamineStatusEnum statusEnum
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String lockKey = "";
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            lockKey = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.GOODS_MATERIAL_PURCHASE_RET + id);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                goodsPurchaseRetLogic.confirm(id, statusEnum);
            }
        } catch(Exception e) {
            log.error("【商品采购退货审核处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/del")
    @ApiOperation(value = "商品采购退货-删除")
    public ResponseHelper del(
            @ApiParam(value = "id", required = true) @RequestParam String id
    ) throws Exception {
        goodsPurchaseRetLogic.del(id);
        return ResponseHelper.success();
    }
}
