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

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.material.worker.OldRefundManageBean;
import com.gree.mall.manager.bean.material.worker.OldRefundManageVO;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.helper.ResponseHelper;
import com.gree.mall.manager.logic.material.manage.WorkerOldRefundManageLogic;
import com.gree.mall.manager.utils.excel.ExcelUtils;
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 org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@Api(value = "师傅旧件返还管理", tags = {"师傅旧件返还管理"})
@RequestMapping(value = "/worker/old-refund", produces = "application/json; charset=utf-8")
public class OldRefundController {

    @Resource
    WorkerOldRefundManageLogic workerOldRefundManageLogic;
    @Resource
    RedisLockRegistry redisLockRegistry;

    @ZfireList
    @ApiOperation("旧件返还管理列表")
    @PostMapping("/list")
    public ResponseHelper<IPage<OldRefundManageVO>> list(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        IPage<OldRefundManageVO> stockBeanIPage = workerOldRefundManageLogic.pageList(zfireParamBean);
        return ResponseHelper.success(stockBeanIPage, new TypeReference<OldRefundManageVO>() {
        });
    }

    @ApiOperation("旧件返还管理列表导出")
    @PostMapping("/list/export")
    public void listExport(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //2.查询要导出的内容
        IPage<OldRefundManageVO> stockBeanIPage = workerOldRefundManageLogic.pageList(zfireParamBean);
        //3.导出
        FieldUtils.exportData(stockBeanIPage.getRecords(), zfireParamBean.getExportFields(), request, response);
    }


    @ApiOperation(value = "旧件返还管理详情")
    @PostMapping("/detail")
    public ResponseHelper<OldRefundManageBean> detail(
            @ApiParam(value = "申请单号",required = true) @RequestParam String applyNo
    ) throws RemoteServiceException {
        OldRefundManageBean bean = workerOldRefundManageLogic.detail(applyNo);
        return ResponseHelper.success(bean);
    }

    @PostMapping("/refund")
    @ApiOperation(value = "旧件返还")
    public ResponseHelper refund(
            @ApiParam(value = "申请单号",required = true) @RequestParam String applyNo,
            @ApiParam(value = "审批状态",required = true) @RequestParam String flag,
            @ApiParam(value = "审批备注") @RequestParam(required = false) String examineRemark
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.NEW_REFUND + applyNo);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                workerOldRefundManageLogic.refund(applyNo, flag, examineRemark);
            }
        } catch(Exception e) {
            log.error("【旧件返还确认处理】失败",e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/examine")
    @ApiOperation(value = "保外新件转销售审核")
    public ResponseHelper examine(
            @ApiParam(value = "申请单号",required = true) @RequestParam String applyNo,
            @ApiParam(value = "是否优惠价 true=是 false=否",required = true) @RequestParam Boolean isDisc,
            @ApiParam(value = "审批备注") @RequestParam(required = false) String examineRemark
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.NEW_REFUND + applyNo);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                workerOldRefundManageLogic.examine(applyNo, isDisc, examineRemark);
            }
        } catch(Exception e) {
            log.error("【旧件返还确认处理】失败",e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/review")
    @ApiOperation(value = "保外新件转销售复核")
    public ResponseHelper review(
            @ApiParam(value = "申请单号",required = true) @RequestParam String applyNo,
            @ApiParam(value = "是否优惠价 true=是 false=否",required = true) @RequestParam Boolean reviewResult,
            @ApiParam(value = "复核备注") @RequestParam(required = false) String reviewRemark
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.NEW_REFUND + applyNo);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                workerOldRefundManageLogic.review(applyNo, reviewResult, reviewRemark);
            }
        } catch(Exception e) {
            log.error("【旧件返还确认处理】失败",e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }


    @ApiOperation("旧件返还结算状态导入")
    @PostMapping("/import-settlement-state")
    public ResponseHelper importSettlementState(
            @ApiParam(required = true, value = "附件") @RequestPart("file") MultipartFile file,
            @ApiParam(required = true, value = "0-旧件返还 1-保外新件转销售") @RequestParam Integer flag
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.NEW_REFUND + "import");
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("获取导入结算状态锁超时");
        }
        try {
            String s;
            if (flag.compareTo(0) == 0) {
                InputStream inputStream = file.getInputStream();
                s = workerOldRefundManageLogic.importInnerSettlement(inputStream);
            } else {
                List<Object> objects = ExcelUtils.importExcel(file);
                s = workerOldRefundManageLogic.importOutsideSettlement(objects);
            }
            return ResponseHelper.success(s);
        } finally {
            obtain.unlock();
        }
    }

    @PostMapping("/transfer/flag")
    @ApiOperation(value = "旧件返还")
    public ResponseHelper transferFlag(
            @ApiParam(value = "申请单号",required = true) @RequestParam String applyNo
    ) throws Exception {
        Lock importObtain = redisLockRegistry.obtain(Constant.RedisPrefix.NEW_REFUND + "import");
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.NEW_REFUND + applyNo);
        try {
            if (importObtain.tryLock(5, TimeUnit.SECONDS)) {
                if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                    workerOldRefundManageLogic.transferFlag(applyNo);
                }
            }
        } catch(Exception e) {
            log.error("【单据转换标志处理】失败",e);
            throw e;
        } finally {
            if (Objects.nonNull(importObtain)) {
                importObtain.unlock();
            }
            if (Objects.nonNull(obtain)) {
                obtain.unlock();
            }
        }

        return ResponseHelper.success();
    }
}
