package com.yunzhi.marketing.channel.sysChannel.controller;

import com.alibaba.fastjson.JSONObject;
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.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.center.sysUser.entity.SysToken;
import com.yunzhi.marketing.center.sysUser.entity.SysUser;
import com.yunzhi.marketing.center.sysUser.service.ISysTokenService;
import com.yunzhi.marketing.center.sysUser.service.ISysUserService;
import com.yunzhi.marketing.center.taUser.entity.TaUser;
import com.yunzhi.marketing.center.taUser.service.ITaUserService;
import com.yunzhi.marketing.channel.sysChannel.entity.TaChannelProxy;
import com.yunzhi.marketing.channel.sysChannel.service.ITaChannelProxyService;
import com.yunzhi.marketing.common.CommConstant;
import com.yunzhi.marketing.common.JWTUtils;
import com.yunzhi.marketing.common.MD5Utils;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.entity.TaChannelAppRelation;
import com.yunzhi.marketing.service.ITaChannelAppRelationService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
    * 系统用户 系统中心账户 前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-09-11
 */
@RestController
@RequestMapping("/api")
public class SysUserChannelController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(SysUserChannelController.class);

    @Autowired
    public ISysUserService iSysUserService;
    
    @Autowired
    private ISysTokenService sysTokenService;

    @Autowired
    private ITaUserService iTaUserService;

    @Autowired
    private ITaChannelProxyService iTaChannelProxyService;

    @Autowired
    private ITaChannelAppRelationService iTaChannelAppRelationService;

    /**
     * 修改对象
     * @param sysUser 实体对象
     * @return
     */
    @RequestMapping(value="/channel/sysUser",method= RequestMethod.PUT)
    public ResponseBean sysUserUpdate(@RequestBody SysUser sysUser, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            String userName = JWTUtils.getSubject(request);
            sysUser.setPassword(MD5Utils.md5(sysUser.getPassword()));
            sysUser.setUserName(userName);
            if (iSysUserService.updateById(sysUser)){
                responseBean.addSuccess(sysUser);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("sysUserUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    @PostMapping("/channel/signin")
    public ResponseBean signinChannel(@RequestBody String paramStr) {
        JSONObject params = JSONObject.parseObject(paramStr);
        if (params == null) {
            return ResponseBean.error("非法参数", ResponseBean.ERROR_MISSING_PARAMS);
        }

        String userName = params.getString("userName");
        String userPassword = params.getString("password");

        //验证用户名密码是否正确
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("user_name",userName);
        sysUserQueryWrapper.eq("password", MD5Utils.md5(userPassword));
        sysUserQueryWrapper.eq("type", CommConstant.LOGIN_TYPE_CHANNEL);
        SysUser sysUser = iSysUserService.getOne(sysUserQueryWrapper);
        if (sysUser == null) {
            return ResponseBean.error("用户名或密码错误", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        if (sysUser.getStatus() != CommConstant.STATUS_NORMAL) {
            return ResponseBean.error("用户状态异常", ResponseBean.ERROR_UNAVAILABLE);
        }

        Map map = new HashMap();
        map.put("userName", sysUser.getUserName());
        map.put("userId",sysUser.getUserId());

        String token = JWTUtils.newTokenByMap(map);

        //保存token
        sysTokenService.saveToken(token);

        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", sysUser);

        return ResponseBean.success(result);
    }

    @PostMapping("/channel/signout")
    public ResponseBean signoutChannel(HttpServletRequest request) {
        String token = JWTUtils.getToken(request);
        QueryWrapper<SysToken> sysTokenQueryWrapper = new QueryWrapper<>();
        sysTokenQueryWrapper.eq("token",token);
        sysTokenService.remove(sysTokenQueryWrapper);
        return ResponseBean.success("成功退出");
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/channel/current",method=RequestMethod.GET)
    public ResponseBean currentChannelUser(HttpServletRequest request){
        String userName = getSysUserName(request);
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("user_name",userName);
        sysUserQueryWrapper.eq("type",CommConstant.LOGIN_TYPE_CHANNEL);
        SysUser sysUser = iSysUserService.getOne(sysUserQueryWrapper);
        sysUser.setPassword(null);

        return ResponseBean.success(sysUser);
    }

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/channel/taChannel",method= RequestMethod.GET)
    public ResponseBean taUserList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                   @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage pg = new Page<>(pageNum, pageSize);
            IPage<TaChannelProxy> result = iTaChannelProxyService.getChannelList(pg);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taUserList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 新增代理商
     * @param taChannelProxy
     * @param request
     * @return
     */
    @RequestMapping(value="/channel/taChannel",method= RequestMethod.POST)
    public ResponseBean taUserList(@RequestBody TaChannelProxy taChannelProxy, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (taChannelProxy.getAppMaxNum() != null && taChannelProxy.getAppMaxNum() <= 0){
                responseBean.addError("维护小程序数量不得小于0");
                return responseBean;
            }
            if (StringUtils.isEmpty(taChannelProxy.getUserName())){
                taChannelProxy.setUserName(taChannelProxy.getChannelTel());
            }

            QueryWrapper<TaChannelProxy> userNameQueryWrapper = new QueryWrapper<>();
            userNameQueryWrapper.eq("user_name", taChannelProxy.getUserName());
            Integer countUserName = iTaChannelProxyService.count(userNameQueryWrapper);
            if (countUserName > 0){
                responseBean.addError("账户名已存在");
                return responseBean;
            }


            QueryWrapper<TaChannelProxy> taChannelProxyQueryWrapper = new QueryWrapper<>();
            taChannelProxyQueryWrapper.eq("channel_tel", taChannelProxy.getChannelTel());
            Integer countChannel = iTaChannelProxyService.count(taChannelProxyQueryWrapper);
            if (countChannel > 0){
                responseBean.addError("手机号已存在");
                return responseBean;
            }
            taChannelProxy.setPassword(MD5Utils.md5(MD5Utils.md5("abc@123")));
            taChannelProxy.setStatus(1);
            taChannelProxy.setCreateTime(LocalDateTime.now());
            iTaChannelProxyService.save(taChannelProxy);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taUserList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/channel/taChannel/{id}",method= RequestMethod.GET)
    public ResponseBean getChannelProxyById(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        QueryWrapper<TaChannelProxy> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("channel_id", id);
        TaChannelProxy taChannelProxy = iTaChannelProxyService.getOne(queryWrapper);
        responseBean.addSuccess(taChannelProxy);
        return responseBean;
    }

    /**
     * 修改对象
     * @param id
     * @param taChannelProxy
     * @param request
     * @return
     */
    @RequestMapping(value="/channel/taChannel/{id}",method= RequestMethod.PUT)
    public ResponseBean taNewsTypeUpdate(@PathVariable Integer id,
                                         @RequestBody TaChannelProxy taChannelProxy, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        if (taChannelProxy.getAppMaxNum() != null && taChannelProxy.getAppMaxNum() <= 0){
            responseBean.addError("维护小程序数量不得小于0");
            return responseBean;
        }

        if (StringUtils.isEmpty(taChannelProxy.getUserName())){
            taChannelProxy.setUserName(taChannelProxy.getChannelTel());
        }

        QueryWrapper<TaChannelProxy> userNameQueryWrapper = new QueryWrapper<>();
        userNameQueryWrapper.eq("user_name", taChannelProxy.getUserName());
        userNameQueryWrapper.ne("channel_id", id);
        Integer countUserName = iTaChannelProxyService.count(userNameQueryWrapper);
        if (countUserName > 0){
            responseBean.addError("账户名已存在");
            return responseBean;
        }

        taChannelProxy.setExpireDate(taChannelProxy.getExpireDate().plusDays(1L));
        //更新业务层的登录账号为禁用
        if (taChannelProxy.getStatus() != null){
            QueryWrapper<TaChannelAppRelation> taChannelAppRelationQueryWrapper = new QueryWrapper<>();
            taChannelAppRelationQueryWrapper.eq("channel_id", id);
            List<TaChannelAppRelation> taChannelAppRelation = iTaChannelAppRelationService.list(taChannelAppRelationQueryWrapper);
            List<Integer> orgIdList = new ArrayList<>();
            taChannelAppRelation.forEach(e->{
                orgIdList.add(e.getOrgId());
            });
            if (CollectionUtils.isNotEmpty(orgIdList)){
                QueryWrapper<TaUser> taUserQueryWrapper = new QueryWrapper<>();
                taUserQueryWrapper.in("org_id", orgIdList);
                TaUser taUser = new TaUser();
                taUser.setStatus(taChannelProxy.getStatus());
                iTaUserService.update(taUser, taUserQueryWrapper);
            }

        }

        QueryWrapper<TaChannelProxy> taChannelProxyQueryWrapper = new QueryWrapper<>();
        taChannelProxyQueryWrapper.eq("channel_id", id);
        iTaChannelProxyService.update(taChannelProxy, taChannelProxyQueryWrapper);
        return ResponseBean.success("更新成功");
    }

}
