/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2022/8/22
 */
package org.springblade.modules.baseinfo.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.springblade.constant.BusinessConstant;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.baseinfo.org.dto.OrgInfoDTO;
import org.springblade.modules.baseinfo.org.entity.OrgTreeNodeEntity;
import org.springblade.modules.baseinfo.project.dto.ProjectInfoDTO;
import org.springblade.modules.baseinfo.project.entity.ProjectInfoEntity;
import org.springblade.modules.baseinfo.project.entity.ProjectTreeNodeEntity;
import org.springblade.modules.baseinfo.project.service.IBaseProjectService;
import org.springblade.modules.baseinfo.project.service.IProjectWarningSettingService;
import org.springblade.modules.baseinfo.project.vo.ProjectInfoVO;
import org.springblade.modules.baseinfo.project.wrapper.ProjectInfoWrapper;
import org.springblade.modules.baseinfo.region.entity.RegionInfoEntity;
import org.springblade.modules.baseinfo.region.service.IBaseRegionService;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


/***
 * Date:2022/8/22
 * Title:文件所属模块（必须填写）
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
@RequestMapping("galaxy-business/baseinfo/project")
@AllArgsConstructor
@Api(value = "项目信息基础管理", tags = "项目信息基础管理")
public class BaseProjectController extends BladeController {
    private final IBaseProjectService baseProjectService;
    private final IBaseRegionService baseRegionService;


    /**
     * 分页
     */
    @GetMapping("/list")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页")
    public R<IPage<ProjectInfoVO>> list(Query query) {
        IPage<ProjectInfoEntity> pages = baseProjectService.page(Condition.getPage(query));
        return R.data(ProjectInfoWrapper.build().pageVO(pages));
    }

    @GetMapping("/org/list")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页")
    public R<List<ProjectInfoVO>> orglist() {
        LambdaQueryWrapper<ProjectInfoEntity> wrapper = Wrappers.<ProjectInfoEntity>query().lambda();
        BladeUser user = AuthUtil.getUser();
        if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {

        } else if (BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
            wrapper.eq(ProjectInfoEntity::getOrgId, user.getDeptId());
        }
        wrapper.eq(ProjectInfoEntity::getIsDeleted, 0);
        List<ProjectInfoEntity> pages = baseProjectService.list(wrapper);
        return R.data(ProjectInfoWrapper.build().listVO(pages));
    }

    /**
     * 多表联合查询自定义分页
     */
    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectName", value = "项目名称", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "orgId", value = "机构ID", paramType = "query", dataType = "long"),
            @ApiImplicitParam(name = "adcd", value = "行政区划编码", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "paramsType", value = "参数类型", paramType = "query", dataType = "int"),
    })
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页")
    public R<IPage<ProjectInfoVO>> page(@ApiIgnore ProjectInfoDTO dto, Query query) {
        BladeUser user = AuthUtil.getUser();
        if (Func.isNull(dto.getTenantId())){
            dto.setTenantId(user.getTenantId());
        }
        if (dto.getParamsType() == 0) {
            dto.setAdcd(null);
            if (dto.getOrgId() != null) {
                if (BusinessConstant.DEPT_DH_ID.equals(dto.getOrgId())) {
                    dto.setOrgId(null);
                }
            }
        } else if (dto.getParamsType() == 2) {
            dto.setOrgId(null);
            if (dto.getAdcd() != null && dto.getAdcd().length() == 0) {
                dto.setAdcd(null);
            }
            if (dto.getAdcd() != null) {
                if ("00".equals(dto.getAdcd())) {
                    dto.setAdcd(null);
                }
            }
        }
        IPage<ProjectInfoVO> pages = baseProjectService.selectPage(Condition.getPage(query), dto);
        List<ProjectInfoVO> list = pages.getRecords();
        for (ProjectInfoVO vo : list) {
            ProjectInfoWrapper.build().entityVO(vo);
        }
        return R.data(pages);
    }


    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入projectInfoEntity")
    public R<ProjectInfoVO> detail(ProjectInfoEntity projectInfoEntity) {
        ProjectInfoEntity detail = baseProjectService.getById(projectInfoEntity.getId());
        return R.data(ProjectInfoWrapper.build().entityVO(detail));
    }


    /**
     * 新增
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入ProjectInfoEntity")
    public R save(@RequestBody ProjectInfoEntity projectInfoEntity) {
        return R.status(baseProjectService.save(projectInfoEntity));
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入ProjectInfoEntity")
    public R update(@RequestBody ProjectInfoEntity projectInfoEntity) {
        return R.status(baseProjectService.updateById(projectInfoEntity));
    }

    /**
     * 新增或修改
     */
    @PostMapping("/submit")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "新增或修改", notes = "传入projectInfoEntity")
    public R submit(@RequestBody ProjectInfoEntity projectInfoEntity) {
        return R.status(baseProjectService.saveOrUpdate(projectInfoEntity));
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "逻辑删除", notes = "传入projectInfoEntity")
    public R remove(@ApiParam(value = "主键集合") @RequestParam String ids) {
        boolean temp = baseProjectService.deleteLogic(Func.toLongList(ids));
        return R.status(temp);
    }

    /**
     * 行政区配置
     *
     * @param dto
     * @return
     */
    @GetMapping("/ad/setting/list")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页")
    public R<List<ProjectInfoVO>> adSettingList(ProjectInfoDTO dto) {
        List<ProjectInfoVO> list = new ArrayList<>();
        return R.data(list);
    }


    /**
     * 行政区配置
     *
     * @param dto
     * @return
     */
    @PostMapping("/ad/setting/submit")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "项目ID", paramType = "query", dataType = "long"),
            @ApiImplicitParam(name = "adcd", value = "项目编码", paramType = "query", dataType = "string"),
    })
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "行政区配置", notes = "")
    public R adSettingSubmit(@ApiIgnore ProjectInfoDTO dto) {
        if (dto.getId() == null || dto.getAdcd() == null) {
            return R.fail("参数错误");
        }

        ProjectInfoEntity entity = this.baseProjectService.getById(dto.getId());

        RegionInfoEntity regionInfoEntity = this.baseRegionService.getByCode(dto.getAdcd());

        entity.setAdcd(regionInfoEntity.getAncestors() + "," + dto.getAdcd());
        this.baseProjectService.updateById(entity);

        return R.success("行政区配置操作成功");
    }


    /**
     * 行政区配置删除
     *
     * @param ids
     * @return
     */
    @PostMapping("/ad/setting/remove")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "逻辑删除", notes = "")
    public R adSettingRemove(@ApiParam(value = "主键集合") @RequestParam String ids) {
        //boolean temp = baseProjectService.deleteLogic(Func.toLongList(ids));
        return R.status(true);
    }

    /**
     * 项目预警配置保存或修改
     *
     * @param projectInfoEntity
     * @return
     */
    @PostMapping("/setting/warning/submit")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "项目ID", paramType = "query", dataType = "long"),
            @ApiImplicitParam(name = "warnActive", value = "预警开关", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "delayTime", value = "延时", paramType = "query", dataType = "int")
    })
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "项目预警配置新增或修改", notes = "传入warningSettingEntity")
    public R warningSubmit(@ApiIgnore ProjectInfoEntity projectInfoEntity) {
        //return R.status(warningSettingService.saveOrUpdate(warningSettingEntity));

//        LambdaUpdateWrapper<ProjectInfoEntity> wrapper = Wrappers.<ProjectInfoEntity>update().lambda();
//        wrapper.set(ProjectInfoEntity::getWarnActive, projectInfoEntity.getWarnActive());
//        wrapper.set(ProjectInfoEntity::getDelayTime, projectInfoEntity.getDelayTime());
//        wrapper.eq(ProjectInfoEntity::getId, projectInfoEntity.getId());
//
//        this.projectBaseInfoService.update(wrapper);

        return R.success("预警设置操作成功");
    }

    @GetMapping("/tree")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情")
    public R<List<ProjectTreeNodeEntity>> projectTree() {
        BladeUser user = AuthUtil.getUser();
        List<ProjectTreeNodeEntity> tree = new LinkedList<>();
        ProjectInfoDTO dto = new ProjectInfoDTO();
        dto.setOrgId(Func.toLong(user.getDeptId()));
        List<ProjectInfoVO> list = this.baseProjectService.selectList(dto);
        if (null != list) {
            for (ProjectInfoVO vo : list) {
                ProjectTreeNodeEntity node = new ProjectTreeNodeEntity();
                node.setText(vo.getProjectName());
                node.setValue(Func.toStr(vo.getId()));
                tree.add(node);
            }
        }
        return R.data(tree);
    }


    @GetMapping("/lazy-tree")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "行政区划代码", paramType = "query", dataType = "long"),
    })
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "树")
    public R<List<ProjectTreeNodeEntity>> lazyTree(@ApiIgnore ProjectInfoDTO dto) {
        List<ProjectTreeNodeEntity> nodeEntities = new LinkedList<>();
        BladeUser user = AuthUtil.getUser();
        dto.setOrgId(Func.toLong(user.getDeptId()));
        List<ProjectInfoVO> list = this.baseProjectService.selectList(dto);
        if (null != list) {
            for (ProjectInfoVO vo : list) {
                ProjectTreeNodeEntity node = new ProjectTreeNodeEntity();
                node.setId(Func.toStr(vo.getId()));
                node.setValue(Func.toStr(vo.getId()));
                node.setTitle(vo.getProjectName());
                node.setText(vo.getProjectName());
                node.setKey(Func.toStr(vo.getId()));

                nodeEntities.add(node);
            }
        }
        return R.data(nodeEntities);
    }

}
