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.material.manage.WebsitWorkSettlementVO;
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.WebsitWorkSettlementLogic;
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.List;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@Api(value = "网点工单结算记录", tags = {"网点工单结算记录"})
@RequestMapping(value = "/parts/work-settlement", produces = "application/json; charset=utf-8")
public class WebsitWorkSettlementController {

    @Resource
    WebsitWorkSettlementLogic websitWorkSettlementLogic;
    @Resource
    RedisLockRegistry redisLockRegistry;

    @ZfireList
    @PostMapping("/list")
    @ApiOperation("网点工单结算记录列表")
    public ResponseHelper<IPage<WebsitWorkSettlementVO>> list(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        IPage<WebsitWorkSettlementVO> partsBeanIPage = websitWorkSettlementLogic.pageList(zfireParamBean);
        return ResponseHelper.success(partsBeanIPage, new TypeReference<WebsitWorkSettlementVO>() {
        });
    }

    @PostMapping("/list/export")
    @ApiOperation("网点工单结算记录列表导出")
    public void listExport(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //2.查询要导出的内容
        IPage<WebsitWorkSettlementVO> stockBeanIPage = websitWorkSettlementLogic.pageList(zfireParamBean);
        //3.导出
        FieldUtils.exportData(stockBeanIPage.getRecords(), zfireParamBean.getExportFields(), request, response);
    }

    @ApiOperation(value = "删除网点工单结算记录")
    @PostMapping("/del")
    public ResponseHelper del(
            @ApiParam(required = true, value = "网点网点工单结算记录id") @RequestParam List<String> ids
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.NEW_REFUND + "import");
        if (!obtain.tryLock()) {
            throw new RemoteServiceException("正在处理导入结算状态数据，请稍后删除");
        }
        try {
            websitWorkSettlementLogic.del(ids);
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }
}
