package com.zfire.mall.manager.controller.invoice;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.invoice.InvoiceProjectOrder;
import com.zfire.mall.manager.bean.invoice.InvoiceRequestJson;
import com.zfire.mall.manager.bean.invoice.InvoiceRequestRefund;
import com.zfire.mall.manager.bean.sale.SaleOrderBean;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.helper.ResponseHelper;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.invoice.InvoiceRefundLogic;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * @author CHANGE
 */
@Slf4j
@RestController
@Api(value = "申请退货单", tags = {"申请退货单"})
@RequestMapping(value = "/invoice/refund", produces = "application/json; charset=utf-8")
public class InvoiceRefundController {


    @Autowired
    InvoiceRefundLogic invoiceRefundLogic;

    @Autowired
    RedisLockRegistry redisLockRegistry;

    @Autowired
    CommonLogic commonLogic;



    @ApiOperation(value = "销售出库单列表")
    @GetMapping("/list")
    public ResponseHelper<IPage<SaleOrderBean>> list(
            @ApiParam(required = false, value = "发货申请单") @RequestParam(required = false) String orderNo,
            @ApiParam(required = false, value = "销售出库单号") @RequestParam(required = false) String id,
            @ApiParam(required = false, value = "订单号") @RequestParam(required = false) String mainOrderId,
            @ApiParam(required = false, value = "经销商名称") @RequestParam(required = false) String customerName,
            @ApiParam(required = false, value = "仓库ID") @RequestParam(required = false) String correspondId,
            @ApiParam(required = false, value = "仓库名称") @RequestParam(required = false) String correspondName,
            @ApiParam(required = false, value = "规格型号") @RequestParam(required = false) String specification,
            @ApiParam(required = false, value = "物料名称") @RequestParam(required = false) String materialName,
            @ApiParam(required = false, value = "物料编码") @RequestParam(required = false) String materialNumber,
            @ApiParam(required = false, value = "经销商编号") @RequestParam(required = false) String customerNumber,
            @ApiParam(required = false, value = "单据开始时间") @RequestParam(required = false) String startTime,
            @ApiParam(required = false, value = "单据结束时间") @RequestParam(required = false) String endTime,
            @ApiParam(value = "工程订单号",required = false) @RequestParam(required = false) String enginOrderNo,
            @ApiParam(value = "工程登录号",required = false) @RequestParam(required = false) String  refEnginRecordNo,
            @ApiParam(value = "工程名称",required = false) @RequestParam(required = false) String refProjectName,
            @ApiParam(value = "存货类别",required = false) @RequestParam(required = false) String categoryName,
            @ApiParam(required = false, value = "1 零售销售出库单  2工程销售出库单") @RequestParam(required = false) Integer saleType,
            @ApiParam(value = "页号", required = true) @RequestParam Integer pageNum,
            @ApiParam(value = "页大小", required = true) @RequestParam Integer pageSize
    ) throws Exception {
        IPage<SaleOrderBean> list = invoiceRefundLogic.salesList(categoryName,mainOrderId,enginOrderNo,refEnginRecordNo,refProjectName,saleType,id,orderNo,correspondName,materialNumber, customerName,correspondId,specification,materialName,customerNumber,startTime,endTime, pageNum, pageSize);
        return ResponseHelper.success(list);
    }


    @PostMapping("/add")
    @ApiOperation("退货申请发货单添加")
    public ResponseHelper add(@RequestBody InvoiceRequestRefund invoiceRequest, HttpServletRequest request) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_APPLICATION);
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            invoiceRefundLogic.add(invoiceRequest, request);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/update")
    @ApiOperation("退货申请发货单编辑")
    public ResponseHelper update(@RequestBody InvoiceRequestJson invoiceRequest, HttpServletRequest request) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_APPLICATION + invoiceRequest.getId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            invoiceRefundLogic.update(invoiceRequest, request);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/delete")
    @ApiOperation("退货申请发货单删除")
    public ResponseHelper delete(
            @ApiParam(required = true, value = "申请发货单ID") @RequestParam(required = true) String id
            , HttpServletRequest request) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_APPLICATION + id);
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            invoiceRefundLogic.delete(id);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/giveUp")
    @ApiOperation("退货申请发货单弃审")
    public ResponseHelper giveUp(
            @ApiParam(required = true, value = "申请发货单ID") @RequestParam(required = true) String id
            , HttpServletRequest request) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_APPLICATION + id);
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }

            AdminUserCom adminUser = commonLogic.getAdminUser();
            if(adminUser.getIsCustomer()){
                throw new RemoteServiceException("暂无权限");
            }
            invoiceRefundLogic.giveUp(id);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/submit")
    @ApiOperation("退货申请发货单申请撤回")
    public ResponseHelper submit(
            @ApiParam(required = true, value = "申请发货单ID") @RequestParam(required = true) String id,
            @ApiParam(required = false, value = "单据状态 SAVE=保存 WAIT=待审核 OK=通过 FAIL=不通过 CLOSE=关闭") @RequestParam(required = false) String examineStatus,
            HttpServletRequest request) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_APPLICATION + id);
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            invoiceRefundLogic.submit(id, examineStatus, request);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/approvalInvoice")
    @ApiOperation("退货申请发货单审核")
    public ResponseHelper approvalInvoice(
            @RequestBody InvoiceRequestJson invoiceRequestJson,
            HttpServletRequest request) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_APPLICATION + invoiceRequestJson.getId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            AdminUserCom adminUser = commonLogic.getAdminUser();
            if(adminUser.getIsCustomer()){
                throw new RemoteServiceException("暂无权限");
            }
            invoiceRefundLogic.approvalInvoice(invoiceRequestJson, request);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

}