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.material.manage.WebsitPartsSalesBean;
import com.gree.mall.manager.bean.material.manage.WebsitPartsSalesVO;
import com.gree.mall.manager.bean.material.manage.WebsitPartsSalesWVO;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.enums.IsEnum;
import com.gree.mall.manager.enums.material.SourceSalesEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.helper.ResponseHelper;
import com.gree.mall.manager.logic.material.manage.WebsitPartsSalesOrderLogic;
import com.gree.mall.manager.plus.entity.WebsitSalesPayOrder;
import com.gree.mall.manager.plus.entity.WebsitStock;
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 javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@Api(value = "网点配件销售单", tags = {"网点配件销售单"})
@RequestMapping(value = "/parts/sales/order", produces = "application/json; charset=utf-8")
public class WebsitPartsSalesOrderController {

    @Resource
    WebsitPartsSalesOrderLogic websitPartsSalesOrderLogic;

    @Resource
    RedisLockRegistry redisLockRegistry;

    @ApiOperation("配件销售单新增")
    @PostMapping("/add")
    public ResponseHelper<WebsitPartsSalesBean> add(
            @RequestBody WebsitPartsSalesBean partsSalesOrderBean
    ) throws Exception {
        partsSalesOrderBean.setOrderSource(SourceSalesEnum.SELF.getKey());
        partsSalesOrderBean.setIsApply(IsEnum.N.getValue());
        websitPartsSalesOrderLogic.add(partsSalesOrderBean);
        return ResponseHelper.success(partsSalesOrderBean);
    }

