package com.jeeplus.finance.workClientInfo.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.finance.workClientInfo.domain.CwOrganizationType;
import com.jeeplus.finance.workClientInfo.service.CwOrganizationTypeService;
import com.jeeplus.finance.workClientInfo.service.dto.CwOrganizationTypeDTO;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Api("客户配置管理-组织类型分类")
@RestController
@RequestMapping(value = "/cw_work_client/organization_type")
public class CwOrganizationTypeController {

    @Resource
    private CwOrganizationTypeService cwOrganizationTypeService;

    /**
     * 查询组织类型分类列表
     * @param cwOrganizationTypeDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询组织类型分类列表")
    @PreAuthorize("hasAuthority('cw_work_client:organization_type:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<CwOrganizationTypeDTO>> data(CwOrganizationTypeDTO cwOrganizationTypeDTO, Page<CwOrganizationTypeDTO> page) throws Exception {
        page.setSize(-1);
        IPage<CwOrganizationTypeDTO> result = new Page<CwOrganizationTypeDTO>();
        if(ObjectUtil.isNotEmpty(cwOrganizationTypeDTO)){
            if(StringUtils.isNotBlank(cwOrganizationTypeDTO.getName())){
                //根据type模糊查询
                List<CwOrganizationType> cwOrganizationTypeList = cwOrganizationTypeService.list(new QueryWrapper<CwOrganizationType>().lambda()
                        .like(StringUtils.isNotBlank(cwOrganizationTypeDTO.getName()), CwOrganizationType::getName, cwOrganizationTypeDTO.getName())
                );
                List<String> idList = new ArrayList<>();
                cwOrganizationTypeList.stream().forEach(item->{
                    if (StringUtils.isNotBlank(item.getParentIds())){
                        String[] split = item.getParentIds().split(",");
                        for (String s : split) {
                            idList.add(s);
                        }
                    }
                    List<CwOrganizationType> list = cwOrganizationTypeService.list(new QueryWrapper<CwOrganizationType>().lambda().like(CwOrganizationType::getParentIds, "," + item.getId() + ","));
                    idList.addAll(list.stream().map(CwOrganizationType::getId).collect(Collectors.toList()));
                    idList.add(item.getId());
                });
                List<String> ids = idList.stream().distinct().filter(item->{
                    if (!"0".equals(item)){
                        return true;
                    }
                    return false;
                }).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(ids)){
                    QueryWrapper<CwOrganizationType> wrapper = new QueryWrapper<CwOrganizationType>()
                            .in("cw_ot.id",ids);
                    result = cwOrganizationTypeService.findList (page,wrapper);
                }
            }else{
                result = cwOrganizationTypeService.findList (page,new QueryWrapper<CwOrganizationType>());
            }
        }
        return ResponseEntity.ok (result);
    }

    /**
     * 查询组织类型分类数据
     * @param id
     * @return
     */
    @ApiLog("查询组织类型分类数据")
    @PreAuthorize ("hasAnyAuthority('cw_work_client:organization_type:view','cw_work_client:organization_type:add','cw_work_client:organization_type:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        CwOrganizationTypeDTO cwOrganizationTypeDTO = cwOrganizationTypeService.queryById ( id );
        return ResponseEntity.ok (cwOrganizationTypeDTO);
    }

    /**
     * 查询全部一级组织类型分类
     * @return
     */
    @ApiLog("查询全部一级组织类型分类")
    @GetMapping("getList")
    public ResponseEntity<List<CwOrganizationTypeDTO>> getList() {
        List<CwOrganizationTypeDTO> list = cwOrganizationTypeService.getList();
        return ResponseEntity.ok (list);
    }

    /**
     * 保存组织类型分类
     * @param cwOrganizationTypeDTO
     * @return
     */
    @ApiLog(value = "修改/新增组织类型分类", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('cw_work_client:organization_type:save','cw_work_client:organization_type:edit')")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody CwOrganizationTypeDTO cwOrganizationTypeDTO) {
        cwOrganizationTypeService.saveType(cwOrganizationTypeDTO);
        return ResponseEntity.ok ("操作成功");
    }

    /**
     * 删除组织类型分类
     * @param ids
     * @return
     */
    @ApiLog(value = "删除组织类型分类", type = LogTypeEnum.SAVE)
    @PreAuthorize ("hasAuthority('cw_work_client:organization_type:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids) {
        return cwOrganizationTypeService.deleteByIds(ids);
    }

}
