package com.yccrc.kede.controller.admin;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yccrc.common.annotation.Log;
import com.yccrc.common.constant.UserConstants;
import com.yccrc.common.core.controller.BaseController;
import com.yccrc.common.core.domain.entity.SysUser;
import com.yccrc.common.enums.BusinessType;
import com.yccrc.common.exception.ServiceException;
import com.yccrc.common.utils.PageUtils;
import com.yccrc.common.utils.SecurityUtils;
import com.yccrc.common.utils.StringUtils;
import com.yccrc.common.vo.Result;
import com.yccrc.kede.domain.Region;
import com.yccrc.kede.service.IRegionService;
import com.yccrc.system.service.ISysRoleService;
import com.yccrc.system.service.ISysUserService;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "政务用户管理")
@RestController
@RequestMapping("/admin/gov")
public class GovUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private IRegionService regionService;
    
    @Autowired
	ISysRoleService sysRoleService;

    @ApiOperation(value = "查询政务用户")
    @GetMapping("/list")
    public Result<Page<SysUser>> list(SysUser user)
    {
    	QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>()
    			.likeRight("user_type", "GOV_")
    			.eq(!StrUtil.isEmpty(user.getStatus()), "status", user.getStatus())
    			.like(!StrUtil.isEmpty(user.getUserName()), "user_name", user.getUserName());
    	
    	if(!StrUtil.isEmpty(user.getDistrictId())) {
    		queryWrapper.eq("scope_id", user.getDistrictId());
    	}else if(!StrUtil.isEmpty(user.getCityId())) {
    		Region region = regionService.getById(user.getCityId());
    		queryWrapper.like(region!=null, "remark", region.getName());
    	}else if(!StrUtil.isEmpty(user.getProvinceId())) {
    		Region region = regionService.getById(user.getProvinceId());
    		queryWrapper.like(region!=null, "remark", region.getName());
    	}
    	
    	queryWrapper.orderByDesc("user_id");
       return new Result<Page<SysUser>>().ok(userService.page(PageUtils.initPage(), queryWrapper));
     
    }

    @ApiOperation(value = "获取用户详细信息")
    @GetMapping(value = "/{id}")
    public Result<SysUser> getInfo(@PathVariable("id") Long id)
    {
    	SysUser sysUser = userService.getById(id);
    	if(sysUser!=null&&!StrUtil.isEmpty(sysUser.getScopeId())) {
    		Region region = regionService.getById(sysUser.getScopeId());
    		if(region!=null) {
    			sysUser.setParentArea(region.getPath());
    		}
    		
    	}
        return new Result<SysUser>().ok(sysUser);
    }

    @ApiOperation(value = "新增政务用户信息")
    @Log(title = "政务用户", businessType = BusinessType.INSERT)
    @PostMapping
    public Result<Boolean> add(@RequestBody SysUser user)
    {
    	if(user.getUserType()==null) throw new ServiceException("请选择负责区级");
    	if(user.getScopeId()==null) throw new ServiceException("请选择负责区域");
    	if(StrUtil.isEmpty(user.getPassword())) throw new ServiceException("请输入登录密码");
    	if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            throw new ServiceException("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
//		 if (StringUtils.isNotEmpty(user.getPhonenumber())){
//	    	 throw new ServiceException("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
//	     }
         user.setCreateBy(getUsername());
         user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
         
         userService.registerUser(user);
         

         //绑定角色(政务用户)
         sysRoleService.insertAuthUsers(3l, new Long[]{user.getUserId()});
         
        return new Result<Boolean>().ok(Boolean.TRUE);
    }

    @ApiOperation(value = "修改政务用户信息")
    @Log(title = "政务用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result<Boolean> edit(@RequestBody SysUser user)
    {
        return new Result<Boolean>().ok(userService.updateById(user));
    }

    @ApiOperation(value = "删除政务用户信息")
    @Log(title = "政务用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public Result<Boolean> remove(@PathVariable Integer[] ids)
    {
        return new Result<Boolean>().ok(userService.removeBatchByIds(Arrays.asList(ids)));
    }
    
}
