package com.fs.his.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.ResponseResult;
import com.fs.common.core.domain.entity.SysRole;
import com.fs.common.core.domain.entity.SysUser;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.ParseUtils;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.StringUtils;
import com.fs.course.dto.BatchSendCourseDTO;
import com.fs.course.param.FsCourseLinkCreateParam;
import com.fs.course.service.IFsUserCompanyUserService;
import com.fs.course.service.IFsUserCourseService;
import com.fs.his.domain.FsUserAddress;
import com.fs.his.dto.FsUserDTO;
import com.fs.his.enums.FsUserIntegralLogTypeEnum;
import com.fs.his.mapper.FsUserMapper;
import com.fs.his.param.FsUserAddIntegralTemplateParam;
import com.fs.his.param.FsUserAddPointsParam;
import com.fs.his.param.FsUserParam;
import com.fs.his.service.IFsUserIntegralLogsService;
import com.fs.his.utils.PhoneUtil;
import com.fs.his.vo.FsUserExportListVO;
import com.fs.his.vo.FsUserVO;
import com.fs.his.vo.UserVo;
import com.fs.im.dto.OpenImResponseDTO;
import com.fs.im.service.OpenIMService;
import com.fs.qw.dto.UserProjectDTO;
import com.fs.store.param.h5.FsUserPageListParam;
import com.fs.store.vo.h5.FsUserPageListVO;
import com.fs.system.service.ISysRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.enums.BusinessType;
import com.fs.his.domain.FsUser;
import com.fs.his.service.IFsUserService;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.common.core.page.TableDataInfo;

import static com.fs.his.utils.PhoneUtil.*;

/**
 * 用户Controller
 *
 * @author fs
 * @date 2023-06-07
 */
