package com.fs.hospital.controller.hospital;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.annotation.Log;
import com.fs.common.constant.UserConstants;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.hospital.domain.Hospital;
import com.fs.hospital.domain.HospitalPost;
import com.fs.hospital.domain.HospitalRole;
import com.fs.hospital.domain.HospitalUser;
import com.fs.hospital.dto.UserPriceDTO;
import com.fs.hospital.service.IHospitalPostService;
import com.fs.hospital.service.IHospitalRoleService;
import com.fs.hospital.service.IHospitalService;
import com.fs.hospital.service.IHospitalUserService;
import com.fs.hospital.vo.HospitalUserListHVO;
import com.fs.hospital.vo.HospitalUserHVO;
import com.fs.framework.security.LoginUser;
import com.fs.framework.security.SecurityUtils;
import com.fs.framework.service.TokenService;
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.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 企业员工信息Controller
 *
 * @author fs
 * @date 2021-10-04
 */
@RestController
@RequestMapping("/hospital/user")
public class HospitalUserController extends BaseController
{
    @Autowired
    private IHospitalRoleService roleService;

    @Autowired
    private IHospitalPostService postService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IHospitalUserService hospitalUserService;
    @Autowired
    private IHospitalService hospitalService;

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(HospitalUser user)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        user.setHospitalId(loginUser.getHospital().getHospitalId());
        startPage();
        List<HospitalUserListHVO> list = hospitalUserService.selectHospitalUserListVO(user);
        return getDataTable(list);
    }
    @GetMapping("/getUserList")
    public R getUserList()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        HospitalUser map = new HospitalUser();
        map.setHospitalId(loginUser.getHospital().getHospitalId());
        List<HospitalUser> list = hospitalUserService.selectHospitalUserList(map);
        return  R.ok().put("data",list);
    }
    @GetMapping("/getList")
    public TableDataInfo getList(HospitalUser user)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        user.setHospitalId(loginUser.getHospital().getHospitalId());
        startPage();
        List<HospitalUser> list = hospitalUserService.selectHospitalUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('hospital:user:export')")
    @GetMapping("/export")
    public AjaxResult export(HospitalUser user)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        user.setHospitalId(loginUser.getHospital().getHospitalId());
        List<HospitalUser> list = hospitalUserService.selectHospitalUserList(user);
        ExcelUtil<HospitalUser> util = new ExcelUtil<HospitalUser>(HospitalUser.class);
        return util.exportExcel(list, "用户数据");
    }



    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('hospital:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        HospitalRole hospitalRoleMap=new HospitalRole();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        hospitalRoleMap.setHospitalId(loginUser.getHospital().getHospitalId());
        List<HospitalRole> roles = roleService.selectHospitalRoleList(hospitalRoleMap);

        ajax.put("roles", HospitalUser.isAdmin(loginUser.getUser().getUserType()) ? roles : roles.stream().filter(r -> r.getRoleKey()!="admin").collect(Collectors.toList()));

        HospitalPost postMap=new HospitalPost();
        postMap.setHospitalId(loginUser.getHospital().getHospitalId());
        ajax.put("posts", postService.selectHospitalPostList(postMap));
        if (StringUtils.isNotNull(userId))
        {
            HospitalUser hospitalUser=hospitalUserService.selectHospitalUserByUserId(userId);
            ajax.put(AjaxResult.DATA_TAG, hospitalUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('hospital:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody HospitalUser user)
    {
        JSONObject jsonObject = JSON.parseObject(user.getPriceJson());
        if (jsonObject.isEmpty()){
            return AjaxResult.error("价格配置不能为空");
        }
        //判断用户数量是否已达到上线
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Integer count=hospitalUserService.selectHospitalUserCountByHospitalId(loginUser.getHospital().getHospitalId());
        Hospital hospital = hospitalService.selectHospitalByHospitalId(loginUser.getHospital().getHospitalId());

        if(count>hospital.getLimitUserCount()){
            return AjaxResult.error("用户数量已达到上限");
        }
        user.setHospitalId(loginUser.getHospital().getHospitalId());
        if (UserConstants.NOT_UNIQUE.equals(hospitalUserService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setCreateTime(new Date());
        user.setUserType("01");//一般用户
        return toAjax(hospitalUserService.insertHospitalUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('hospital:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody HospitalUser user)
    {
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(hospitalUserService.updateHospitalUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('hospital:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(hospitalUserService.deleteHospitalUserByUserIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('hospital:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody HospitalUser user)
    {
        return toAjax(hospitalUserService.resetUserPwdByUserId(user.getUserId(), SecurityUtils.encryptPassword(user.getPassword())));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('hospital:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody HospitalUser user)
    {
        //管理员的状态不能修改
        HospitalUser hospitalUser=hospitalUserService.selectHospitalUserByUserId(user.getUserId());
        if(hospitalUser.isAdmin()){
            return AjaxResult.error("不能修改管理员状态");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(hospitalUserService.updateHospitalUser(user));
    }


    /**
     * 获取通讯录
     * @param user
     * @return
     */
    @GetMapping("/getAddressBookList")
    public TableDataInfo getAddressBookList(HospitalUser user)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        user.setHospitalId(loginUser.getHospital().getHospitalId());
        List<HospitalUserHVO> list = hospitalUserService.selectMyUserList(user);
        return getDataTable(list);
    }


//    @GetMapping("/getAllUserlist")
//    public R getAllUserlist()
//    {
//        HospitalUser map=new HospitalUser();
//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        map.setHospitalId(loginUser.getHospital().getHospitalId());
//        map.setStatus("1");
//        List<HospitalUser> list = hospitalUserService.selectHospitalUserList(map);
//        return R.ok().put("data",list);
//    }

    @GetMapping("/getUserListByDeptId")
    public R getUserListByDeptId(HospitalUser user)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        user.setHospitalId(loginUser.getHospital().getHospitalId());

        List<HospitalUser> list = hospitalUserService.getUserListByDeptId(user);
        return R.ok().put("data",list);
    }

    @GetMapping("/isDoctorList")
    public R isDoctorList()
    {
        HospitalUser user = new HospitalUser();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        user.setHospitalId(loginUser.getHospital().getHospitalId());
        user.setIsDoctor(1);
        List<HospitalUserListHVO> list = hospitalUserService.selectHospitalUserListVO(user);
        return R.ok().put("data",list);
    }
}
