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.bean.SystemProperties;
import com.yiboshi.science.config.security.SecurityUserHolder;
import com.yiboshi.science.entity.ComUnit;
import com.yiboshi.science.entity.SelectListItem;
import com.yiboshi.science.enumeration.CommonEnum;
import com.yiboshi.science.param.dto.ComUnitDTO;
import com.yiboshi.science.param.query.ComUnitQueryVO;
import com.yiboshi.science.rest.BaseController;
import com.yiboshi.science.service.ComPersonService;
import com.yiboshi.science.service.ComUnitService;
import com.yiboshi.science.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.*;

/**
 * 功能：单位表 接口
 *
 * @author lkl
 * @version 2021-08-26
 */
@Api(tags = "com-unit", description = "单位表")
@RestController
@RequestMapping("/v1/science-admin/com-unit")
public class ComUnitController extends BaseController<ComUnitService, ComUnitQueryVO, ComUnitDTO, ComUnit> {

    @Autowired
    private ComUnitService comUnitService;

    @Autowired
    private ComPersonService comPersonService;

    @Autowired
    private SystemProperties properties;

    @ApiOperation(value = "1.02 分页查询", httpMethod = "GET", notes = "根据参数获取单位信息列表(分页)")
    @GetMapping
    @RequestMapping("/getListByPage")
    @PreAuthorize("hasAnyRole('GOV','ADMIN')")
    public ResponseDataModel<Pagination<ComUnitDTO>> getListByPage(@Validated ComUnitQueryVO vo, BindingResult bindingResult) {
        if (!StringUtil.isContainsRole(SecurityUserHolder.getRoles(), CommonEnum.systemRole.sys.getCode().toString())) {
            vo.setUpTreeCode(SecurityUserHolder.getUnitCode());
            vo.setAuditResult(10);
        }
        return getPaginationResponseDataModel(vo);
    }

    @ApiOperation(value = "获取单位审核列表", httpMethod = "GET", notes = "获取单位审核列表(分页)")
    @GetMapping
    @RequestMapping("/getAuditListByPage")
    @PreAuthorize("hasAnyRole('GOV')")
    public ResponseDataModel<Pagination<ComUnitDTO>> getAuditListByPage(@Validated ComUnitQueryVO vo, BindingResult bindingResult) {
        vo.setAuditResult(0);
        if (SecurityUserHolder.getUnitCode().length() != properties.getDefaultCodeLength())
            vo.setAuditUnit(SecurityUserHolder.getUnitId());
        vo.setTreeCode(SecurityUserHolder.getUnitCode());
        return getPaginationResponseDataModel(vo);
    }

    private ResponseDataModel<Pagination<ComUnitDTO>> getPaginationResponseDataModel(@Validated ComUnitQueryVO vo) {
        Pagination<ComUnitDTO> page = comUnitService.getListByPage(vo);
        if (null != page && null != page.getDataList() && page.getDataList().size() != 0) {
            page.getDataList().forEach((e) -> {
                e.setUnitTypeName(CommonEnum.unitType.getEnum(e.getUnitType()).getDescription());
                e.setUnitStateName(CommonEnum.unitState.getEnum(e.getUnitState()).getDescription());
            });
        }
        return ResponseDataModel.ok(page);
    }

    @ApiOperation(value = "获取单位信息", httpMethod = "GET", notes = "获取单位信息")
    @GetMapping
    @RequestMapping("/getUnitById")
    public ResponseDataModel<ComUnitDTO> getUnitById(String id) {
        return ResponseDataModel.ok(comUnitService.getUnitById(id));
    }

    @ApiOperation(value = "单位注册", httpMethod = "POST", notes = "单位注册")
    @RequestMapping("/register")
    @PostMapping
    @Anonymous
    @Logs(value = CommonEnum.logType.unitRegister)
    public ResponseDataModel<String> register(@Validated @RequestBody ComUnitDTO dto) {
        return ResponseDataModel.ok(comUnitService.register(dto));
    }

    @ApiOperation(value = "单位审核", httpMethod = "POST", notes = "单位审核")
    @RequestMapping("/audit")
    @PostMapping
    @Logs(value = CommonEnum.logType.unitAudit)
    public ResponseDataModel<String> audit(@Validated @RequestBody ComUnitDTO dto) {
        return ResponseDataModel.ok(comUnitService.audit(dto));
    }