    @ApiOperation("配件销售单修改")
    @PostMapping("/update")
    public ResponseHelper<WebsitPartsSalesBean> update(
            @RequestBody WebsitPartsSalesBean partsSalesOrderBean
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.PARTS_SALES + partsSalesOrderBean.getId());
        if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("配件销售单冻结中");
        }
        try {
            websitPartsSalesOrderLogic.update(partsSalesOrderBean);
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success(partsSalesOrderBean);
    }

    @ApiOperation("配件销售单根据id获取")
    @PostMapping("/loadSalesOrderById")
    public ResponseHelper<WebsitPartsSalesBean> loadSalesOrderById(
            @RequestParam String id
    ) throws RemoteServiceException {
        return ResponseHelper.success(websitPartsSalesOrderLogic.loadSalesOrderById(id));
    }

    @ZfireList
    @ApiOperation("配件销售列表")
    @PostMapping("/list")
    public ResponseHelper<IPage<WebsitPartsSalesVO>> list(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        IPage<WebsitPartsSalesVO> partsSalesOrderBeanIPage = websitPartsSalesOrderLogic.list(zfireParamBean);
        return ResponseHelper.success(partsSalesOrderBeanIPage, new TypeReference<WebsitPartsSalesVO>() {
        });
    }

    @ZfireList
    @ApiOperation("网点配件销售列表")
    @PostMapping("/websit/list")
    public ResponseHelper<IPage<WebsitPartsSalesWVO>> websitList(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        IPage<WebsitPartsSalesWVO> partsSalesOrderBeanIPage = websitPartsSalesOrderLogic.websitList(zfireParamBean);
        return ResponseHelper.success(partsSalesOrderBeanIPage, new TypeReference<WebsitPartsSalesWVO>() {
        });
    }

    @ApiOperation(value = "生成支付二维码")
    @PostMapping("/code")
    public ResponseHelper<PayDetail> generateCode(
            @ApiParam(value = "网点销售单id", required = true) @RequestParam String id,
            @ApiParam(value = "网点支付配置id") @RequestParam(required = false) String payConfigId
    ) throws Exception {
        return ResponseHelper.success(websitPartsSalesOrderLogic.generateCode(id, payConfigId));
    }

    @ApiOperation(value = "查询二维码支付状态")
    @GetMapping("/query/pay/status")
    public ResponseHelper<WebsitSalesPayOrder> queryPayStatus(
            @ApiParam(value = "网点编号",required = true) @RequestParam String websitId,
            @ApiParam(value = "单据号",required = true) @RequestParam String id,
            @ApiParam(value = "商户订单号",required = true) @RequestParam String outTradeNo
    ) throws Exception {
        return ResponseHelper.success(websitPartsSalesOrderLogic.queryPayStatus(websitId, id, outTradeNo));
    }

    @ApiOperation("配件销售列表导出")
    @PostMapping("/list/export")
    public void listExport(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //2.查询要导出的内容
        IPage<WebsitPartsSalesVO> partsSalesOrderBeanIPage = websitPartsSalesOrderLogic.list(zfireParamBean);
        //3.导出
        FieldUtils.exportData(partsSalesOrderBeanIPage.getRecords(), zfireParamBean.getExportFields(), request, response);
    }

    @ApiOperation("网点配件销售列表导出")
    @PostMapping("/websit/list/export")
    public void shopListExport(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //2.查询要导出的内容
        IPage<WebsitPartsSalesWVO> partsSalesOrderBeanIPage = websitPartsSalesOrderLogic.websitList(zfireParamBean);
        //3.导出
        FieldUtils.exportData(partsSalesOrderBeanIPage.getRecords(), zfireParamBean.getExportFields(), request, response);
    }

    @ApiOperation("提交订单")
    @PostMapping("/submit")
    public ResponseHelper<WebsitPartsSalesBean> submit(@ApiParam(value = "销售单id", required = true) @RequestParam String id) throws InterruptedException {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.PARTS_SALES + id);
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("销售单冻结中");
        }
        try {
            return ResponseHelper.success(websitPartsSalesOrderLogic.submit(id));
        } catch (Exception e) {
            log.error("【提交订单处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }
    }

    @ApiOperation("现金支付")
    @PostMapping("/change-cash")
    public ResponseHelper<WebsitPartsSalesBean> changeCash(@ApiParam(value = "销售单号", required = true) @RequestParam String id) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.PARTS_SALES + id);
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("销售单冻结中");
        }
        try {
            return ResponseHelper.success(websitPartsSalesOrderLogic.changeCash(id));
        } catch (Exception e) {
            log.error("【提交订单处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }
    }

    @ApiOperation("网点提货")
    @PostMapping("/confirm/delivery")
    public ResponseHelper confirmDelivery(
            @ApiParam(value = "销售单号", required = true) @RequestParam String id,
            @ApiParam(value = "物流单号") @RequestParam(required = false) String logisticsNo
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.PARTS_SALES + id);
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("销售单冻结中");
        }
        try {
            websitPartsSalesOrderLogic.confirmDelivery(id, logisticsNo);
        } catch (Exception e) {
            log.error("【网点提货处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @ApiOperation("删除")
    @PostMapping("/deleteById")
    public ResponseHelper deleteById(
            @ApiParam(value = "销售单id", required = true) @RequestParam String id
    ) throws RemoteServiceException {
        websitPartsSalesOrderLogic.deleteById(id);
        return ResponseHelper.success();
    }

    @ApiOperation("退回-保存状态")
    @PostMapping("/backToSave")
    public ResponseHelper<WebsitPartsSalesBean> backToSave(
            @RequestParam String id
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.PARTS_SALES + id);
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("销售单冻结中");
        }
        try {
            return ResponseHelper.success(websitPartsSalesOrderLogic.backToSave(id));
        } catch (Exception e) {
            log.error("【网点退回保存处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

    }

    @ApiOperation("取消订单")
    @PostMapping("/cancel")
    public ResponseHelper cancel(@RequestParam String id) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.PARTS_SALES + id);
        if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("配件销售单冻结中");
        }
        try {
            websitPartsSalesOrderLogic.cancel(id);
        } catch (Exception e) {
            log.error("【取消订单处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @ApiOperation("获取配件可用库存")
    @PostMapping("/query/parts/new/qty")
    public ResponseHelper<WebsitStock> queryPartsNewQty(
            @ApiParam(required = true, value = "网点编码") @RequestParam String websitId,
            @ApiParam(required = true, value = "配件网点编号") @RequestParam String partsWebsitId,
            @ApiParam(required = true, value = "配件编码") @RequestParam String partsNumber
    ) {
        return ResponseHelper.success(websitPartsSalesOrderLogic.queryPartsNewQty(websitId, partsWebsitId, partsNumber));
    }

    @ApiOperation("转换非申请")
    @PostMapping("/trans/not/apply")
    public ResponseHelper transNotApply(@RequestParam String id) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.PARTS_SALES + id);
        if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("配件销售申请单冻结中");
        }
        try {
            websitPartsSalesOrderLogic.transNotApply(id);
        } catch (Exception e) {
            log.error("【转换非申请处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }


}
