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

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.annotation.ApiNotAuth;
import com.zfire.mall.manager.annotation.Sign;
import com.zfire.mall.manager.annotation.ZfireList;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.front.*;
import com.zfire.mall.manager.bean.invoice.InvoiceApplicationPick;
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.front.CustomerFrontOrderLogic;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.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.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author changelin
 */
@Slf4j
@RestController
@Api(value = "前置仓库", tags = {"前置仓库订单管理"})
@RequestMapping(value = "/customer/frontOrder", produces = "application/json; charset=utf-8")
public class CustomerFrontOrderController {

    @Autowired
    CustomerFrontOrderLogic customerFrontOrderLogic;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    RedisLockRegistry redisLockRegistry;


    @ZfireList
    @PostMapping("/list")
    @ApiOperation("客户销售单列表")
    public ResponseHelper<IPage<CustomerOrderBean>> list(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        IPage<CustomerOrderBean> customerOrderBeanIPage = customerFrontOrderLogic.list(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        return ResponseHelper.success(customerOrderBeanIPage, new TypeReference<CustomerOrderBean>() {});
    }

    @PostMapping("/list/export")
    @ApiOperation("客户销售单导出")
    public void listExport(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        //2.查询要导出的内容
        IPage<CustomerOrderBean> stockBeanIPage = customerFrontOrderLogic.list(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        //3.导出
        FieldUtils.exportData(stockBeanIPage.getRecords(), zfireParam.getExportFields(), request, response);
    }

    @ApiOperation(value = "客户销售单详情")
    @GetMapping("/detail")
    public ResponseHelper<CustomerOrderDetail> detail(
            @ApiParam(required = true, value = "id") @RequestParam(required = true) String id
    ) throws Exception {
        CustomerOrderDetail customerStockDetail = customerFrontOrderLogic.detail(id);
        return ResponseHelper.success(customerStockDetail);
    }


    @PostMapping("/add")
    @ApiOperation("新增客户销售单")
    public ResponseHelper<String> add(@RequestBody CustomerOrderDetail customerOrderDetail, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+adminUser.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            String id = customerFrontOrderLogic.add(customerOrderDetail);
            return ResponseHelper.success(id);
        } finally {
            obtain.unlock();
        }

    }

    @PostMapping("/send")
    @ApiOperation("客户销售订单通知发货")
    public ResponseHelper send(@ApiParam(required = false, value = "销售订单id") @RequestParam(required = false) String id,
                               @ApiParam(required = false, value = "1 已提交 2 待发货 3已发货 4已签收 5已退货") @RequestParam(required = false) Integer status, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+adminUser.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            customerFrontOrderLogic.send(id,status);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/sendRevoke")
    @ApiOperation("客户订单撤销发货")
    public ResponseHelper sendRevoke(@ApiParam(required = false, value = "销售订单id") @RequestParam(required = false) String id,
                                           @ApiParam(required = false, value = "1 已提交") @RequestParam(required = false) Integer status, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+adminUser.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            customerFrontOrderLogic.sendRevoke(id,status);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }


    @PostMapping("/signIn")
    @ApiOperation("客户销售订单签收")
    public ResponseHelper signIn(@ApiParam(required = false, value = "销售订单id") @RequestParam(required = false) String id,
                               @ApiParam(required = false, value = "1 已提交 2 待发货 3已发货 4已签收 5已退货") @RequestParam(required = false) Integer status, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+adminUser.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            customerFrontOrderLogic.signIn(id,status);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }


    @PostMapping("/update")
    @ApiOperation("修改客户销售单")
    public ResponseHelper update(@RequestBody CustomerOrderDetail customerOrderDetail, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+adminUser.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            customerFrontOrderLogic.update(customerOrderDetail);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }


    @PostMapping("/delete")
    @ApiOperation("删除客户销售单")
    public ResponseHelper delete(@ApiParam(required = false, value = "销售订单id") @RequestParam(required = false) String id, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+adminUser.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            customerFrontOrderLogic.delete(id);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @ZfireList
    @PostMapping("/listRefund")
    @ApiOperation("客户退货单")
    public ResponseHelper<IPage<CustomerRefundOrderBean>> listRefund(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        IPage<CustomerRefundOrderBean> customerOrderBeanIPage = customerFrontOrderLogic.listRefund(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        return ResponseHelper.success(customerOrderBeanIPage, new TypeReference<CustomerRefundOrderBean>() {});
    }

    @PostMapping("/list/exportRefund")
    @ApiOperation("客户退货单导出")
    public void exportRefund(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        //2.查询要导出的内容
        IPage<CustomerRefundOrderBean> stockBeanIPage = customerFrontOrderLogic.listRefund(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        //3.导出
        FieldUtils.exportData(stockBeanIPage.getRecords(), zfireParam.getExportFields(), request, response);
    }

    @ApiOperation(value = "客户退货单详情")
    @GetMapping("/detailRefund")
    public ResponseHelper<CustomerOrderRefundDetail> detailRefund(
            @ApiParam(required = true, value = "id") @RequestParam(required = true) String id
    ) throws Exception {
        CustomerOrderRefundDetail customerStockDetail = customerFrontOrderLogic.detailRefund(id);
        return ResponseHelper.success(customerStockDetail);
    }


    @ZfireList
    @PostMapping("/listOrder")
    @ApiOperation("客户销售单引用")
    public ResponseHelper<IPage<CustomerOrderRefundOrder>> listOrder(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        IPage<CustomerOrderRefundOrder> customerOrderBeanIPage = customerFrontOrderLogic.listOrder(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        return ResponseHelper.success(customerOrderBeanIPage, new TypeReference<CustomerOrderRefundOrder>() {});
    }

    @PostMapping("/addRefund")
    @ApiOperation("新增客户退货单")
    public ResponseHelper<String> addRefund(@RequestBody CustomerOrderRefundDetail customerOrderRefundDetail, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+adminUser.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            String orderId = customerFrontOrderLogic.addRefund(customerOrderRefundDetail);
            return ResponseHelper.success(orderId);
        } finally {
            obtain.unlock();
        }

    }

    @PostMapping("/updateRefund")
    @ApiOperation("修改客户退货单")
    public ResponseHelper updateRefund(@RequestBody CustomerOrderRefundDetail customerOrderRefundDetail, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+adminUser.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            customerFrontOrderLogic.updateRefund(customerOrderRefundDetail);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/sendRefund")
    @ApiOperation("客户退货订单通知退货")
    public ResponseHelper sendRefund(@ApiParam(required = false, value = "销售订单id") @RequestParam(required = false) String id,
                                     @ApiParam(required = false, value = "1 已提交 2 已退货") @RequestParam(required = false) Integer status, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+adminUser.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            customerFrontOrderLogic.sendRefund(id,status);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }


    @PostMapping("/sendRefundRevoke")
    @ApiOperation("客户退货订单撤销退货")
    public ResponseHelper sendRevokeRefund(@ApiParam(required = false, value = "销售订单id") @RequestParam(required = false) String id,
                                     @ApiParam(required = false, value = "1 已提交") @RequestParam(required = false) Integer status, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+adminUser.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            customerFrontOrderLogic.sendRevokeRefund(id,status);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }


    @PostMapping("/deleteRefund")
    @ApiOperation("删除客户退货单")
    public ResponseHelper deleteRefund(@ApiParam(required = false, value = "销售订单id") @RequestParam(required = false) String id, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+adminUser.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            customerFrontOrderLogic.deleteRefund(id);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }



    ////////////////////////////嘉贤订单同步/////////////////////



    @ApiOperation(value = "同步客户销售订单列表")
    @PostMapping("/customerOrderPush")
    @ApiNotAuth
    @Sign
    public ResponseHelper<String> customerOrderPush(
            @ApiParam(required = false, value = "更新时间,秒级别") @RequestParam(required = false) String encrypted
    ) throws Exception {
        CustomerOrderPushBean customerOrderBeanIPage = customerFrontOrderLogic.listPush(encrypted);
        String pi = JSONUtil.toJsonStr(customerOrderBeanIPage);
        return ResponseHelper.success(pi);
    }


    @ApiOperation(value = "同步客户销售退货单列表")
    @PostMapping("/orderRefundPush")
    @ApiNotAuth
    @Sign
    public ResponseHelper<String> orderRefundPush(
            @ApiParam(required = false, value = "更新时间,秒级别") @RequestParam(required = false) String encrypted
    ) throws Exception {
        CustomerOrderRefundPushBean customerOrderBeanIPage = customerFrontOrderLogic.orderRefundPush(encrypted);
        String pi = JSONUtil.toJsonStr(customerOrderBeanIPage);
        return ResponseHelper.success(pi);
    }


    @ApiOperation(value = "同步库存调整列表")
    @PostMapping("/customerStockAcc")
    @ApiNotAuth
    @Sign
    public ResponseHelper<String> customerStockAcc(
            @ApiParam(required = false, value = "更新时间,秒级别") @RequestParam(required = false) String encrypted
    ) throws Exception {
        CustomerStockOrderPushBean customerOrderBeanIPage = customerFrontOrderLogic.customerStockAcc(encrypted);
        String pi = JSONUtil.toJsonStr(customerOrderBeanIPage);
        return ResponseHelper.success(pi);
    }



    ////////////////////////////////物流接口 /////////////////////////

    @ZfireList
    @PostMapping("/orderTrackList")
    @ApiOperation("物流信息获取")
    public ResponseHelper<IPage<OrderTrackTocBean>> orderTrackList(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        IPage<OrderTrackTocBean> customerOrderBeanIPage = customerFrontOrderLogic.orderTrackList(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        return ResponseHelper.success(customerOrderBeanIPage, new TypeReference<OrderTrackTocBean>() {});
    }

    @PostMapping("/orderTrackList/export")
    @ApiOperation("物流信息获取导出")
    public void orderTrackListExport(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        //2.查询要导出的内容
        IPage<OrderTrackTocBean> stockBeanIPage = customerFrontOrderLogic.orderTrackList(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        //3.导出
        FieldUtils.exportData(stockBeanIPage.getRecords(), zfireParam.getExportFields(), request, response);
    }

}
