package com.yiboshi.science.rest.v1;

import com.yiboshi.arch.base.ResponseDataModel;
import com.yiboshi.science.base.Pagination;
import com.yiboshi.science.config.annotation.Logs;
import com.yiboshi.science.config.security.SecurityUserHolder;
import com.yiboshi.science.entity.ComExpert;
import com.yiboshi.science.entity.ComUnit;
import com.yiboshi.science.entity.SelectListItem;
import com.yiboshi.science.enumeration.CommonEnum;
import com.yiboshi.science.param.dto.ComExpertDTO;
import com.yiboshi.science.param.dto.ComExpertSpecDTO;
import com.yiboshi.science.param.dto.ComUnitDTO;
import com.yiboshi.science.param.query.ComExpertQueryVO;
import com.yiboshi.science.rest.BaseController;
import com.yiboshi.science.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.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.List;
import java.util.Map;
import java.util.Objects;


@Api(tags = "com-expert", description = "专家表")
@RestController
@RequestMapping("/v1/science-admin/com-expert")
public class ComExpertController extends BaseController<ComExpertService, ComExpertQueryVO, ComExpertDTO, ComExpert> {

    @Autowired
    private ComExpertService comExpertService;
    @Autowired
    private ComProjectAssignService ComProjectAssignService;

    @Autowired
    private ComExpertSpecService comExpertSpecService;

    @Autowired
    private ComUnitService comUnitService;

