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

import cn.hutool.core.lang.TypeReference;
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.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.CustomerFrontLogic;
import com.zfire.mall.manager.utils.CommonUtils;
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 org.springframework.web.multipart.MultipartFile;

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

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

    @Autowired
    CustomerFrontLogic customerFrontLogic;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    RedisLockRegistry redisLockRegistry;


    @ZfireList
    @PostMapping("/list")
    @ApiOperation("经销商仓库库存列表")
    public ResponseHelper<IPage<CustomerStockBean>> list(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        IPage<CustomerStockBean> stockBeanIPage = customerFrontLogic.stockList(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        return ResponseHelper.success(stockBeanIPage, new TypeReference<CustomerStockBean>() {});
    }

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


    @GetMapping("/kunCunDownload")
    @ApiOperation("库存初始化下载模板")
    public void kunCunDownload(
            HttpServletResponse response
    ) throws IOException {
        CommonUtils.downloadFile("kucunchushih.xlsx",response);
    }


    @PostMapping("/kunCunImportData")
    @ApiOperation("导入库存初始化")
    public ResponseHelper kunCunImportData(
            MultipartFile file
    ) throws IOException {
        customerFrontLogic.kunCunImportData(file);
        return ResponseHelper.success();
    }

    @PostMapping("/kunCunTiaoImportData")
    @ApiOperation("导入库存调整")
    public ResponseHelper kunCunTiaoImportData(
            MultipartFile file
    ) throws IOException {
        customerFrontLogic.kunCunTiaoImportData(file);
        return ResponseHelper.success();
    }



    @ZfireList
    @PostMapping("/listCustomer")
    @ApiOperation("经销商仓库库存列表(商家)")
    public ResponseHelper<IPage<CustomerStockBean>> listCustomer(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        IPage<CustomerStockBean> stockBeanIPage = customerFrontLogic.stockList(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        return ResponseHelper.success(stockBeanIPage, new TypeReference<CustomerStockBean>() {});
    }

    @PostMapping("/list/exportCustomer")
    @ApiOperation("经销商仓库库存导出（商家）")
    public void exportCustomer(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        //2.查询要导出的内容
        IPage<CustomerStockBean> stockBeanIPage = customerFrontLogic.stockList(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        //3.导出
        FieldUtils.exportData(stockBeanIPage.getRecords(), zfireParam.getExportFields(), request, response);
    }



    @ZfireList
    @PostMapping("/listCustomerAcc")
    @ApiOperation("库存调整管理")
    public ResponseHelper<IPage<CustomerStockOrderBean>> listCustomerAcc(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        IPage<CustomerStockOrderBean> stockBeanIPage = customerFrontLogic.listCustomerAcc(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        return ResponseHelper.success(stockBeanIPage, new TypeReference<CustomerStockOrderBean>() {});
    }

    @PostMapping("/list/exportCustomerStockOrderBean")
    @ApiOperation("库存调整管理导出")
    public void exportCustomerStockOrderBean(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        //2.查询要导出的内容
        IPage<CustomerStockOrderBean> stockBeanIPage = customerFrontLogic.listCustomerAcc(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        //3.导出
        FieldUtils.exportData(stockBeanIPage.getRecords(), zfireParam.getExportFields(), request, response);
    }


    @PostMapping("/addCustomerStockOrder")
    @ApiOperation("新增库存调整")
    public ResponseHelper add(@RequestBody CustomerStockInsert customerStockInsert, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+customerStockInsert.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            customerFrontLogic.add(customerStockInsert);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/updateCustomerStockOrder")
    @ApiOperation("修改库存调整")
    public ResponseHelper update(@RequestBody CustomerStockInsert customerStockInsert, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+customerStockInsert.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            customerFrontLogic.update(customerStockInsert);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/deleteCustomerStockOrder")
    @ApiOperation("删除库存调整")
    public ResponseHelper deleteCustomerStockOrder(@RequestBody CustomerStockInsert customerStockInsert, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+customerStockInsert.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            customerFrontLogic.deleteCustomerStockOrder(customerStockInsert);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/approvalCustomerStockOrder")
    @ApiOperation("审批库存调整")
    public ResponseHelper approvalCustomerStockOrder(@RequestBody CustomerStockInsert customerStockInsert, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_CUSTOMER_FRONT+customerStockInsert.getCustomerId());
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            customerFrontLogic.approvalCustomerStockOrder(customerStockInsert);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }



    @ApiOperation(value = "库存调整详情")
    @GetMapping("/detail")
    public ResponseHelper<CustomerStockDetail> detail(
            @ApiParam(required = true, value = "id") @RequestParam(required = true) String id
    ) throws Exception {
        CustomerStockDetail customerStockDetail = customerFrontLogic.detail(id);
        return ResponseHelper.success(customerStockDetail);
    }

    @ZfireList
    @PostMapping("/listStockAcc")
    @ApiOperation("商家库存三级账列表")
    public ResponseHelper<IPage<CustomerStockAccBean>> listStockAcc(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        IPage<CustomerStockAccBean> stockBeanIPage = customerFrontLogic.listStockAcc(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        return ResponseHelper.success(stockBeanIPage, new TypeReference<CustomerStockAccBean>() {});
    }

    @PostMapping("/listStockAcc/exportListStockAcc")
    @ApiOperation("商家库存三级账导出")
    public void exportListStockAcc(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        //2.查询要导出的内容
        IPage<CustomerStockAccBean> stockBeanIPage = customerFrontLogic.listStockAcc(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        //3.导出
        FieldUtils.exportData(stockBeanIPage.getRecords(), zfireParam.getExportFields(), request, response);
    }


    @ApiOperation(value = "同步成功返回")
    @PostMapping("/syncStatus")
    @ApiNotAuth
    @Sign
    public ResponseHelper<String> syncStatus(
            @RequestBody SyncStatusBean syncStatusBean
    ) throws Exception {

        customerFrontLogic.syncStatus(syncStatusBean);
        return ResponseHelper.success();
    }


    @GetMapping("/download")
    @ApiOperation("库存调整下载模板")
    public void download(
            HttpServletResponse response
    ) throws IOException {
        CommonUtils.downloadFile("kctz.xlsx",response);
    }


    @PostMapping("/importData")
    @ApiOperation("导入商家库存")
    public ResponseHelper importData(
            MultipartFile file
    ) throws IOException {
        customerFrontLogic.importData(file);
        return ResponseHelper.success();
    }




    @ApiOperation(value = "同步物流订单")
    @PostMapping("/syncOrderTrack")
    @ApiNotAuth
    @Sign
    public ResponseHelper<String> syncOrderTrack(
            @RequestBody SyncOrderTrack syncStatusBean
    ) throws Exception {

        customerFrontLogic.syncOrderTrack(syncStatusBean);
        return ResponseHelper.success();
    }


}
