package com.yiboshi.science.rest.v1;

import com.yiboshi.arch.base.ResponseDataModel;
import com.yiboshi.science.base.Pagination;
import com.yiboshi.science.config.annotation.Anonymous;
import com.yiboshi.science.config.annotation.Logs;
import com.yiboshi.science.config.security.SecurityUserHolder;
import com.yiboshi.science.entity.ComPerson;
import com.yiboshi.science.enumeration.CommonEnum;
import com.yiboshi.science.param.dto.ComPersonDTO;
import com.yiboshi.science.param.dto.ComUnitDTO;
import com.yiboshi.science.param.query.ComPersonQueryVO;
import com.yiboshi.science.rest.BaseController;
import com.yiboshi.science.service.ComPersonService;
import com.yiboshi.science.service.ComUnitService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.yiboshi.science.utils.StringUtil.hideAllIdCardNum;
import static com.yiboshi.science.utils.StringUtil.hideAllPhoneNum;

/**
 * 功能：人员表 接口
 *
 * @author lkl
 * @version 2021-08-26
 */
@Api(tags = "com-person", description = "人员表")
@RestController
@RequestMapping("/v1/science-admin/com-person")
public class ComPersonController extends BaseController<ComPersonService, ComPersonQueryVO, ComPersonDTO, ComPerson> {

    @Autowired
    private ComPersonService comPersonService;

    @Autowired
    private ComUnitService comUnitService;

    /**
     * 功能:分页查询
     *
     * @param vo 查询条件
     */
    @ApiOperation(value = "1.02 分页查询", httpMethod = "GET", notes = "1.02 根据参数获取列表")
    @GetMapping
    @RequestMapping("/getListByPage")
    @PreAuthorize("hasAnyRole('UNIT')")
    public ResponseDataModel<Pagination<ComPersonDTO>> getListByPage(@Validated ComPersonQueryVO vo, BindingResult bindingResult) {
        vo.setUnitId(SecurityUserHolder.getUnitId());
        vo.setAuditResult(10);
        return getPaginationResponseDataModel(vo);
    }

    /**
     * 功能:分页查询
     *
     * @param vo 查询条件
     */
    @ApiOperation(value = "1.02 分页查询", httpMethod = "GET", notes = "1.02 根据参数获取列表")
    @GetMapping
    @RequestMapping("/getAuditListByPage")
    @PreAuthorize("hasAnyRole('UNIT')")
    public ResponseDataModel<Pagination<ComPersonDTO>> getAuditListByPage(@Validated ComPersonQueryVO vo, BindingResult bindingResult) {
        vo.setTreeCode(SecurityUserHolder.getUnitCode());
        vo.setAuditResult(0);
        return getPaginationResponseDataModel(vo);
    }

    private ResponseDataModel<Pagination<ComPersonDTO>> getPaginationResponseDataModel(@Validated ComPersonQueryVO vo) {
        vo.setRoleId(CommonEnum.systemRole.personal.getCode().toString());
        Pagination<ComPersonDTO> page = comPersonService.getListByPage(vo);
        if (null != page && null != page.getDataList() && page.getDataList().size() != 0) {
            page.getDataList().forEach((e) -> {
                e.setCertId(hideAllIdCardNum(e.getCertId()));
                e.setMobile(hideAllPhoneNum(e.getMobile()));
//                e.setCertId(AesHelper.encrypt(e.getCertId()));
                e.setPersonStateName(CommonEnum.personState.getEnum(e.getPersonState()).getDescription());
            });
        }
        return ResponseDataModel.ok(page);
    }

    /**
     * 功能:分页查询
     *
     * @param vo 查询条件
     */
    @ApiOperation(value = "1.02 分页查询", httpMethod = "GET", notes = "1.02 根据参数获取列表")
    @GetMapping
    @RequestMapping("/getAllListByPage")
    @PreAuthorize("hasAnyRole('ADMIN')")
    public ResponseDataModel<Pagination<ComPersonDTO>> getAllListByPage(@Validated ComPersonQueryVO vo, BindingResult bindingResult) {
        Pagination<ComPersonDTO> page = comPersonService.getAllListByPage(vo);
        if (null != page && null != page.getDataList() && page.getDataList().size() != 0) {
            page.getDataList().forEach((e) -> {
                e.setPersonStateName(CommonEnum.personState.getEnum(e.getPersonState()).getDescription());
            });
        }
        return ResponseDataModel.ok(page);
    }

