package com.liquidnet.service.adam.controller.web.company;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.liquidnet.common.exception.constant.ErrorCode;
import com.liquidnet.common.swagger.config.SwaggerApiVersion;
import com.liquidnet.service.ResponseDto;
import com.liquidnet.service.adam.constant.AdamComConstants;
import com.liquidnet.service.adam.config.swagger.AdamSwaggerApiVersionConstant;
import com.liquidnet.service.adam.common.AdamErrorCode;
import com.liquidnet.service.adam.dto.*;
import com.liquidnet.service.adam.dto.base.AdamCurrentUser;
import com.liquidnet.service.adam.dto.base.AdamResultDto;
import com.liquidnet.service.adam.entity.AdamComInfo;
import com.liquidnet.service.adam.interceptor.annotation.RequiresPermissions;
import com.liquidnet.service.adam.service.IAdamComActivateService;
import com.liquidnet.service.adam.service.IAdamComInfoService;
import com.liquidnet.service.adam.service.IAdamSysCountryService;
import com.liquidnet.service.adam.util.AdamRedisLockUtil;
import com.liquidnet.service.adam.util.CurrentUserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 公司信息 前端控制器
 * </p>
 *
 * @author liquidnet
 * @since 2020-09-16
 */
@Api(tags = "web com activate")
@Slf4j
@RestController
@RequestMapping("/adam-com-activate")
public class AdamComActivateController {
    @Autowired
    private IAdamComInfoService adamComInfoService;

    @Autowired
    private IAdamComActivateService adamComActivateService;


