package com.dgtly.api.controller;

import com.dgtly.common.annotation.ApiPassToken;
import com.dgtly.common.core.controller.ApiBaseController;
import com.dgtly.common.core.domain.AjaxResult;
import com.dgtly.common.core.domain.ParameterObject;
import com.dgtly.common.core.domain.ResultType;
import com.dgtly.common.utils.security.EncryptPassWordClass;
import com.dgtly.system.domain.OrderSalesParameter;
import com.dgtly.system.domain.SysUser;
import com.dgtly.system.service.IAlertConfigurationService;
import com.dgtly.system.service.ISysUserExtService;
import com.dgtly.wxportal.domain.WxQyUser;
import com.dgtly.system.service.ISysUserService;
import com.dgtly.wxportal.service.IWxQyUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "系统用户相关API")
@RestController
@RequestMapping("sysuser")
public class SysUserController extends ApiBaseController {

    @Autowired
    private IWxQyUserService wxQyUserService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserExtService userExtService;
    @Autowired
    private IAlertConfigurationService alertConfigurationService;


    @ApiOperation(value = "绑定微信用户和系统用户",
            notes = "参数：{wxUserId:'xxxxxxxxxxxxxxxxxxxx'," +
            "username:'admin',password:'admin123'}" +
            "错误：" +
            "301  用户不存在或密码错误")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @ApiPassToken
    @PostMapping("bindingUser")
    public Object bindingUser(){
        ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("wxUserId,username,password");
        SysUser sysUser = sysUserService.selectUserByLoginName(obj.getString("username"));
        if(sysUser==null){
            return AjaxResult.error(301,"用户不存在或密码错误");
        }
        String p =EncryptPassWordClass.encryptPassword(sysUser.getLoginName(), obj.getString("password"), sysUser.getSalt());
        if(!sysUser.getPassword().equals(p)){
            return AjaxResult.error(301,"用户不存在或密码错误");
        }

        String wxUserId = obj.getString("wxUserId");
        WxQyUser wxQyUserIntable = wxQyUserService.selectWxQyUserById(wxUserId);
        if(wxQyUserIntable.getSysUserId()!=null){
            return AjaxResult.error(302,"此用户已绑定现相关系统用户");
        }

        WxQyUser wxQyUser  = new WxQyUser();
        wxQyUser.setUserid(wxUserId);
        wxQyUser.setSysUserId(sysUser.getUserId());
        int i  =wxQyUserService.updateWxQyUser(wxQyUser);

        if (i > 0) {
            return AjaxResult.success().putKV("user",sysUser);
        }else{
            return AjaxResult.error();
        }
    }