    @ApiOperation(value = "用户注册", httpMethod = "POST", notes = "用户注册")
    @PostMapping("/register")
    @Anonymous
    @Logs(value = CommonEnum.logType.userRegister)
    public ResponseDataModel<String> register(@Validated @RequestBody ComPersonDTO dto) {
        return ResponseDataModel.ok(comPersonService.register(dto));
    }

    @ApiOperation(value = "用户审核", httpMethod = "POST", notes = "用户审核")
    @RequestMapping("/audit")
    @PostMapping
    @Logs(value = CommonEnum.logType.userAudit)
    @PreAuthorize("hasAnyRole('UNIT')")
    public ResponseDataModel<String> audit(@Validated @RequestBody ComPersonDTO dto) {
        return ResponseDataModel.ok(comPersonService.audit(dto));
    }

    /**
     * 功能:人员信息修改
     * @param d 输入值
     */
    @ApiOperation(value = "1.02", httpMethod = "POST", notes = "1.02 人员信息修改")
    @RequestMapping("/updatePerson")
    @PostMapping
    @PreAuthorize("hasAnyRole('REPORT','UNIT','ADMIN','EXPERT')")
    @Logs(value = CommonEnum.logType.personUpdate)
    public ResponseDataModel<String> updatePerson(@RequestBody ComPersonDTO d) {
        if (!SecurityUserHolder.getRoles().contains(CommonEnum.systemRole.sys.getCode().toString())) {
            d.setCertId(null);
            d.setMobile(null);
        } else {
            if (Objects.nonNull(d.getTreeCode())) {
                ComUnitDTO unit = comUnitService.getByTreeCode(d.getTreeCode());
                if (null != unit) {
                    d.setUnitId(unit.getId());
                }
            }
        }
        return ResponseDataModel.ok(comPersonService.updatePerson(d));
    }

    /**
     * 功能:修改人员状态
     *
     * @param e 输入值
     */
    @ApiOperation(value = "1.02", httpMethod = "POST", notes = "1.02 修改人员状态")
    @RequestMapping("/updateState")
    @PostMapping
    @PreAuthorize("hasAnyRole('ADMIN')")
    public ResponseDataModel<String> updateState(@RequestBody ComPerson e) {
        return ResponseDataModel.ok(comPersonService.updateState(e.getId(), e.getPersonState()));
    }

    @ApiOperation(value = "获取用户信息", httpMethod = "GET", notes = "获取用户信息")
    @GetMapping
    @RequestMapping("/getUserInfo")
    public ResponseDataModel<ComPersonDTO> getUserInfo() {
        ComPersonDTO comPersonDTO = comPersonService.getPersonById(SecurityUserHolder.getPersonId());
        return ResponseDataModel.ok(comPersonDTO);
    }

    @ApiOperation(value = "获取用户信息", httpMethod = "GET", notes = "获取用户信息")
    @GetMapping
    @RequestMapping("/getAppPersonInfo")
    public ResponseDataModel<Map<String, Object>> getAppPersonInfo() {
        ComPerson comPerson = comPersonService.entityById(SecurityUserHolder.getPersonId());
        boolean finalComplete = comPersonService.isComplete(comPerson);
        Map<String, Object> data = new HashMap<String, Object>(3) {
            {
                put("person", comPerson);
                put("isComplete", finalComplete);
            }
        };
        return ResponseDataModel.ok(data);
    }

    @ApiOperation(value = "通过Id获取人员信息", httpMethod = "GET", notes = "通过Id获取人员信息")
    @GetMapping
    @RequestMapping("/getPersonById")
    public ResponseDataModel<ComPersonDTO> getPersonById(String id) {
        ComPersonDTO comPersonDTO = comPersonService.getPersonById(id);
        return ResponseDataModel.ok(comPersonDTO);
    }
}
