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.HttpUtil;
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.key.ParamKey;
import com.mortals.xhx.common.pdu.CustomerInfoPdu;
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.*;

/**
 * 用户同步
 * @author:
 * @date: 2023/3/6 13:46
 */
@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://127.0.0.1:8076/doors/inter/user/userList");

        Map<String, String> headers = new HashMap<>();
        try {
            String resp = HttpUtil.doGet(url, headers);
            ApiResp<List<CustomerInfoPdu>> apiResp = JSON.parseObject(resp, new TypeReference<ApiResp<List<CustomerInfoPdu>>>() {
            });
            if(apiResp.getCode()==0){
                apiResp.getData().stream().forEach(user->{
                    //查询用户是否存在
                    UserQuery userQuery = new UserQuery();
                    userQuery.id(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.setUserType(user.getUserType());
                        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 {

    }


}
