package com.yihu.jw.base.endpoint.user;

import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.base.service.user.UserService;
import com.yihu.jw.base.util.ConstantUtils;
import com.yihu.jw.entity.base.user.UserDO;
import com.yihu.jw.restmodel.base.user.UserVO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * Endpoint - 后台管理员
 * Created by progr1mmer on 2018/8/16.
 */
@RestController
@RequestMapping(value = BaseRequestMapping.User.PREFIX)
@Api(value = "用户管理", description = "用户管理服务接口", tags = {"wlyy基础服务 - 用户管理服务接口"})
public class UserEndpoint extends EnvelopRestEndpoint {

    @Autowired
    private UserService userService;

    @Value("${wechat.id}")
    private String wechatId;

    @PostMapping(value = BaseRequestMapping.User.CREATE)
    @ApiOperation(value = "创建")
    public Envelop create (
            @ApiParam(name = "jsonData", value = "Json数据", required = true)
            @RequestParam String jsonData) throws Exception {
        JSONObject jsonObject =  userService.createUser(jsonData);
        if (jsonObject.getString("response").equalsIgnoreCase(ConstantUtils.FAIL)) {
            return failed(jsonObject.getString("msg"));
        }
        return success(jsonObject.getString("msg"));
    }

    @PostMapping(value = BaseRequestMapping.User.DELETE)
    @ApiOperation(value = "删除")
    public Envelop delete(
            @ApiParam(name = "ids", value = "id串，中间用,分隔", required = true)
            @RequestParam(value = "ids") String ids) {
        userService.delete(ids.split(","));
        return success("删除成功");
    }

    @PostMapping(value = BaseRequestMapping.User.UPDATE)
    @ApiOperation(value = "更新")
    public Envelop update (
                @ApiParam(name = "jsonData", value = "Json数据")
                @RequestParam(value = "jsonData", required = false) String jsonData) throws Exception {
        //String jsonData = "{\"user\":{\"id\":\"2c9a80ed73b1d22b0173b35407710003\",\"createTime\":\"2020-08-03 15:58:15\",\"createUser\":\"123\",\"createUserName\":null,\"updateTime\":\"2020-08-03 16:20:58\",\"updateUser\":\"123\",\"updateUserName\":null,\"username\":\"15571028167\",\"password\":\"54a16e2a3f246ed11f890e479b279555\",\"salt\":\"O5eZc\",\"name\":\"sss\",\"gender\":null,\"idcard\":\"111111111111111111\",\"mobile\":\"15511111111\",\"email\":null,\"ak\":null,\"enabled\":true,\"locked\":false,\"lockedDate\":null,\"loginDate\":null,\"loginFailureCount\":0,\"saasId\":\"2c9a80ed719a6dcb0171a5dd1d700014\",\"roleId\":\"2c9a80ed72068fa2017207df3d460003\"},\"org\":[{\"orgCode\":\"3502120200\"},{\"orgCode\":\"3502120100\"},{\"orgCode\":\"3502120400\"},{\"orgCode\":\"3502120300\"},{\"orgCode\":\"3502120600\"},{\"orgCode\":\"3502120500\"},{\"orgCode\":\"3502120800\"},{\"orgCode\":\"3502120700\"},{\"orgCode\":\"3502120900\"},{\"orgCode\":\"3502130500\"},{\"orgCode\":\"3502130400\"},{\"orgCode\":\"3502130300\"},{\"orgCode\":\"3502130200\"},{\"orgCode\":\"3502130100\"},{\"orgCode\":\"3502050300\"},{\"orgCode\":\"3502050400\"},{\"orgCode\":\"3502050100\"},{\"orgCode\":\"3502050200\"},{\"orgCode\":\"3502060200\"},{\"orgCode\":\"3502060300\"},{\"orgCode\":\"3502060400\"},{\"orgCode\":\"3502060500\"},{\"orgCode\":\"3502060100\"},{\"orgCode\":\"3502031000\"},{\"orgCode\":\"3502030300\"},{\"orgCode\":\"3502030400\"},{\"orgCode\":\"3502030100\"},{\"orgCode\":\"3502030200\"},{\"orgCode\":\"3502030700\"},{\"orgCode\":\"iot-hospital\"},{\"orgCode\":\"3502030800\"},{\"orgCode\":\"3502030500\"},{\"orgCode\":\"3502030600\"},{\"orgCode\":\"3502030900\"}]}";
        JSONObject jsonObject =  userService.updateUser(jsonData);
        if (jsonObject.getString("response").equalsIgnoreCase(ConstantUtils.FAIL)) {
            return failed(jsonObject.getString("msg"));
        }
        return success(jsonObject.getString("msg"));
    }