@Slf4j
@RestController
@RequestMapping("/his/user")
public class FsUserController extends BaseController
{
    @Autowired
    private IFsUserService fsUserService;
    @Autowired
    private IFsUserIntegralLogsService userIntegralLogsService;
    @Autowired
    private IFsUserCompanyUserService userCompanyUserService;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 查询用户列表
     */
    @PreAuthorize("@ss.hasPermi('his:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsUserParam fsUser)
    {
        startPage();
        if (fsUser.getPhoneMk()!=null&&fsUser.getPhoneMk()!=""){
            fsUser.setPhone(encryptPhone(fsUser.getPhoneMk()));
        }
        if(StringUtils.isNotEmpty(fsUser.getPhone())){
            fsUser.setEncryptPhone(encryptPhone(fsUser.getPhone()));
        }
        List<FsUserVO> list = fsUserService.selectFsUserListVO(fsUser);
        SysRole sysRole = isCheckPermission();
        for (FsUserVO fsUserVO : list) {
            if(fsUserVO.getPhone() != null&&fsUserVO.getPhone()!=""){
                if (!(sysRole.getIsCheckPhone()==1)){
                    if (fsUserVO.getPhone().length()>11){
                        fsUserVO.setPhone(decryptPhoneMk(fsUserVO.getPhone()));
                    }else {
                        fsUserVO.setPhone(fsUserVO.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                    }
                } else {
                    if (fsUserVO.getPhone().length()>11) {
                        fsUserVO.setPhone(decryptPhone(fsUserVO.getPhone()));
                    }
                }
            }

        }
        return getDataTable(list);
    }

    /**
     * 导出用户列表
     */
    @PreAuthorize("@ss.hasPermi('his:user:export')")
    @Log(title = "用户", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsUserParam fsUser)
    {
        logger.info("导出用户列表:"+ SecurityUtils.getUserId());
        if (fsUserService.isEntityNull(fsUser)){
            return AjaxResult.error("请筛选数据导出");
        }
        Long count = fsUserService.selectFsUserExportListVOCount(fsUser);
        if (count>10000){
            return AjaxResult.error("导出数据不可超过1w条");
        }
        List<FsUserVO> list = fsUserService.selectFsUserListVO(fsUser);
        SysRole sysRole = isCheckPermission();
        List<FsUserDTO> listDTO = Lists.newArrayList();
        for (FsUserVO fsUserVO : list) {
            if(fsUserVO.getPhone() != null&&fsUserVO.getPhone()!=""){
                if (!(sysRole.getIsCheckPhone()==1)){
                    if (fsUserVO.getPhone().length()>11){
                        fsUserVO.setPhone(decryptPhoneMk(fsUserVO.getPhone()));
                    }else {
                        fsUserVO.setPhone(fsUserVO.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                    }
                } else {
                    if (fsUserVO.getPhone().length()>11) {
                        fsUserVO.setPhone(decryptPhone(fsUserVO.getPhone()));
                    }
                }
            }
            FsUserDTO fsUserDTO = new FsUserDTO();
            BeanUtils.copyProperties(fsUserVO,fsUserDTO);
            listDTO.add(fsUserDTO);
        }
        ExcelUtil<FsUserDTO> util = new ExcelUtil<FsUserDTO>(FsUserDTO.class);
        return util.exportExcel(listDTO, "用户数据");
    }

    @Autowired
    private ISysRoleService sysRoleService;
    private SysRole isCheckPermission() {
        SysRole sysRole = new SysRole();
        SysUser user = getLoginUser().getUser();
        boolean flag = user.isAdmin();
        if (flag) {
            sysRole.setIsCheckPhone(1);
            sysRole.setIsCheckAddress(1);
        } else {
            List<SysRole> roles = user.getRoles();
            if (roles != null && !roles.isEmpty()) {
                Long[] roleIds = roles.stream().map(SysRole::getRoleId).toArray(Long[]::new);
                return sysRoleService.getIsCheckPermission(roleIds);
            }
        }
        return sysRole;
    }

    @PreAuthorize("@ss.hasPermi('his:user:list')")
    @GetMapping("/listProject")
    public TableDataInfo listProject(FsUser fsUser)
    {
        startPage();
        if(StringUtils.isNotEmpty(fsUser.getPhone())){
            fsUser.setPhone(encryptPhone(fsUser.getPhone()));
        }
        if(StringUtils.isNotEmpty(fsUser.getCompanyUserIdMulti())){
            String[] split = fsUser.getCompanyUserIdMulti().split(",");
            fsUser.setCompanyUserIds(split);
        }
//        List<FsUserVO> list = fsUserService.selectFsUserVOListByProject(fsUser);

        // xgb sql执行太慢，优化修改
        List<FsUserVO> list = fsUserService.selectFsUserVOListByProjectNew(fsUser);

        SysRole sysRole = isCheckPermission();
        for (FsUserVO fsUserVO : list) {
            if(fsUserVO.getPhone() != null&&fsUserVO.getPhone()!=""){
                if (!(sysRole.getIsCheckPhone()==1)){
                    if (fsUserVO.getPhone().length()>11){
                        fsUserVO.setPhone(decryptPhoneMk(fsUserVO.getPhone()));
                    }else {
                        fsUserVO.setPhone(fsUserVO.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                    }
                } else {
                    if (fsUserVO.getPhone().length()>11) {
                        fsUserVO.setPhone(decryptPhone(fsUserVO.getPhone()));
                    }
                }
            }
        }
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('his:user:export')")
    @GetMapping("/exportListProject")
    public AjaxResult exportListProject(FsUser fsUser)
    {
        if(StringUtils.isNotEmpty(fsUser.getPhone())){
            fsUser.setPhone(encryptPhone(fsUser.getPhone()));
        }
        List<FsUserVO> list = fsUserService.selectFsUserVOListByProject(fsUser);
        SysRole sysRole = isCheckPermission();
        for (FsUserVO fsUserVO : list) {
            if(fsUserVO.getPhone() != null&&fsUserVO.getPhone()!=""){
                if (!(sysRole.getIsCheckPhone()==1)){
                    if (fsUserVO.getPhone().length()>11){
                        fsUserVO.setPhone(decryptPhoneMk(fsUserVO.getPhone()));
                    }else {
                        fsUserVO.setPhone(fsUserVO.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                    }
                } else {
                    if (fsUserVO.getPhone().length()>11) {
                        fsUserVO.setPhone(decryptPhone(fsUserVO.getPhone()));
                    }
                }
            }
        }
        ExcelUtil<FsUserVO> util = new ExcelUtil<FsUserVO>(FsUserVO.class);
        return util.exportExcel(list, "项目会员数据");
    }

    /**
     * 获取用户详细信息
     */
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId)
    {
        FsUser fsUser = fsUserService.selectFsUserByUserId(userId);
        fsUser.setPhone(decryptAutoPhoneMk(fsUser.getPhone()));
        return AjaxResult.success(fsUser);
    }

    @GetMapping(value = "/getUserAddr/{userId}")
    public AjaxResult getUserAddr(@PathVariable("userId") Long userId)
    {

        List<FsUserAddress> fsUserAddresses = fsUserService.selectFsUserAddressByUserId(userId);
        for (FsUserAddress fsUserAddress : fsUserAddresses) {
            if (fsUserAddress.getPhone()!=null&&fsUserAddress.getPhone()!=""){
                if (fsUserAddress.getPhone().length()>11){
                    fsUserAddress.setPhone(decryptPhoneMk(fsUserAddress.getPhone()));
                }else {
                    fsUserAddress.setPhone(fsUserAddress.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
            }
        }

        return AjaxResult.success(fsUserAddresses);
    }


    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('his:user:add')")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsUser fsUser)
    {
        return toAjax(fsUserService.insertFsUser(fsUser));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('his:user:edit')")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsUser fsUser)
    {
        return toAjax(fsUserService.updateFsUser(fsUser));
    }

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

    /**
     * 删除微信用户和销售关系信息
     */
    @PreAuthorize("@ss.hasPermi('his:userCompanyUser:remove')")
    @Log(title = "微信用户和销售关系", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable Long id)
    {
        return toAjax(userCompanyUserService.deleteFsUserCompanyUserById(id));
    }

    /**
     * 查询用户
     */
    @GetMapping("user/list/{name}")
    public TableDataInfo userlist(@PathVariable("name")String name)
    {
        List<UserVo> list = fsUserService.selectUserVOList(name);
        if (list==null||list.size()==0){
            String s = encryptPhone(name);
            list = fsUserService.selectUserVOList(s);
        }
        return getDataTable(list);
    }

    @GetMapping("/listBySearch")
    public R listBySearch(FsUser user)
    {
        if (Objects.nonNull(user) && StringUtils.isNotBlank(user.getPhone())){
            user.setPhone(PhoneUtil.encryptPhone(user.getPhone()));
        }
        List<FsUser> list = fsUserService.selectFsUserList(user);
        return R.ok().put("data",list);
    }

    @PreAuthorize("@ss.hasPermi('his:user:darkRoomList')")
    @GetMapping("/darkRoomList")
    @ApiOperation("小黑屋")
    public R darkRoomList(FsUserPageListParam param) {
//        startPage();
//        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        //判断是否是电话号码
        if(StringUtils.isFullNumber(param.getKeyword()) && param.getKeyword().trim().length() == 11){
            param.setKeyword(encryptPhone(param.getKeyword()));
        }
        PageInfo<FsUserPageListVO> fsUserPageListVOPageInfo = fsUserService.selectFsUserPageList(param);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", fsUserPageListVOPageInfo.getList());
        map.put("total", fsUserPageListVOPageInfo.getTotal());
        return R.ok(map);
    }

    @PreAuthorize("@ss.hasPermi('his:user:enabledUsers')")
    @PostMapping("/enabledUsers")
    @ApiOperation("批量启用会员")
    public ResponseResult<Boolean> enabledUsers(@RequestBody List<UserProjectDTO> ids) {
        log.debug("批量启用会员 ids: {}", JSON.toJSONString(ids));
        Boolean r = userCompanyUserService.batchUpdateUserProjectStatus(ids, 1);
        return ResponseResult.ok(r);
    }

    @PreAuthorize("@ss.hasPermi('his:user:blacklist')")
    @GetMapping("/blacklist")
    @ApiOperation("黑名单")
    public R blacklist(FsUserPageListParam param) {
        //判断是否是电话号码
        if(StringUtils.isFullNumber(param.getKeyword()) && param.getKeyword().trim().length() == 11){
            param.setKeyword(encryptPhone(param.getKeyword()));
        }
        PageInfo<FsUserPageListVO> fsUserPageListVOPageInfo = fsUserService.selectFsUserPageList(param);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", fsUserPageListVOPageInfo.getList());
        map.put("total", fsUserPageListVOPageInfo.getTotal());
        return R.ok(map);
    }

    @PreAuthorize("@ss.hasPermi('his:user:enabledBlackUsers')")
    @PostMapping("/enabledBlackUsers")
    @ApiOperation("批量启用会员")
    public ResponseResult<Boolean> enabledBlackUsers(@RequestBody List<UserProjectDTO> ids) {
        log.debug("批量启用会员 ids: {}", JSON.toJSONString(ids));
        Boolean r = userCompanyUserService.batchUpdateUserProjectStatus(ids, 1);
        return ResponseResult.ok(r);
    }

    @PreAuthorize("@ss.hasPermi('his:user:addPoints')")
    @PostMapping("/addPoints")
    @ApiOperation("添加积分")
    public R addPoints(@RequestBody @Validated FsUserAddPointsParam param) {
        FsUserAddIntegralTemplateParam integralTemplateParam = new FsUserAddIntegralTemplateParam();
        integralTemplateParam.setUserId(param.getUserId());
        integralTemplateParam.setLogType(FsUserIntegralLogTypeEnum.TYPE_23.getValue());
        integralTemplateParam.setBusinessId(SecurityUtils.getUserId().toString());
        integralTemplateParam.setPoints(param.getPoint());
        integralTemplateParam.setRemark(param.getRemark());
        return userIntegralLogsService.addIntegralTemplate(integralTemplateParam);
    }

    @PreAuthorize("@ss.hasPermi('his:user:unbind')")
    @Log(title = "批量解绑会员（删除销售和会员的关系）", businessType = BusinessType.DELETE)
    @DeleteMapping("/batchUnbind")
    public AjaxResult batchUnbind(@RequestBody List<Long> userIds){
        if(!userIds.isEmpty()){
            return toAjax(userCompanyUserService.batchUnbind(userIds));
        } else {
            return error("请先选择会员");
        }
    }

}
