package com.sqx.modules.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.LoginUser;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.form.UpdateUserTypeForm;
import com.sqx.modules.app.response.HomeMessageResponse;
import com.sqx.modules.app.response.UserMessageResponse;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.pay.service.PayDetailsService;
import com.sqx.modules.resumes.entity.Company;
import com.sqx.modules.resumes.entity.Resumes;
import com.sqx.modules.resumes.service.CompanyService;
import com.sqx.modules.resumes.service.ResumesService;
import com.sqx.modules.utils.SenInfoCheckUtil;
import com.sqx.modules.utils.excel.ExcelData;
import com.sqx.modules.utils.excel.ExportExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.catalina.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author fang
 * @date 2020/7/30
 */
@RestController
@Api(value = "用户管理", tags = {"用户管理"})
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private PayDetailsService payDetailsService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private ResumesService resumesService;
    @Autowired
    private CommonInfoService commonInfoService;
    
    @PostMapping("/saveUser")
    @ApiOperation("系统添加用户")
    public Result saveUser(@RequestBody UserEntity userEntity){
        return userService.saveUser(userEntity);
    }

    @PostMapping("/updateUserType")
    @ApiOperation("管理端修改用户类型")
    public Result updateUserType(@RequestBody UpdateUserTypeForm updateUserTypeForm){
        return userService.updateUserType(updateUserTypeForm);
    }

    @PostMapping("/updateUserViewResumes")
    @ApiOperation("修改查看简历次数")
    public Result updateUserViewResumes(Long userId, Integer num) {
        UserEntity userEntity = userService.selectUserById(userId);
        userService.updateById(userEntity);
        return Result.success();
    }

    @PostMapping("/updateUserResumes")
    @ApiOperation("修改用户入职状态")
    public Result updateUserResumes(String userIds, Integer status, String auditContent) {
        String value = commonInfoService.findOne(310).getValue();
        for (String id : userIds.split(",")) {
            Long userId = Long.parseLong(id);
            UserEntity user = userService.selectUserById(userId);
            user.setAuditContent(auditContent);
            userService.updateById(user);
            List<String> msgList = new ArrayList<>();
            msgList.add("用户状态修改通知");
            if (status == 1) {
                Resumes resumes = resumesService.selectResumesByUserId(userId);
                resumes.setStatus(2);
                resumesService.updateById(resumes);
                msgList.add("你的状态已改为待入职！");
            } else {
                msgList.add("审核未通过！");
            }
            msgList.add(DateUtils.format(new Date()));
            SenInfoCheckUtil.sendMsg(user.getOpenId(), value, msgList, 3, null);
        }

        return Result.success();
    }


    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    @ApiOperation("获取用户详细信息")
    @ResponseBody
    public Result selectUserById(@ApiParam("用户id") @PathVariable Long userId) {
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = userService.queryByUserId(userId);
        if (userEntity.getUserType() == 2) {
            Company company = companyService.getOne(new QueryWrapper<Company>().eq("user_id", userEntity.getUserId()));
            if (company != null) {
                userEntity.setCompanyId(company.getCompanyId());
            }
        }
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        //查询本月充值
        Double consume = payDetailsService.instantselectSumPay(date, userId);
        //查询本月提现
        Double income = userMoneyDetailsService.monthIncome(date, userId);
        //查询邀请人数
        int count = userService.queryInviterCount(userEntity.getInvitationCode());
        Company company = companyService.selectCompanyByUserId(userId);
        map.put("company", company);
        map.put("userEntity", userEntity);
        map.put("money", userMoney);
        map.put("consume", consume);
        map.put("income", income);
        map.put("count", count);
        return Result.success().put("data", map);
    }

    @RequestMapping(value = "/selectUserByInvitationCode", method = RequestMethod.GET)
    @ApiOperation("获取用户详细信息")
    @ResponseBody
    public Result selectUserByInvitationCode(String invitationCode) {
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = userService.queryByInvitationCode(invitationCode);
        Long userId=userEntity.getUserId();
        if (userEntity.getUserType() == 2) {
            Company company = companyService.getOne(new QueryWrapper<Company>().eq("user_id", userEntity.getUserId()));
            if (company != null) {
                userEntity.setCompanyId(company.getCompanyId());
            }
        }
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        //查询本月充值
        Double consume = payDetailsService.instantselectSumPay(date, userId);
        //查询本月提现
        Double income = userMoneyDetailsService.monthIncome(date, userId);
        //查询邀请人数
        int count = userService.queryInviterCount(userEntity.getInvitationCode());
        Company company = companyService.selectCompanyByUserId(userId);
        map.put("company", company);
        map.put("userEntity", userEntity);
        map.put("money", userMoney);
        map.put("consume", consume);
        map.put("income", income);
        map.put("count", count);
        return Result.success().put("data", map);
    }

    @RequestMapping(value = "/addCannotMoney/{userId}/{money}/{type}", method = RequestMethod.POST)
    @ApiOperation("修改金额")
    @ResponseBody
    public Result addCannotMoney(@PathVariable("userId") Long userId, @PathVariable("money") Double money, @PathVariable("type") Integer type) {
        if (type == 1) {
            userMoneyService.updateMoney(1, userId, BigDecimal.valueOf(money));
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setMoney(BigDecimal.valueOf(money));
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setContent("系统充值：" + money);
            userMoneyDetails.setTitle("系统充值金额");
            userMoneyDetails.setType(1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
        } else {
            userMoneyService.updateMoney(2, userId, BigDecimal.valueOf(money));
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setMoney(BigDecimal.valueOf(money));
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setContent("系统减少：" + money);
            userMoneyDetails.setTitle("系统减少金额");
            userMoneyDetails.setType(2);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
        }
        return Result.success();
    }

    @RequestMapping(value = "/updateCustomizationMoney/{userId}/{money}/{type}", method = RequestMethod.POST)
    @ApiOperation("修改金额")
    @ResponseBody
    public Result updateCustomizationMoney(@PathVariable("userId") Long userId, @PathVariable("money") Double money, @PathVariable("type") Integer type) {
        if (type == 1) {
            userMoneyService.updateCustomizationMoney(1, userId, BigDecimal.valueOf(money));
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setMoney(BigDecimal.valueOf(money));
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setContent("系统增加定制化钻石：" + money);
            userMoneyDetails.setTitle("系统增加定制化抵扣钻石");
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(2);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
        } else {
            userMoneyService.updateCustomizationMoney(2, userId, BigDecimal.valueOf(money));
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setMoney(BigDecimal.valueOf(money));
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setContent("系统减少定制化钻石：" + money);
            userMoneyDetails.setTitle("系统增加定制化抵扣钻石");
            userMoneyDetails.setType(2);
            userMoneyDetails.setClassify(2);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
        }
        return Result.success();
    }


    @RequestMapping(value = "/selectUserList", method = RequestMethod.GET)
    @ApiOperation("查询所有用户列表")
    @ResponseBody
    public Result selectUserList(Integer page, Integer limit,String startTime, String endTime,
                                 UserEntity userEntity) {
        return Result.success().put("data", userService.selectUserPage(page, limit, startTime,  endTime, userEntity));
    }


    @RequestMapping(value = "/getNotHasCompanyUserList", method = RequestMethod.GET)
    @ApiOperation("获取所有未绑定企业的用户")
    @ResponseBody
    public Result getNotHasCompanyUserList(Integer page, Integer limit,UserEntity userEntity){
        return Result.success().put("data", userService.getNotHasCompanyUserList(page, limit,userEntity));
    }

    @ApiOperation("导出用户")
    @GetMapping(value = "exportExcelUser")
    public void exportExcelIndent(String startTime,String endTime, UserEntity userEntity, HttpServletResponse response) throws Exception {
        ExcelData excelData = userService.exportExcelUser(startTime,endTime,userEntity);
        ExportExcelUtils.exportExcel(response, "用户列表.xlsx", excelData);
    }



    @RequestMapping(value = "/deleteUserByUserId/{userId}", method = RequestMethod.POST)
    @ApiOperation("删除用户")
    @ResponseBody
    public Result deleteUserByUserId(@PathVariable("userId") Long userId) {
        userService.removeById(userId);
        return Result.success();
    }

    @RequestMapping(value = "/updateUserByUserId", method = RequestMethod.POST)
    @ApiOperation("修改用户")
    @ResponseBody
    public Result updateUserByUserId(@RequestBody UserEntity userEntity) {
        if (StringUtils.isNotBlank(userEntity.getPhone())){
            int count = userService.count(new QueryWrapper<UserEntity>().eq("phone", userEntity.getPhone()).ne("user_id", userEntity.getUserId()));
            if (count>=1){
                return Result.error("当前手机号已存在");
            }
        }
        userService.updateById(userEntity);
        return Result.success();
    }

    @RequestMapping(value = "/updateUserStatusByUserId", method = RequestMethod.GET)
    @ApiOperation("禁用或启用用户")
    @ResponseBody
    public Result updateUserByUserId(Long userId) {
        UserEntity byId = userService.getById(userId);
        if (byId.getStatus().equals(1)) {
            byId.setStatus(2);
        } else {
            byId.setStatus(1);
        }
        userService.updateById(byId);
        return Result.success();
    }


    /**
     * 获取openid
     *
     * @param code 微信code
     * @return openid
     */
    @GetMapping("/openId/{code:.+}/{userId}")
    @ApiOperation("根据code获取openid")
    public Result getOpenid(@PathVariable("code") String code, @PathVariable("userId") Long userId) {
        return userService.getOpenId(code, userId);
    }

    /**
     * 信息分析
     *
     * @return
     */
    @GetMapping("/homeMessage")
    @ApiOperation("信息分析")
    public Result homeMessage() {
        HomeMessageResponse homeMessageResponse = new HomeMessageResponse();
        //   0查总   1查天  2查月  3查年
        //企业总用户
        homeMessageResponse.setTotalUsers(userService.queryUserCount(0, null, 2));
        //企业今日新增
        homeMessageResponse.setNewToday(userService.queryUserCount(1, null, 2));
        //个人总数
        homeMessageResponse.setNewMonth(userService.queryUserCount(0, null, 1));
        //个人今日新增
        homeMessageResponse.setNewYear(userService.queryUserCount(1, null, 1));

        //设置总收入
        homeMessageResponse.setTotalRevenue(userService.queryPayMoney(0));
        //设置今日收入
        homeMessageResponse.setTodayRevenue(userService.queryPayMoney(1));
        //设置本月收入
        homeMessageResponse.setMonthRevenue(userService.queryPayMoney(2));
        //设置本年收入
        homeMessageResponse.setYearRevenue(userService.queryPayMoney(3));

        return Result.success().put("data", homeMessageResponse);
    }

    /**
     * 接单分析
     *
     * @return
     */
    @GetMapping("/takingOrdersMessage")
    @ApiOperation("接单分析")
    public Result takingOrdersMessage(Long page, Long limit, String date, Long type) {
        Page<Map<String, Object>> iPage = new Page<>(page, limit);
        return userService.takingOrdersMessage(iPage, type, date);
    }

    /**
     * 用户分析
     */
    /*@GetMapping("/userMessage")
    @ApiOperation("用户分析")
    public Result userMessage(String date, int type) {
        UserMessageResponse userMessageResponse = new UserMessageResponse();
        userMessageResponse.setTotalNumber(userService.queryUserCount(type, date));
        userMessageResponse.setVipUserNumber(userService.userMessage(date, type));
        userMessageResponse.setUserNumber(userService.queryUserCount(type, date) - userService.userMessage(date, type));
        return Result.success().put("data", userMessageResponse);
    }*/
}