    @ApiOperation(value = "新增单位", httpMethod = "POST", notes = "新增单位数据", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping
    @RequestMapping("/addUnit")
    @Logs(value = CommonEnum.logType.unitAdd)
    public ResponseDataModel<String> addUnit(@Validated @RequestBody ComUnitDTO d) {
        if(Objects.isNull(d.getUpTreeCode()))
            d.setUpTreeCode(SecurityUserHolder.getUnitCode());
        return ResponseDataModel.ok(comUnitService.save(d));
    }

    @ApiOperation(value = "修改单位信息", httpMethod = "PUT", notes = "2.02 修改数据", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(dataType = "string", name = "id", value = "主键", example = "1", type = "path")
    @PutMapping(value = "updateUnit")
    @Logs(value = CommonEnum.logType.unitUpdate)
    public ResponseDataModel<String> updateUnit(@Validated @RequestBody ComUnitDTO dto) {
        return ResponseDataModel.ok(comUnitService.save(dto));
    }

    @ApiOperation(value = "修改单位状态", httpMethod = "PUT", notes = "修改单位状态", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(dataType = "string", name = "id", value = "主键", example = "1", type = "path")
    @PutMapping(value = "updateUnitState")
    @Logs(value = CommonEnum.logType.unitStateUpdate)
    public ResponseDataModel<String> updateUnitState(@Validated @RequestBody ComUnitDTO D) {
        return ResponseDataModel.ok(comUnitService.updateUnitState(D));
    }

    @ApiOperation(value = "删除单位", httpMethod = "DELETE", notes = "删除单位")
    @DeleteMapping(value = "deleteUnitById/{id}")
    @Logs(value = CommonEnum.logType.unitDelete)
    public ResponseDataModel<String> deleteUnitById(@PathVariable String id) {
        return ResponseDataModel.ok(comUnitService.deleteUnit(id));
    }

    @ApiOperation(value = "获取单位编码列表", httpMethod = "GET", notes = "获取单位编码列表")
    @GetMapping
    @RequestMapping("/getTreeCodeListByType")
    @Anonymous
    public ResponseDataModel<List<SelectListItem>> getTreeCodeListByType(ComUnitDTO unit) {
        List<SelectListItem> list = new ArrayList<>();
        List<ComUnitDTO> dtoList = comUnitService.getListByType(unit.getUnitType());
        dtoList.forEach((e) -> {
            list.add(new SelectListItem(e.getUnitName(), e.getTreeCode(),"",true, true, null));
        });
        return ResponseDataModel.ok(list);
    }

    @ApiOperation(value = "获取单位Id列表", httpMethod = "GET", notes = "获取单位Id列表")
    @GetMapping
    @RequestMapping("/getIdListByType")
    @Anonymous
    public ResponseDataModel<List<SelectListItem>> getIdListByType(ComUnitDTO unit) {
        List<SelectListItem> list = new ArrayList<>();
        List<ComUnitDTO> dtoList = comUnitService.getListByType(unit.getUnitType());
        dtoList.forEach((e) -> {
            list.add(new SelectListItem(e.getUnitName(), e.getId(),"",true, true, null));
        });
        return ResponseDataModel.ok(list);
    }

    @ApiOperation(value = "获取单位信息", httpMethod = "GET", notes = "获取单位信息")
    @GetMapping
    @RequestMapping("/getListByUnitName")
    @Anonymous
    public ResponseDataModel<List<SelectListItem>> getListByUnitName(String UnitName) {
        List<SelectListItem> list = new ArrayList<>();
        List<ComUnitDTO> dtoList = comUnitService.getListByUnitName(UnitName);
        dtoList.forEach((e) -> {
            list.add(new SelectListItem(e.getUnitName(), e.getId(),"",true, true, null));
        });
        return ResponseDataModel.ok(list);
    }



    @ApiOperation(value = "获取单位类型", httpMethod = "GET", notes = "获取单位类型")
    @GetMapping
    @RequestMapping("/getUnitType")
    @Anonymous
    public ResponseDataModel<List<SelectListItem>> getUnitTypeList() {
        List<SelectListItem> list = new ArrayList<>(CommonEnum.unitType.values().length);
        for (CommonEnum.unitType unitType : CommonEnum.unitType.values()) {
            SelectListItem item = new SelectListItem();
            item.setKey(unitType.getCode().toString());
            item.setTitle(unitType.getDescription());
            list.add(item);
        }
        return ResponseDataModel.ok(list);
    }

    @ApiOperation(value = "获取单位级别", httpMethod = "GET", notes = "获取单位级别")
    @GetMapping
    @RequestMapping("/getUnitLevel")
    @Anonymous
    public ResponseDataModel<List<SelectListItem>> getUnitLevelList() {
        List<SelectListItem> list = new ArrayList<>(CommonEnum.unitLevel.values().length);
        for (CommonEnum.unitLevel unitLevel : CommonEnum.unitLevel.values()) {
            SelectListItem item = new SelectListItem();
            item.setKey(unitLevel.getCode().toString());
            item.setTitle(unitLevel.getDescription());
            list.add(item);
        }
        return ResponseDataModel.ok(list);
    }

    @ApiOperation(value = "处理远程单位人员信息", httpMethod = "GET", notes = "处理远程单位人员信息")
    @GetMapping
    @RequestMapping("/processRemoteInfo")
    public ResponseDataModel<Map<String, Object>> processRemoteInfo(String id) {
        comPersonService.getUserFromRemoteServer();
        ComUnitDTO ComUnit = comUnitService.getUnitById(SecurityUserHolder.getUnitId());
        Map<String, Object> info = new HashMap<String, Object>(2) {
            {
                put("roleId", SecurityUserHolder.getRoles());
                put("unit", ComUnit);
            }
        };
        return ResponseDataModel.ok(info);
    }

    @ApiOperation(value = "获取单位信息", httpMethod = "GET", notes = "获取单位信息")
    @GetMapping
    @RequestMapping("/getAppUnitInfo")
    public ResponseDataModel<Map<String, Object>> getAppUnitInfo() {
        ComUnit comUnit = comUnitService.entityById(SecurityUserHolder.getUnitId());
        boolean finalComplete = comUnitService.isComplete(comUnit);
        Map<String, Object> data = new HashMap<String, Object>(2) {
            {
                put("unit", comUnit);
                put("isComplete", finalComplete);
            }
        };
        return ResponseDataModel.ok(data);
    }

    @ApiOperation(value = "获取当前操作人员的单位信息", httpMethod = "GET", notes = "获取当前操作人员的单位信息")
    @GetMapping
    @RequestMapping("/getCurrentUnitInfo")
    public ResponseDataModel<ComUnitDTO> getCurrentUnitInfo() {
        return ResponseDataModel.ok(comUnitService.getUnitById(SecurityUserHolder.getUnitId()));
    }
}
