/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 运维系统
 * 创建日期:2023/11/9
 */
package org.springblade.modules.yjxt.base.servicePerson.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.DigestUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.baseinfo.org.entity.DeptRegionEntity;
import org.springblade.modules.baseinfo.org.service.IDeptRegionService;
import org.springblade.modules.system.entity.Post;
import org.springblade.modules.system.entity.Role;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IPostService;
import org.springblade.modules.system.service.IRoleService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.yjxt.base.servicePerson.dto.YjxtServicePersonDTO;
import org.springblade.modules.yjxt.base.servicePerson.entity.YjxtServicePersonEntity;
import org.springblade.modules.yjxt.base.servicePerson.service.IYjxtServicePersonServcie;
import org.springblade.modules.yjxt.base.servicePerson.vo.YjxtServicePersonVO;
import org.springblade.modules.yjxt.base.servicePerson.wrapper.YjxtServicePersonWrapper;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;


import java.util.List;
import java.util.Objects;

/***
 * Date:2023/11/9
 * Title:文件所属模块（必须填写）
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
@RequestMapping("galaxy-business/yj/base/serviceperson")
@AllArgsConstructor
@Api(value = "应急系统工作人员管理接口", tags = "增、删、改、查")
public class YjxtServicePersonController extends BladeController {

    private final IYjxtServicePersonServcie yjxtServicePersonServcie;
    private final IUserService userService;
    private final IRoleService roleService;
    private final IPostService postService;
    private final IDeptRegionService deptRegionService;


    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "名称", paramType = "query", dataType = "string"),
    })
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "分页")
    public R<IPage<YjxtServicePersonVO>> page(@ApiIgnore YjxtServicePersonDTO dto, Query query) {
        BladeUser user = AuthUtil.getUser();
       if (Func.isNull(dto.getAdCode())) {
            if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
                dto.setAdCode(BusinessConstant.REGION_NM_ADCODE);
            } else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)) {
                    return R.fail("查询失败");
                }
                dto.setAdCode(deptRegionEntity.getAdcd());
            } else if (BusinessConstant.ROLE_YJ_SERVICE_PERSON.equals(user.getRoleName())) {
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)) {
                    return R.fail("查询失败");
                }
                dto.setAdCode(deptRegionEntity.getAdcd());
            } else if (BusinessConstant.ROLE_QI_ADMIN.equals(user.getRoleName())) {
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)) {
                    return R.fail("查询失败");
                }
                dto.setAdCode(deptRegionEntity.getAdcd());
            } else {
                return R.fail("查询失败");
            }
        }

//        if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
//            dto.setDeptId(user.getDeptId());
//        }
        IPage<YjxtServicePersonVO> pages = yjxtServicePersonServcie.selectPage(Condition.getPage(query), dto);
        return R.data(pages);
    }

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "详情", notes = "传入 User")
    public R<YjxtServicePersonVO> detail(YjxtServicePersonEntity entity) {
        YjxtServicePersonEntity detail = yjxtServicePersonServcie.getById(entity.getId());
        return R.data(YjxtServicePersonWrapper.build().entityVO(detail));
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入 User")
    public R save(@RequestBody YjxtServicePersonDTO dto) {
        BladeUser user = AuthUtil.getUser();
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>query().lambda();
        wrapper.eq(User::getAccount, dto.getUserAccount());
        wrapper.eq(User::getIsDeleted, 0);
        wrapper.last("limit 1");
        User detail = userService.getOne(wrapper);
        if (Func.notNull(detail)) {
            return R.fail("帐号已经存在");
        }
        LambdaQueryWrapper<DeptRegionEntity> regionWrapper = Wrappers.<DeptRegionEntity>query().lambda();
        regionWrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
        regionWrapper.last("limit 1");
        DeptRegionEntity deptRegionEntity = deptRegionService.getOne(regionWrapper);
        if (Func.isNull(deptRegionEntity)) {
            return R.fail("系统错误");
        }
        User userEntity = new User();
        userEntity.setAccount(dto.getUserAccount());
        userEntity.setRealName(dto.getUserName());
        userEntity.setName(dto.getUserName());
        userEntity.setPhone(dto.getPhone());
        userEntity.setPassword(DigestUtil.encrypt(userEntity.getAccount() + BusinessConstant.ACCOUNT_PW_SUFFIX));
        LambdaQueryWrapper<Role> roleWrapper = Wrappers.<Role>query().lambda();
        roleWrapper.eq(Role::getRoleAlias, BusinessConstant.ROLE_YJ_SERVICE_PERSON);
        roleWrapper.eq(Role::getIsDeleted, 0);
        roleWrapper.last("limit 1");
        Role role = roleService.getOne(roleWrapper);
        userEntity.setRoleId(Func.toStr(role.getId()));
        LambdaQueryWrapper<Post> postWrapper = Wrappers.<Post>query().lambda();
        postWrapper.eq(Post::getPostCode, BusinessConstant.POST_YJ_SERVICE_PERSON_CODE);
        postWrapper.eq(Post::getIsDeleted, 0);
        postWrapper.last("limit 1");
        Post post = postService.getOne(postWrapper);
        userEntity.setPostId(Func.toStr(post.getId()));
        userEntity.setDeptId(user.getDeptId());
        userEntity.setUserType(2);
        if (userService.save(userEntity)) {
            YjxtServicePersonEntity yjxtServicePersonEntity = new YjxtServicePersonEntity();
            yjxtServicePersonEntity.setUserId(userEntity.getId());
            yjxtServicePersonEntity.setAdCode(deptRegionEntity.getAdcd());
            yjxtServicePersonServcie.save(yjxtServicePersonEntity);
        }
        return R.status(true);
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入 User")
    public R update(@RequestBody YjxtServicePersonDTO dto) {
        if (Objects.isNull(dto.getId())) {
            return R.fail("用户ID不能为空！");
        }
        YjxtServicePersonEntity entity = yjxtServicePersonServcie.getById(dto.getId());
        entity.setAdCode(dto.getAdCode());
        yjxtServicePersonServcie.updateById(entity);

        User user = userService.getById(dto.getUserId());
        user.setName(dto.getUserName());
        user.setRealName(dto.getUserName());
        user.setPhone(dto.getPhone());
        return R.status(userService.updateById(user));
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "逻辑删除", notes = "传入 ids")
    public R remove(@ApiParam(value = "主键集合") @RequestParam String ids) {
        List<Long> list = Func.toLongList(ids);
        if (list.size() > 0) {
            for (Long id : list) {
                YjxtServicePersonEntity entity = yjxtServicePersonServcie.getById(id);
                if (userService.removeById(entity.getUserId())) {
                    yjxtServicePersonServcie.removeById(id);
                }
            }
        }
        return R.status(true);
    }

}
