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

import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.GoodsPurchaseLogic;
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", produces = "application/json; charset=utf-8")
public class GoodsPurchaseController {

    @Resource
    GoodsPurchaseLogic goodsPurchaseLogic;
    @Resource
    RedisLockRegistry redisLockRegistry;
    @Resource
    CommonLogic commonLogic;

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

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

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

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

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

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

    @PostMapping("/detail")
    @ApiOperation(value = "商品采购入库-详情")
    public ResponseHelper<GoodsPurchaseBean> detail(
            @ApiParam(value = "id",required = true) @RequestParam String id,
            @ApiParam(value = "是否查当前库存true=是 false=否") @RequestParam(required = false) Boolean isQuery
    ) throws RemoteServiceException {
        GoodsPurchaseBean detail = goodsPurchaseLogic.detail(id, isQuery);
        return ResponseHelper.success(detail);
    }

    @PostMapping("/add")
    @ApiOperation(value = "商品采购入库-新增")
    public ResponseHelper add(
            @ApiParam(value = "object",required = true) @RequestBody GoodsPurchaseBean bean
    ) throws RemoteServiceException {
        goodsPurchaseLogic.add(bean);
        return ResponseHelper.success(bean);
    }

    @PostMapping("/update")
    @ApiOperation(value = "商品采购入库-修改")
    public ResponseHelper update(
            @ApiParam(value = "object",required = true) @RequestBody GoodsPurchaseBean goodsBean
    ) 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 + lockKey);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                goodsPurchaseLogic.update(goodsBean, 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 purchaseItemId
    ) 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 + lockKey);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                goodsPurchaseLogic.itemImportCode(file, purchaseItemId, 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 GoodsPurchaseItemBean 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 + lockKey);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                goodsPurchaseLogic.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 + lockKey);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                goodsPurchaseLogic.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 RemoteServiceException, InterruptedException {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String lockKey = "";
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            lockKey = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.GOODS_MATERIAL_PURCHASE + lockKey);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                goodsPurchaseLogic.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 RemoteServiceException, InterruptedException {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String lockKey = "";
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            lockKey = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.GOODS_MATERIAL_PURCHASE + lockKey);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                goodsPurchaseLogic.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 {
        goodsPurchaseLogic.del(id);
        return ResponseHelper.success();
    }
}
