package com.mortals.xhx.daemon.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.HttpUtil;
import com.mortals.xhx.base.framework.ws.message.SendToAllRequest;
import com.mortals.xhx.base.framework.ws.util.WebSocketUtil;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.base.system.role.model.RoleUserQuery;
import com.mortals.xhx.base.system.role.service.RoleUserService;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.common.code.DeviceOnlineStatusEnum;
import com.mortals.xhx.common.key.ParamKey;
import com.mortals.xhx.module.device.model.DeviceLogEntity;
import com.mortals.xhx.module.device.model.DeviceLogQuery;
import com.mortals.xhx.module.device.service.DeviceLogService;
import com.mortals.xhx.module.device.service.DeviceService;
import lombok.extern.apachecommons.CommonsLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;

import static com.alibaba.druid.sql.ast.SQLPartitionValue.Operator.List;

/**
 * 用户同步
 *
 * @author: zxfei
 * @date: 2022/3/9 15:19
 */
@Slf4j
@Service("UserSyncTask")
public class UserSyncTaskImpl implements ITaskExcuteService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleUserService roleUserService;



    @Override
    public void excuteTask(ITask task) throws AppException {
        log.debug("用户同步，开始执行");
        syncUser();
        log.debug("用户同步，结束执行");
    }

    /**
     * 用户同步
     */
    private void syncUser() {
        String url = GlobalSysInfo.getParamValue(ParamKey.SYS_PARAM_USER_URL, "http://125.64.74.247:8076/doors/inter/user/userList");

        Map<String, String> headers = new HashMap<>();
        try {
            String resp = HttpUtil.doGet(url, headers);
            ApiResp<List<CustomerInfo>> apiResp = JSON.parseObject(resp, new TypeReference<ApiResp<List<CustomerInfo>>>() {
            });
            if(apiResp.getCode()==0){
                apiResp.getData().stream().forEach(user->{
                    //查询用户是否存在
                    UserQuery userQuery = new UserQuery();
                    userQuery.setCustomerId(user.getId());
                    userQuery.setLoginName(user.getAccount());
                    UserEntity userEntity = userService.selectOne(userQuery);
                    if(!ObjectUtils.isEmpty(userEntity)){
                        userEntity.setCustomerId(user.getId());
                        userEntity.setLoginName(user.getAccount());
                        userEntity.setRealName(user.getUser_name());
                        userEntity.setMobile(user.getMobile());
                        userEntity.setLoginPwd(user.getPassword());
                        userEntity.setUpdateUserId(1L);
                        userEntity.setUpdateTime(new Date());
                        userService.update(userEntity);
                    }else {
                        //新增用户
                        userEntity = userService.createUser(null, user.getId(), "", user.getAccount(), user.getPassword(), user.getUser_name(), user.getMobile());
                         //添加默认访问权限
                        RoleUserQuery roleUserQuery = new RoleUserQuery();
                        roleUserQuery.setUserId(userEntity.getId());
                        roleUserQuery.setRoleIdList(Arrays.asList(new Long[]{1L}));
                        roleUserService.doDistributionRole(roleUserQuery);
                    }
                });
            }
            log.debug("user resp:{}", JSON.toJSONString(apiResp));
        } catch (Exception e) {
            log.error("用户同步异常，结束执行", e);
        }
    }


    @Override
    public void stopTask(ITask task) throws AppException {

    }


}