    @ApiOperation(value = "1.02 分页查询", httpMethod = "GET", notes = "1.02 根据参数获取列表")
    @GetMapping
    @RequestMapping("/getListByPage")
    @PreAuthorize("hasAnyRole('GOV','UNIT')")
    public ResponseDataModel<Pagination<ComExpertDTO>> getListByPage(@Validated ComExpertQueryVO vo, BindingResult bindingResult) {
        vo.setRoleId(CommonEnum.systemRole.expert.getCode().toString());
        if (SecurityUserHolder.getRoles().contains(CommonEnum.systemRole.unit.getCode().toString())) {
            vo.setUnitId(SecurityUserHolder.getUnitId());
        }else{
            vo.setReportState(2);
        }
        Pagination<ComExpertDTO> page = comExpertService.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.setExpertStateName(CommonEnum.loginState.getEnum(e.getExpertState()).getDescription());
                List<ComExpertSpecDTO> ExpertSpecList = comExpertSpecService.getListByExpertId(e.getId());
                e.setSpecList(ExpertSpecList);
                ExpertSpecList.forEach((p) -> {
                    e.setSpecName(e.getSpecName() + p.getSpecName() + "、");
                });
                if (StringUtils.isNotBlank(e.getSpecName()))
                    e.setSpecName(e.getSpecName().substring(0, e.getSpecName().length() - 1));
            });
        }
        return ResponseDataModel.ok(page);
    }

    @ApiOperation(value = "获取专家列表(分页)", httpMethod = "GET", notes = "获取专家列表(分页)")
    @GetMapping
    @RequestMapping("/getAssignExpertList")
    public ResponseDataModel<Pagination<ComExpertDTO>> getAssignExpertList(@Validated ComExpertQueryVO vo, BindingResult bindingResult) {
        Pagination<ComExpertDTO> page = comExpertService.getListByPage(vo);
        if (null != page && null != page.getDataList() && page.getDataList().size() != 0) {
            page.getDataList().forEach((e) -> {
//                e.setCertId(hideAllIdCardNum(e.getCertId()));
//                e.setMobile(concealAllPhoneNum(e.getMobile()));
//                e.setExpertStateName(CommonEnum.ExpertState.getEnum(e.getExpertState()).getDescription());
                e.setAssignInfo(ComProjectAssignService.getAssignCount(e.getId()));
            });
        }
        return ResponseDataModel.ok(page);
    }

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

    @ApiOperation(value = "添加", httpMethod = "POST", notes = "添加或更新专家")
    @RequestMapping("/insert")
    @PostMapping
    @Logs(value = CommonEnum.logType.expertAdd)
    public ResponseDataModel<String> insert(@Validated @RequestBody ComExpertDTO dto) {
        checkRole(dto);
        return ResponseDataModel.ok(comExpertService.insert(dto));
    }

    @ApiOperation(value = "更新专家", httpMethod = "POST", notes = "添加或更新专家")
    @RequestMapping("/update")
    @PutMapping
    @Logs(value = CommonEnum.logType.expertUpdate)
    public ResponseDataModel<String> update(@Validated @RequestBody ComExpertDTO dto) {
        checkRole(dto);
        return ResponseDataModel.ok(comExpertService.update(dto));
    }

    private void checkRole(@RequestBody @Validated ComExpertDTO dto) {
        if (SecurityUserHolder.getRoles().contains(CommonEnum.systemRole.unit.getCode().toString())) {
            dto.setUnitId(SecurityUserHolder.getUnitId());
            ComUnitDTO comUnitDTO = comUnitService.getUnitById(SecurityUserHolder.getUnitId());
            dto.setWorkUnit(comUnitDTO.getUnitName());
            if (Objects.isNull(dto.getReportState())) {
                dto.setReportState(1);
            }
        } else {
            if (Objects.nonNull(dto.getTreeCode())) {
                ComUnitDTO unit = comUnitService.getByTreeCode(dto.getTreeCode());
                if (null != unit) {
                    dto.setUnitId(unit.getId());
                    dto.setWorkUnit(unit.getUnitName());
                }
            }else {
                ComUnit comUnit = comUnitService.isExist(dto.getWorkUnit());
                if (null != comUnit){
                    dto.setUnitId(comUnit.getId());
                    dto.setWorkUnit(comUnit.getUnitName());
                }
            }
            if (Objects.isNull(dto.getReportState())) {
                dto.setReportState(2);
            }
        }
    }

    @ApiOperation(value = "删除专家", httpMethod = "POST", notes = "删除专家")
    @RequestMapping("/deleteExpert")
    @PostMapping
    @Logs(value = CommonEnum.logType.expertDelete)
    public ResponseDataModel<String> deleteExpert(@Validated @RequestBody ComExpertDTO dto) {
        return ResponseDataModel.ok(comExpertService.deleteExpert(dto));
    }

    /**
     * 功能:修改状态
     *
     * @param d 输入值
     */
    @ApiOperation(value = "1.02", httpMethod = "POST", notes = "1.02 修改状态")
    @RequestMapping("/updateExpertState")
    @PostMapping
    @Logs(value = CommonEnum.logType.expertStateUpdate)
    public ResponseDataModel<String> updateExpertState(@RequestBody ComExpertDTO d) {
        return ResponseDataModel.ok(comExpertService.updateExpertState(d));
    }

    @ApiOperation(value = "专家批量导入", httpMethod = "POST", notes = "专家批量导入")
    @RequestMapping("/expertImport")
    @PostMapping
    public ResponseDataModel<String> expertImport(@Validated @RequestBody List<ComExpertDTO> list) {
        String unitName="";
        ComUnit unit = comUnitService.getById(SecurityUserHolder.getUnitId());
        if (null != unit) {
            unitName=unit.getUnitName();
        }
        return ResponseDataModel.ok(comExpertService.expertImport(list,unitName));
    }

    @ApiOperation(value = "验证证件号是否存在", httpMethod = "GET", notes = "验证证件号是否存在")
    @GetMapping
    @RequestMapping("/expertIsExist")
    public ResponseDataModel<Boolean> expertIsExist(String certId, String id) {
        Boolean result = comExpertService.expertIsExist(certId, id);
        return ResponseDataModel.ok(result);
    }

    @ApiOperation(value = "根据类型参数列表", httpMethod = "GET", notes = "根据类型参数列表")
    @GetMapping
    @RequestMapping("/getExpertListByIdList")
    public ResponseDataModel<List<SelectListItem>> getExpertListByIdList(@RequestBody Map<String, Object> idList) {
        return ResponseDataModel.ok(comExpertService.getExpertListByIdList(idList));
    }
}