    @ApiOperation(value = "接触绑定",
            notes = "参数：{" +
                    "userId:xxxxxx}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("bonded")
    public Object bonded(){
        ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("userId");
        Long userId =obj.getLong("userId");
        int i = wxQyUserService.bondedSysUserBySysUserId(userId);
        return toAjax(i);
    }

    @ApiOperation(value = "获取用户信息",
            notes = "参数：{" +
                    "userId:xxxxxx}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("getUserInfo")
    public Object getUserInfo(){
        ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("userId");
        Long userId =obj.getLong("userId");
        SysUser user = sysUserService.selectUserById(userId);
        WxQyUser wxQyUser = new WxQyUser();
        wxQyUser.setSysUserId(userId);
        List<WxQyUser> wxQyUsers = wxQyUserService.selectWxQyUserList(wxQyUser);
        wxQyUser = wxQyUsers.size()>0?wxQyUsers.get(0):null;
        return AjaxResult.success().putKV("wxUser",wxQyUser).putKV("sysUser",user);
    }

    @ApiOperation(value = "获取用户信息",
            notes = "参数：{" +
                    "loginName:xxxxxx}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("getUserInfoByLoginName")
    public Object getUserInfoByLoginName(){
        ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("loginName");
        String loginName =obj.getString("loginName");
        SysUser user = sysUserService.selectUserByLoginName(loginName);
        if(user==null){
            return AjaxResult.error("查无此人");
        }
        return AjaxResult.success().putKV("sysUser",user);
    }

    @ApiOperation(value = "测试接口访问超时",
            notes = "参数：{" +
                    "waitingTime:int秒}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("testAccessTimeout")
    public Object testAccessTimeout() throws Exception{
        ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("waitingTime");
        String waitingTime =obj.getString("waitingTime");
        int i = Integer.parseInt(waitingTime);
        if (a<3) {
            TimeUnit.SECONDS.sleep(i);//秒
        }
        a=a++;
        System.out.println("访问次数");
        return AjaxResult.success();
    }

    private int a=0;

    @ApiOperation(value = "获取销售员列表",
            notes = "参数：{" +
                    "bossEmployeeId:xxxxxx}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body")
    })
    @PostMapping("getSelesList")
    public Object getSelesList(){
        ParameterObject obj =  getParameterObject();
        obj.checkParameterNotNull("bossEmployeeId");
        String bossEmployeeId =obj.getString("bossEmployeeId");
        List<String> list = userExtService.selectEmployeeIdsByBossEmployeeId(bossEmployeeId);
        return list.size()>0?AjaxResult.success().putKV("list",list):AjaxResult.error(ResultType.NUll);
    }

//    @PostMapping("/searchOrg")
//    @ApiOperation(value = "查询组织架构",notes = "参数：{'parType':'1','parValue':'xxx'}" )
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "params" , paramType = "body")
//    })
//    public Map searchProductParamByCustomerCode() {
//        ParameterObject obj =  getParameterObject();
//        OrderSalesParameter salesManager =new OrderSalesParameter();
//        String payType = obj.getString("parType");
//        String payValue = obj.getString("parValue");
//        if("".equals(payType) ||payType ==null){
//            salesManager.setParType("diy_level");
//        }else{
//            salesManager.setParType(payType);
//            salesManager.setParValue(payValue);
//        }
//        Map map = new HashMap();
//        List<Map<String,Object>> dataList = alertConfigurationService.searchProductParamByCustomerCode(
//                salesManager.getParType(),salesManager.getParValue());
//        if(dataList != null && dataList.size() > 0){
//            map.put("levelInfo",dataList.get(0));
//            if ("suboffice_level".equals(salesManager.getParType()) ||
//                    "customer_level".equals(salesManager.getParType()) ||
//                    "emp_level".equals(salesManager.getParType()) ||
//                    "saledept_level".equals(salesManager.getParType())
//            ){
//                map.put("dataList",new ArrayList());
//            }else{
//                map.put("dataList",dataList);
//            }
//            return map;
//        } else {
//            Map mapnull = new HashMap();
//            map.put("levelInfo",mapnull);
//            map.put("dataList",dataList);
//            return map;
//        }
//    }

    @PostMapping("/searchOrg")
    public Map searchProductParamByCustomerCode(OrderSalesParameter salesManager) {
        if("".equals(salesManager.getParType()) || salesManager.getParType() ==null){
            salesManager.setParType("div_level");
        }
        Map map = new HashMap();
        List<Map<String,Object>> dataList = alertConfigurationService.searchProductParamByCustomerCode(
                salesManager.getParType(),salesManager.getParValue());
        if(dataList != null && dataList.size() > 0){
            map.put("levelInfo",dataList.get(0));
            if ("suboffice_level".equals(salesManager.getParType()) ||
                    "customer_level".equals(salesManager.getParType()) ||
                    "emp_level".equals(salesManager.getParType()) ||
                    "saledept_level".equals(salesManager.getParType())
            ){
                map.put("dataList",new ArrayList());
            }else{
                map.put("dataList",dataList);
            }
            return map;
        } else {
            Map mapnull = new HashMap();
            map.put("levelInfo",mapnull);
            map.put("dataList",dataList);
            return map;
        }
    }

}
