package com.gree.mall.manager.controller.material.manage;

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.PayDetail;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.material.manage.ImportResultBean;
import com.gree.mall.manager.bean.material.manage.WebsitSalesBean;
import com.gree.mall.manager.bean.material.manage.WebsitSalesVO;
import com.gree.mall.manager.bean.material.stock.WebsitSalesCategoryVO;
import com.gree.mall.manager.bean.material.stock.WebsitSalesGoodsVO;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.enums.material.WebsitGoodsTypeEnum;
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.material.manage.WebsitSalesLogic;
import com.gree.mall.manager.zfire.bean.WebsitSalesParamBean;
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.validation.annotation.Validated;
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 javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@Api(value = "网点销售管理API", tags = {"网点销售管理API"})
@Validated
@RequestMapping(value = "/websit/sales", produces = "application/json; charset=utf-8")
public class WebsitSalesController {

    @Resource
    WebsitSalesLogic websitSalesLogic;
    @Resource
    RedisLockRegistry redisLockRegistry;
    @Resource
    CommonLogic commonLogic;

    @ZfireList
    @PostMapping("/list")
    @ApiOperation(value = "网点销售订单-列表")
    public ResponseHelper<IPage<WebsitSalesVO>> page(
            @RequestBody WebsitSalesParamBean zfireParamBean
    ) {
        IPage<WebsitSalesVO> page = websitSalesLogic.page(zfireParamBean);
        return ResponseHelper.success(page, new TypeReference<WebsitSalesVO>() {
        });
    }

    @PostMapping("/list/export")
    @ApiOperation("网点销售订单-导出")
    public void listExport(
            @RequestBody WebsitSalesParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //2.查询要导出的内容
        IPage<WebsitSalesVO> baseVOIPage = websitSalesLogic.page(zfireParamBean);
        //3.导出
        FieldUtils.exportData(baseVOIPage.getRecords(), zfireParamBean.getExportFields(), request, response);
    }

    @PostMapping("/detail")
    @ApiOperation(value = "网点销售订单-详情")
    public ResponseHelper<List> detail(
            @ApiParam(value = "salesId", required = true) @RequestParam String salesId
    ) throws RemoteServiceException {
        WebsitSalesBean bean = websitSalesLogic.detail(salesId);
        return ResponseHelper.success(bean);
    }

    @PostMapping("/add")
    @ApiOperation(value = "网点销售订单-添加")
    public ResponseHelper add(
            @Valid @RequestBody WebsitSalesBean bean
    ) throws Exception {
        websitSalesLogic.add(bean);
        return ResponseHelper.success();
    }