    @GetMapping(value = BaseRequestMapping.User.PAGE)
    @ApiOperation(value = "获取分页")
    public PageEnvelop<UserVO> page (
            @ApiParam(name = "fields", value = "返回的字段，为空返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器，为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序，规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size) throws Exception {
        List<UserDO> userDOS = userService.search(fields, filters, sorts, page, size);
        int count = (int)userService.getCount(filters);
        return success(userDOS, count, page, size, UserVO.class);
    }

    @GetMapping(value = BaseRequestMapping.User.LIST)
    @ApiOperation(value = "获取列表")
    public ListEnvelop<UserVO> list (
            @ApiParam(name = "fields", value = "返回的字段，为空返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器，为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序，规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        List<UserDO> userDOS = userService.search(fields, filters, sorts);
        return success(userDOS, UserVO.class);
    }

    @GetMapping(value = BaseRequestMapping.User.CHECK_USERNAME)
    @ApiOperation(value = "检查用户名是否可用(message=available代表可用，message=inavailable代表不可用)")
    public Envelop checkName (
            @ApiParam(name = "username", value = "用户名", required = true)
            @RequestParam(value = "username", required = false) String username) throws Exception {
        if (userService.existUsername(username)) {
            return success("inavailable");
        } else {
            return success("available");
        }
    }

    @GetMapping(value = BaseRequestMapping.User.CHECK_MOBILE)
    @ApiOperation(value = "检查手机号是否可用(message=available代表可用，message=inavailable代表不可用)")
    public Envelop checkMobile (
            @ApiParam(name = "mobile", value = "手机号", required = true)
            @RequestParam(value = "mobile", required = false) String mobile) throws Exception {
        if (userService.existMobile(mobile)) {
            return success("inavailable");
        } else {
            return success("available");
        }
    }

    @GetMapping(value = BaseRequestMapping.User.findUserBaseInfo)
    @ApiOperation(value = "获取登录基本信息")
    public ObjEnvelop<Map<String,Object>> findUserBaseInfo(@ApiParam(name = "id", value = "用户id", required = true)
                                                               @RequestParam(value = "id", required = false)String id) throws Exception {
        return success(BaseRequestMapping.User.api_success,userService.findUserBaseInfo(id));
    }

    /**
     * 获取单个用户信息
     *
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping(value = BaseRequestMapping.User.queryOne)
    @ApiOperation(value = "获取单个用户信息")
    public Envelop doctorHosplist(
            @ApiParam(name = "id", value = "获取单个用户信息")
            @RequestParam(value = "id", required = true) String id) throws Exception {
        JSONObject jsonObject = userService.getOneUserInfo(id);
        if (jsonObject.getString("response").equalsIgnoreCase(ConstantUtils.FAIL)) {
            return failed(jsonObject.getString("msg"));
        }
        return success(jsonObject.getJSONObject("msg"));
    }

    /**
     * 获取用户管理机构树 省/市/区/机构 树形结构数据
     *
     * @param saasid
     * @return
     * @throws Exception
     */
    @GetMapping(value = BaseRequestMapping.User.orgTreeInfo)
    @ApiOperation(value = "获取用户管理机构树 省/市/区/机构 树形结构数据")
    public Envelop getOrgDutyTree(
            @ApiParam(name = "saasid", value = "saasid")
            @RequestParam(value = "saasid", required = false) String saasid,
            @ApiParam(name = "userId", value = "userId")
            @RequestParam(value = "userId", required = false) String userId,
            @ApiParam(name = "roleId", value = "roleId")
            @RequestParam(value = "roleId", required = false) String roleId) throws Exception {
        JSONObject jsonObject = userService.generateUserOrgTree(saasid,userId,roleId);
        if (jsonObject.getString("response").equalsIgnoreCase(ConstantUtils.FAIL)) {
            return failed(jsonObject.getString("msg"));
        }
        return success(jsonObject.get("msg"));
    }

    /**
     * 获取用户管理机构树 省/市/区/机构 树形结构数据
     * 新增社区树
     * @param saasid
     * @return
     * @throws Exception
     */
    @GetMapping(value = BaseRequestMapping.User.orgChoiceInfo)
    @ApiOperation(value = "获取用户管理机构树 省/市/区/机构 树形结构数据(新增社区树)")
    public Envelop orgChoiceInfo(
            @ApiParam(name = "saasid", value = "saasid")
            @RequestParam(value = "saasid", required = false) String saasid,
            @ApiParam(name = "userId", value = "userId")
            @RequestParam(value = "userId", required = false) String userId,
            @ApiParam(name = "roleId", value = "roleId")
            @RequestParam(value = "roleId", required = false) String roleId) throws Exception {
        JSONObject jsonObject = userService.orgChoiceInfo(saasid,userId,roleId);
        if (jsonObject.getString("response").equalsIgnoreCase(ConstantUtils.FAIL)) {
            return failed(jsonObject.getString("msg"));
        }
        return success(jsonObject.get("msg"));
    }

    /**
     * 获取用户信息列表
     *
     * @param saasid
     * @return
     * @throws Exception
     */
    @GetMapping(value = BaseRequestMapping.User.userInfoList)
    @ApiOperation(value = "获取用户信息列表")
    public PageEnvelop userInfoList(
            @ApiParam(name = "realName", value = "realName")
            @RequestParam(value = "realName", required = false) String realName,
            @ApiParam(name = "saasid", value = "saasid")
            @RequestParam(value = "saasid", required = false) String saasid,
            @ApiParam(name = "roleId", value = "roleId")
            @RequestParam(value = "roleId", required = false) String roleId,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size) throws Exception {
        JSONObject result = userService.userInfoList(realName,saasid, roleId,page,size,wechatId);
        return success(result.getJSONArray("msg"),result.getInteger("count"),page,size);
    }

    /**
     * 生效或失效某个用户
     *
     * @param id
     * @param status
     * @return
     * @throws Exception
     */
    @PostMapping(value = BaseRequestMapping.User.lockOrUnlock)
    @ApiOperation(value = "生效或失效某个用户")
    public Envelop enableOrDisableOrg(
            @ApiParam(name = "id", value = "用户标识")
            @RequestParam(value = "id", required = true) String id,
            @ApiParam(name = "status", value = "生效或失效标识")
            @RequestParam(value = "status", required = true) boolean status) throws Exception {
        JSONObject jsonObject =  userService.lockOrUnlocakUser(id, status);
        if (jsonObject.getString("response").equalsIgnoreCase(ConstantUtils.FAIL)) {
            return failed(jsonObject.getString("msg"));
        }
        return success(jsonObject.getString("response"));
    }


    @PostMapping(value = "enableOrDisable")
    @ApiOperation(value = "生效失效某个用户(新写接口-按钮)")
    public Envelop enableOrDisable(
            @ApiParam(name = "id", value = "用户标识")
            @RequestParam(value = "id", required = true) String id,
            @ApiParam(name = "status", value = "生效或失效标识")
            @RequestParam(value = "status", required = true) boolean status) throws Exception {
        JSONObject jsonObject =  userService.enableOrDisable(id, status);
        if (jsonObject.getString("response").equalsIgnoreCase(ConstantUtils.FAIL)) {
            return failed(jsonObject.getString("msg"));
        }
        return success(jsonObject.getString("response"));
    }


    /**
     * 重置密码
     *
     * @param id
     * @return
     * @throws Exception
     */
    @PostMapping(value = BaseRequestMapping.User.resetPwd)
    @ApiOperation(value = "重置密码")
    public Envelop resetPwd(
            @ApiParam(name = "id", value = "用户标识")
            @RequestParam(value = "id", required = true) String id) throws Exception {
        JSONObject jsonObject =  userService.resetPassword(id);
        if (jsonObject.getString("response").equalsIgnoreCase(ConstantUtils.FAIL)) {
            return failed(jsonObject.getString("msg"));
        }
        return success(jsonObject.getString("msg"));
    }
    
    @PostMapping(value = BaseRequestMapping.User.updatePwd)
    @ApiOperation(value = "修账号密码")
    public Envelop updatePwd(@ApiParam(name = "id", value = "用户ID")
                                  @RequestParam(value = "id", required = true)String id,
                                  @ApiParam(name = "pw", value = "密码")
                                  @RequestParam(value = "pw", required = true)String pw,
                                  @ApiParam(name = "orgPw", value = "原密码")
                                  @RequestParam(value = "orgPw", required = true)String orgPw)throws Exception{
        return success(userService.updatePwd(id,pw,orgPw));
    }
}
