package cn.estsh.i3plus.ext.mes.apiservice.controller.base;

import cn.estsh.i3plus.ext.mes.api.base.ICommonExtService;
import cn.estsh.i3plus.ext.mes.pojo.model.ExcelImportResultExtModel;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.util.MesConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.impp.framework.base.controller.BaseCommonController;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.util.ImppRedis;
import cn.estsh.impp.framework.boot.util.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @Description :通用功能服务
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-08-26 20:07
 * @Modify:
 **/
@RestController
@Api(description = "通用功能服务")
@RequestMapping(MesConstWords.BASE_CONTROLLER_PATH + "/common/ext")
public class CommonExtController extends BaseCommonController {

    public static final Logger LOGGER = LoggerFactory.getLogger(CommonExtController.class);

    @Autowired
    private ICommonExtService commonExtService;

    @Resource(name = "redisMes")
    private ImppRedis redisMes;

    @PostMapping(value = "/insert-excel")
    @ApiOperation(value = "导入")
    public ResultBean insertDataByExcel(MultipartFile file, Integer module) {

        LOGGER.info("MES二开导入 --- module:{} --- START ---", module);

        boolean falg = true;
        String moduleKey = null;
        if (null == MesExtEnumUtil.MES_EXT_EXCEL.getByValue(module)) {
            falg = false;
        } else {
            moduleKey = AuthUtil.getOrganize().getOrganizeCode() + ":MES_EXT_IMPORT_MODULE:" + MesExtEnumUtil.MES_EXT_EXCEL.getByValue(module).toString();
        }

        try {
            if (!falg) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("该模块暂不支持导入，请联系运维人员")
                        .build();
            }

            if (file == null) {
                falg = false;
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请先上传EXCEL文件")
                        .build();
            }

            if (!doLock(moduleKey)) {
                falg = false;
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("该模块导入已有人正在执行，请稍后再试")
                        .build();
            }

            //导入业务方法
            ExcelImportResultExtModel excelImportResultExtModel = commonExtService.insertDataByExcel(file, module);

            return ResultBean.success((null != excelImportResultExtModel && excelImportResultExtModel.isResult()) ? "导入成功" : "导入失败")
                    .setCode((null != excelImportResultExtModel && excelImportResultExtModel.isResult()) ?
                            ResourceEnumUtil.MESSAGE.SUCCESS.getCode() : ResourceEnumUtil.MESSAGE.FAIL.getCode())
                    .setResultObject(excelImportResultExtModel);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        } finally {
            if (falg) {
               redisMes.deleteKey(moduleKey);
            }
        }
    }

    //todo 后面会调整为分布式锁
    private synchronized boolean doLock(String moduleKey) {
        if (redisMes.hasKey(moduleKey)) {
            return false;
        } else {
            redisMes.putObject(moduleKey, true, MesEnumUtil.EXPIRE_TIME.TEN_MIN.getValue());
            return true;
        }
    }



}
