package com.qmth.themis.admin.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qmth.themis.business.annotation.ApiJsonObject;
import com.qmth.themis.business.annotation.ApiJsonProperty;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.dto.response.TBOrgDto;
import com.qmth.themis.business.entity.TBOrg;
import com.qmth.themis.business.entity.TBUser;
import com.qmth.themis.business.enums.FieldUniqueEnum;
import com.qmth.themis.business.service.ThemisCacheService;
import com.qmth.themis.business.service.TBOrgService;
import com.qmth.themis.business.util.ServletUtil;
import com.qmth.themis.business.util.UidUtil;
import com.qmth.themis.common.enums.ExceptionResultEnum;
import com.qmth.themis.common.exception.BusinessException;
import com.qmth.themis.common.util.Result;
import com.qmth.themis.common.util.ResultUtil;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 机构 前端控制器
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/6/25
 */
@Api(tags = "机构Controller")
@RestController
@RequestMapping(SystemConstant.PREFIX_URL_ADMIN + "/org")
@Validated
public class TBOrgController {

    private final static Logger log = LoggerFactory.getLogger(TBOrgController.class);

    @Resource
    TBOrgService tbOrgService;

    @Resource
    UidUtil uidUtil;

    @Resource
    ThemisCacheService themisCacheService;

    @ApiOperation(value = "机构查询分页接口")
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "机构信息", response = TBOrgDto.class)})
    public Result queryByPage(@ApiParam(value = "机构代码", required = false) @RequestParam(required = false) String code,
                              @ApiParam(value = "机构名称", required = false) @RequestParam(required = false) String name,
                              @ApiParam(value = "是否启用", required = false) @RequestParam(required = false) Integer enable,
                              @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) int pageNumber,
                              @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) int pageSize) {
        return ResultUtil.ok(tbOrgService.queryByPage(new Page<>(pageNumber, pageSize), code, name, enable));
    }

    @ApiOperation(value = "机构新增/编辑接口")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @Transactional
    @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
    public Result save(@ApiParam(value = "机构信息", required = true) @RequestBody TBOrg tbOrg) {
        if (Objects.isNull(tbOrg)) {
            throw new BusinessException(ExceptionResultEnum.ORG_INFO_IS_NULL);
        }
        if (Objects.isNull(tbOrg.getCode()) || Objects.equals(tbOrg.getCode(), "")) {
            throw new BusinessException(ExceptionResultEnum.ORG_CODE_IS_NULL);
        }
        if (Objects.isNull(tbOrg.getName()) || Objects.equals(tbOrg.getName(), "")) {
            throw new BusinessException(ExceptionResultEnum.ORG_NAME_IS_NULL);
        }
        if (Objects.nonNull(tbOrg.getCode()) && Objects.equals(tbOrg.getCode().toUpperCase(), SystemConstant.ADMIN)) {
            throw new BusinessException("admin为超级管理员专属编码,请重新输入");
        }
        try {
            TBUser tbUser = (TBUser) ServletUtil.getRequestAccount();
            if (Objects.isNull(tbOrg.getId())) {
                tbOrg.setId(uidUtil.getId());
                tbOrg.setCreateId(tbUser.getId());
            } else {
                tbOrg.setUpdateId(tbUser.getId());
            }
            tbOrgService.saveOrUpdate(tbOrg);
            themisCacheService.updateOrgCache(tbOrg.getId());
            themisCacheService.updateOrgCodeCache(tbOrg.getCode());
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            if (e instanceof DuplicateKeyException) {
                String errorColumn = e.getCause().toString();
                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length())
                        .replaceAll("'", "");
                throw new BusinessException(FieldUniqueEnum.convertToCode(columnStr) + "数据不允许重复插入");
            } else if (e instanceof BusinessException) {
                throw new BusinessException(e.getMessage());
            } else {
                throw new RuntimeException(e);
            }
        }
        return ResultUtil.ok(true);
    }

    @ApiOperation(value = "机构停用/启用接口")
    @RequestMapping(value = "/enable", method = RequestMethod.POST)
    @Transactional
    @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
    public Result enableOrg(@ApiJsonObject(name = "enableOrg", value = {
            @ApiJsonProperty(key = "id", type = "long", example = "1", description = "机构id"),
            @ApiJsonProperty(key = "enable", type = "int", example = "1", description = "停用/启用")}) @ApiParam(value = "用户信息", required = true) @RequestBody Map<String, Object> user) {
        if (Objects.isNull(user.get(SystemConstant.ID)) || Objects.equals(user.get(SystemConstant.ID), "")) {
            throw new BusinessException(ExceptionResultEnum.ORG_ID_IS_NULL);
        }
        Long orgId = Long.parseLong(String.valueOf(user.get(SystemConstant.ID)));
        if (Objects.isNull(user.get("enable")) || Objects.equals(user.get("enable"), "")) {
            throw new BusinessException(ExceptionResultEnum.ENABLE_IS_NULL);
        }
        Integer enable = Integer.parseInt(String.valueOf(user.get("enable")));
        TBOrg tbOrg = themisCacheService.addOrgCache(orgId);
        if (Objects.isNull(tbOrg)) {
            throw new BusinessException(ExceptionResultEnum.ORG_NO);
        }
        //保存机构
        tbOrg.setEnable(enable);
        tbOrgService.updateById(tbOrg);
        themisCacheService.updateOrgCache(orgId);
        themisCacheService.updateOrgCodeCache(tbOrg.getCode());
        return ResultUtil.ok(true);
    }
}