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

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.base.PartsBaseVO;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.enums.material.PartBaseTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.helper.ResponseHelper;
import com.gree.mall.manager.logic.material.base.PartsBaseLogic;
import com.gree.mall.manager.plus.entity.MaterialConfig;
import com.gree.mall.manager.plus.entity.WebsitPartsBase;
import com.gree.mall.manager.utils.CommonUtils;
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.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@Api(value = "配件基础API", tags ={"配件基础API"} )
@RequestMapping(value = "/parts/base", produces = "application/json; charset=utf-8")
public class PartsBaseController {

    @Resource
    PartsBaseLogic partsBaseLogic;
    @Resource
    RedisLockRegistry redisLockRegistry;

    @ZfireList
    @PostMapping("/list")
    @ApiOperation(value = "配件基础-列表")
    public ResponseHelper<IPage<PartsBaseVO>> page(
            @RequestBody ZfireParamBean zfireParamBean
    ) {
        IPage<PartsBaseVO> page = partsBaseLogic.page(zfireParamBean);
        return ResponseHelper.success(page, new TypeReference<PartsBaseVO>() {});
    }

    @PostMapping("/list/export")
    @ApiOperation("配件基础-导出")
    public void listExport(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //2.查询要导出的内容
        IPage<PartsBaseVO> baseVOIPage = partsBaseLogic.page(zfireParamBean);
        //3.导出
        FieldUtils.exportData(baseVOIPage.getRecords(), zfireParamBean.getExportFields(), request, response);
    }

    @PostMapping("/detail")
    @ApiOperation(value = "配件基础-详情")
    public ResponseHelper<WebsitPartsBase> detail(
            @ApiParam(value = "id", required = true) @RequestParam String id
    ) throws RemoteServiceException {
        return ResponseHelper.success(partsBaseLogic.detail(id));
    }

    @PostMapping("/add")
    @ApiOperation(value = "配件基础-添加")
    public ResponseHelper<WebsitPartsBase> add(
            @RequestBody WebsitPartsBase websitPartsBase
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.PARTS_BASE_MANAGE + websitPartsBase.getType());
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                partsBaseLogic.add(websitPartsBase);
            }
        } catch(Exception e) {
            log.error("【配件基础管理处理】失败",e);
            throw e;
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/edit")
    @ApiOperation(value = "配件基础-编辑")
    public ResponseHelper<WebsitPartsBase> edit(
            @RequestBody WebsitPartsBase websitPartsBase
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.PARTS_BASE_MANAGE + websitPartsBase.getType());
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                partsBaseLogic.edit(websitPartsBase);
            }
        } catch(Exception e) {
            log.error("【配件基础管理处理】失败",e);
            throw e;
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/config")
    @ApiOperation(value = "配件基础-配置")
    public ResponseHelper<MaterialConfig> config() throws Exception {

        MaterialConfig config = partsBaseLogic.config();
        return ResponseHelper.success(config);
    }

    @PostMapping("/config/edit")
    @ApiOperation(value = "配件基础-配置编辑")
    public ResponseHelper configEdit(
            @RequestBody MaterialConfig materialConfig
    ) throws Exception {
        partsBaseLogic.configEdit(materialConfig);
        return ResponseHelper.success();
    }

    @GetMapping("/template/excel")
    @ApiOperation("模板下载")
    public void excelDownload(
            HttpServletResponse response
    ) throws RemoteServiceException, IOException {
        String fileName = "配件基础管理模板.xlsx";
        CommonUtils.downloadFile(fileName,response);
    }

    @PostMapping("/unit/import")
    @ApiOperation("导入单位管理")
    public ResponseHelper importManageUnit(
            MultipartFile file
    ) throws Exception {
        this.commonImportManage(file, PartBaseTypeEnum.UNIT.getKey());
        return ResponseHelper.success();
    }

    private void commonImportManage(MultipartFile file, String type) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.PARTS_BASE_MANAGE + type);
        if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("冻结中，请稍候再操作...");
        }
        try {
            List<Object> objects = ExcelUtils.importExcel(file);
            partsBaseLogic.importManage(objects, type);
        } catch(Exception e) {
            log.error("【配件基础管理处理】失败",e);
            throw e;
        } finally {
            obtain.unlock();
        }
    }
}