    @RequiresPermissions("096D7A14")
    @ApiOperation(value = "active Company Information")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_0)
    @PostMapping(value = {"/active_s1", "/active_s1/{temp}"})
    public ResponseDto activeCompanyInformation(HttpServletRequest request,
                                                @ModelAttribute AdamComInfoParam adamComInfoParam,
                                                @PathVariable(required = false) String temp) {
        log.info("active_s1,temp=[{}],AdamComInfoParam=[{}]", temp, JSON.toJSONString(adamComInfoParam, SerializerFeature.WriteMapNullValue));
        try {
            AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
            String comId = currentUser.getComId();
            boolean b = AdamRedisLockUtil.tryLock("com_active_s1" + comId, 0, 3);
            if (!b) {
                return ResponseDto.failure(ErrorCode.REQUEST_REPEATED_SUBMISSION);
            }
            adamComInfoParam.setId(comId);
            AdamResultDto<AdamComInfoDto> adamResultDto = adamComActivateService.activeCompanyInformation(temp, adamComInfoParam);
            return AdamResultDto.getResponseDto(adamResultDto);
        } catch (Exception e) {
            log.error("active_s1异常", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "active Business Question")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_0)
    @PostMapping(value = {"/active_s2", "/active_s2/{temp}"})
    public ResponseDto activebusinessQuestion(HttpServletRequest request,
                                              @RequestBody List<AdamComQuestionDto> businessQuestionList,
                                              @PathVariable(required = false) String temp) {
        log.info("active_s2,temp=[{}],businessQuestionList=[{}]", temp, JSON.toJSONString(businessQuestionList, SerializerFeature.WriteMapNullValue));
        try {
            AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
            String comId = currentUser.getComId();
            boolean b = AdamRedisLockUtil.tryLock("com_active_s2" + comId, 0, 3);
            if (!b) {
                return ResponseDto.failure(ErrorCode.REQUEST_REPEATED_SUBMISSION);
            }
            AdamComInfoExtendParam param = new AdamComInfoExtendParam();
            param.setId(comId);
            param.setBusinessQuestion(JSON.toJSONString(businessQuestionList));
            AdamResultDto<AdamComInfoExtendDto> adamResultDto = adamComActivateService.activebusinessQuestion(temp, param);
            return AdamResultDto.getResponseDto(adamResultDto);
        } catch (Exception e) {
            log.error("active_s2异常", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }

    }

    @ApiOperation(value = "active Legal Person")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_0)
    @PostMapping(value = {"/active_s3", "/active_s3/{temp}"})
    public ResponseDto activeLegalPerson(HttpServletRequest request,
                                         @ModelAttribute AdamComLegalPersonParam adamComLegalPersonParam,
                                         @PathVariable(required = false) String temp) {
        log.info("active_s3,temp=[{}],adamComLegalPersonParam=[{}]", temp, JSON.toJSONString(adamComLegalPersonParam, SerializerFeature.WriteMapNullValue));
        try {
            AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
            String comId = currentUser.getComId();
            boolean b = AdamRedisLockUtil.tryLock("com_active_s3" + comId, 0, 3);
            if (!b) {
                return ResponseDto.failure(ErrorCode.REQUEST_REPEATED_SUBMISSION);
            }
            adamComLegalPersonParam.setComId(comId);
            AdamResultDto<AdamComLegalPersonDto> adamResultDto = adamComActivateService.activeLegalPerson(temp, adamComLegalPersonParam);
            return AdamResultDto.getResponseDto(adamResultDto);
        } catch (Exception e) {
            log.error("active_s3异常", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }

    }

    @ApiOperation(value = "active Shareholders Information")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_0)
    @PostMapping(value = {"/active_s4", "/active_s4/{temp}"})
    public ResponseDto activeShareholder(HttpServletRequest request,
                                         @RequestBody List<AdamComShareholderParam> adamComShareholderParamList,
                                         @PathVariable(required = false) String temp) {
        log.info("active_s4,temp=[{}],adamComShareholderParamList=[{}]", temp, JSON.toJSONString(adamComShareholderParamList, SerializerFeature.WriteMapNullValue));
        try {
            AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
            String comId = currentUser.getComId();
            boolean b = AdamRedisLockUtil.tryLock("com_active_s4" + comId, 0, 3);
            if (!b) {
                return ResponseDto.failure(ErrorCode.REQUEST_REPEATED_SUBMISSION);
            }
            AdamResultDto<AdamComShareholderDto> adamResultDto = adamComActivateService.activeShareholder(temp, comId, adamComShareholderParamList);
            return AdamResultDto.getResponseDto(adamResultDto);

        } catch (Exception e) {
            log.error("active_s4异常", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }

    }

    @ApiOperation(value = "active Financial Question")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_0)
    @PostMapping(value = {"/active_s5", "/active_s5/{temp}"})
    public ResponseDto activeFinancialQuestion(HttpServletRequest request,
                                               @RequestBody List<AdamComQuestionDto> financialQuestionList,
                                               @PathVariable(required = false) String temp) {
        log.info("active_s5,temp=[{}],financialQuestionList=[{}]", temp, JSON.toJSONString(financialQuestionList, SerializerFeature.WriteMapNullValue));
        try {
            AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
            String comId = currentUser.getComId();
            boolean b = AdamRedisLockUtil.tryLock("com_active_s5" + comId, 0, 3);
            if (!b) {
                return ResponseDto.failure(ErrorCode.REQUEST_REPEATED_SUBMISSION);
            }
            AdamComInfoExtendParam param = new AdamComInfoExtendParam();
            param.setId(comId);
            param.setFinancialQuestion(JSON.toJSONString(financialQuestionList));
            AdamResultDto<AdamComInfoExtendDto> adamResultDto = adamComActivateService.activeFinancialQuestion(temp, param);
            return AdamResultDto.getResponseDto(adamResultDto);
        } catch (Exception e) {
            log.error("active_s5异常", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }

    }

    @ApiOperation(value = "active back")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_0)
    @PostMapping(value = "/back")
    public ResponseDto activeBack(HttpServletRequest request) {
        try {
            AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
            String comId = currentUser.getComId();
            boolean b = AdamRedisLockUtil.tryLock("com_active_back" + comId, 0, 3);
            if (!b) {
                return ResponseDto.failure(ErrorCode.REQUEST_REPEATED_SUBMISSION);
            }

            AdamComInfo adamComInfo = adamComInfoService.selectById(comId);
            log.info("active back,state=[{}],adamComInfo=[{}]", adamComInfo.getState(), JSON.toJSONString(adamComInfo, SerializerFeature.WriteMapNullValue));
            String comState = adamComInfo.getState();
            AdamComInfoParam updateCom = new AdamComInfoParam();
            updateCom.setId(comId);
            if (AdamComConstants.ComStateEnum.S2.getCode().equals(comState)) {
                updateCom.setState(AdamComConstants.ComStateEnum.S1.getCode());
            } else if (AdamComConstants.ComStateEnum.S3.getCode().equals(comState)) {
                updateCom.setState(AdamComConstants.ComStateEnum.S2.getCode());
            } else if (AdamComConstants.ComStateEnum.S4.getCode().equals(comState)) {
                updateCom.setState(AdamComConstants.ComStateEnum.S3.getCode());
            } else if (AdamComConstants.ComStateEnum.S5.getCode().equals(comState)) {
                updateCom.setState(AdamComConstants.ComStateEnum.S4.getCode());
            } else if (AdamComConstants.ComStateEnum.S6.getCode().equals(comState)) {
                updateCom.setState(AdamComConstants.ComStateEnum.S5.getCode());
            } else {
                return ResponseDto.failure(AdamErrorCode.ADAM001_ILLEGAL_OPERATION.getCode(), AdamErrorCode.ADAM001_ILLEGAL_OPERATION.getVal());
            }

            adamComInfoService.updateById(updateCom);

        } catch (Exception e) {
            log.error("active back异常", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }
        return ResponseDto.success();
    }

    @ApiOperation(value = "active final submit")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_0)
    @PostMapping(value = "/final_submit")
    public ResponseDto activeFinalSubmit(HttpServletRequest request) {
        try {
            AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
            String comId = currentUser.getComId();
            boolean b = AdamRedisLockUtil.tryLock("com_active_final_submit" + comId, 0, 3);
            if (!b) {
                return ResponseDto.failure(ErrorCode.REQUEST_REPEATED_SUBMISSION);
            }
            AdamComInfo adamComInfo = adamComInfoService.selectById(comId);
            log.info("active final submit,adamComInfo=[{}]", JSON.toJSONString(adamComInfo, SerializerFeature.WriteMapNullValue));
            AdamComInfoParam updateCom = new AdamComInfoParam();
            updateCom.setId(comId);
            // todo-lichen 测试
//            updateCom.setState(AdamComConstants.ComStateEnum.S7.getCode());
            updateCom.setState(AdamComConstants.ComStateEnum.S8.getCode());
            adamComInfoService.updateById(updateCom);

        } catch (Exception e) {
            log.error("active final submit异常", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }
        return ResponseDto.success();
    }

}