    @PostMapping("/edit")
    @ApiOperation(value = "网点销售订单-编辑")
    public ResponseHelper edit(
            @Valid @RequestBody WebsitSalesBean bean
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.MATERIAL_SALES + bean.getSalesId());
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                websitSalesLogic.edit(bean);
            }
        } catch (Exception e) {
            log.error("【销售订单处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/submit")
    @ApiOperation(value = "网点销售订单-提交")
    public ResponseHelper submit(
            @ApiParam(value = "单号", required = true) @NotBlank(message = "单号不能为空") @RequestParam String salesId,
            @ApiParam(value = "金额") @RequestParam(required = false) BigDecimal price,
            @ApiParam(value = "凭证") @RequestParam(required = false) String urlPrc,
            @ApiParam(value = "备注") @RequestParam(required = false) String remark
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.MATERIAL_SALES + salesId);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                websitSalesLogic.submit(salesId, price, urlPrc, remark);
            }
        } catch (Exception e) {
            log.error("【销售订单处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("change/cash")
    @ApiOperation(value = "网点销售订单-改为现金支付")
    public ResponseHelper changeCash(
            @ApiParam(value = "单号", required = true) @NotBlank(message = "单号不能为空") @RequestParam String salesId
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.MATERIAL_SALES + salesId);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                websitSalesLogic.changeCash(salesId);
            }
        } catch (Exception e) {
            log.error("【销售订单处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/confirm")
    @ApiOperation(value = "网点销售订单-审核")
    public ResponseHelper confirm(
            @ApiParam(value = "单号", required = true) @NotBlank(message = "单号不能为空") @RequestParam String salesId,
            @ApiParam(value = "仓储id") @RequestParam(required = false) String storageId
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.MATERIAL_SALES + salesId);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                websitSalesLogic.confirm(salesId, storageId);
            }
        } catch (Exception e) {
            log.error("【销售订单处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/exist/stock/category")
    @ApiOperation(value = "网点销售订单-辅材库存分类")
    public ResponseHelper<List<WebsitSalesCategoryVO>> existStockCategory(
            @ApiParam(value = "网点编号", required = true) @RequestParam String websitId,
            @ApiParam(value = "仓库id", required = false) @RequestParam(required = false) String storageId
    ) throws RemoteServiceException {
        List<WebsitSalesCategoryVO> list = websitSalesLogic.existStockCategory(websitId, storageId);
        return ResponseHelper.success(list);
    }

    @PostMapping("/exist/stock/goods")
    @ApiOperation(value = "网点销售订单-辅材库存")
    public ResponseHelper<List<WebsitSalesGoodsVO>> existStockGoods(
            @ApiParam(value = "销售类型") @RequestParam(required = false, defaultValue = "RETAIL") String saleType,
            @ApiParam(value = "网点编号", required = true) @RequestParam String websitId,
            @ApiParam(value = "分类id", required = true) @RequestParam(required = false) String categoryId,
            @ApiParam(value = "商品类型", required = true) @RequestParam WebsitGoodsTypeEnum type,
            @ApiParam(value = "商品名称") @RequestParam(required = false) String goodsName,
            @ApiParam(value = "工程基础资料id") @RequestParam(required = false) String orderEnginBaseId,
            @ApiParam(value = "仓库id") @RequestParam(required = false) String storageId
    ) throws RemoteServiceException {
        List<WebsitSalesGoodsVO> list = websitSalesLogic.existStockGoods(saleType, websitId, categoryId, type, goodsName, orderEnginBaseId, storageId);
        return ResponseHelper.success(list);
    }

    @PostMapping("/exist/stock/goodsList")
    @ApiOperation(value = "网点销售订单-辅材库存列表")
    public ResponseHelper<List<WebsitSalesGoodsVO>> existStockGoodsList(
            @ApiParam(value = "网点编号", required = false) @RequestParam String websitId,
            @ApiParam(value = "分类id", required = false) @RequestParam(required = false) String categoryId,
            @ApiParam(value = "商品类型", required = false) @RequestParam WebsitGoodsTypeEnum type,
            @ApiParam(value = "商品名称") @RequestParam(required = false) String goodsName,
            @ApiParam(value = "规格") @RequestParam(required = false) String goodsSpecification,
            @ApiParam(value = "配件类型") @RequestParam(required = false) String partType,
            @ApiParam(value = "仓库id") @RequestParam(required = false) String storageId
    ) throws RemoteServiceException {
        List<WebsitSalesGoodsVO> list = websitSalesLogic.existStockGoodsList(websitId, categoryId, type, goodsName, goodsSpecification, partType, storageId);
        return ResponseHelper.success(list);
    }

    @PostMapping("/generate/pay/code")
    @ApiOperation(value = "网点销售订单-生成支付二维码")
    public ResponseHelper<PayDetail> pay(
            @ApiParam(value = "salesId单号", required = true) @RequestParam String salesId,
            @ApiParam(value = "支付配置id", required = true) @RequestParam String payConfigId,
            HttpServletRequest request
    ) throws Exception {
        PayDetail detail = websitSalesLogic.pay(salesId, payConfigId, request);
        return ResponseHelper.success(detail);
    }

    @PostMapping("/m/import")
    @ApiOperation(value = "网点销售订单-导入辅材(下载模板:辅材销售订单导入模板.xlsx)")
    public ResponseHelper<String> importMaterialData(
            @RequestPart("file") MultipartFile file
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String companyId = "";
        String batchId = "";
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            companyId = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.MATERIAL_SALES + companyId);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                batchId = websitSalesLogic.importMaterialData(file);
            }
        } catch (Exception e) {
            log.error("【导入辅材销售处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success(batchId);
    }

    @PostMapping("/p/import")
    @ApiOperation(value = "网点销售订单-导入配件(下载模板:配件销售订单导入模板.xlsx)")
    public ResponseHelper<String> importPartsData(
            @RequestPart("file") MultipartFile file
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String companyId = "";
        String batchId = "";
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            companyId = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.MATERIAL_SALES + companyId);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                batchId = websitSalesLogic.importPartsData(file);
            }
        } catch (Exception e) {
            log.error("【导入配件销售处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success(batchId);
    }

    @PostMapping("/query/import/result")
    @ApiOperation(value = "网点销售订单-查询导入处理结果")
    public ResponseHelper<ImportResultBean> queryImportResult(
            @ApiParam(value = "导入回传时的batchId", required = true) @RequestParam String importBatchId
    ) throws RemoteServiceException {
        ImportResultBean bean = websitSalesLogic.queryImportResult(importBatchId);
        return ResponseHelper.success(bean);
    }

    @PostMapping("/test/refund")
    @ApiOperation(value = "网点销售订单-测试退款")
    public ResponseHelper<PayDetail> testRefund(
            @ApiParam(value = "salesId单号", required = true) @RequestParam String salesId,
            HttpServletRequest request
    ) throws Exception {
        websitSalesLogic.testRefund(salesId, request);
        return ResponseHelper.success();
    }
}
