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.code.UserType;
import com.mortals.xhx.common.key.ParamKey;
import com.mortals.xhx.common.pdu.CustomerInfoPdu;
import com.mortals.xhx.module.dept.model.DeptEntity;
import com.mortals.xhx.module.dept.model.DeptQuery;
import com.mortals.xhx.module.dept.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
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;
    @Autowired
    private DeptService deptService;

    @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://192.168.0.231: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) {
                for (CustomerInfoPdu user : apiResp.getData()) {
                    if("admin".equalsIgnoreCase(user.getAccount())){
                        //更新超级管理员
                        UserEntity userEntity = userService.get(1L);
                        userEntity.setLoginName(user.getAccount());
                        userEntity.setRealName(user.getUser_name());
                        userEntity.setMobile(user.getMobile());
                        userEntity.setUserType(UserType.SYSTEM.getValue());
                        userEntity.setLoginPwd(user.getPassword());
                        userEntity.setUpdateUserId(1L);
                        userEntity.setUpdateTime(new Date());

                        updateDefaultDept(userEntity);
                        userService.doHandlerUser(userEntity);
                        userService.getUserDao().update(userEntity);
                      //  userService.update(userEntity);
                        continue;
                    }
                    //查询用户是否存在,登录用户名唯一
                    UserQuery userQuery = new UserQuery();
                    //userQuery.id(user.getId());
                    userQuery.setLoginName(user.getAccount());
                    UserEntity userEntity = userService.selectOne(userQuery);
                    if (!ObjectUtils.isEmpty(userEntity)) {
                        updateDefaultDept(userEntity);
                        userEntity.setLoginName(user.getAccount());
                        userEntity.setRealName(user.getUser_name());
                        userEntity.setMobile(user.getMobile());
                        userEntity.setUserType(user.getType());
                        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());
                        if(UserType.WORK.getValue()==user.getType()){
                            //根据用户类型添加默认访问权限
                            RoleUserQuery roleUserQuery = new RoleUserQuery();
                            roleUserQuery.setUserId(userEntity.getId());
                            roleUserQuery.setRoleIdList(Arrays.asList(new Long[]{3L}));
                            roleUserService.doDistributionRole(roleUserQuery);
                        }else if (UserType.WORK_PERSON.getValue()==user.getType()){
                            //根据用户类型添加默认访问权限
                            RoleUserQuery roleUserQuery = new RoleUserQuery();
                            roleUserQuery.setUserId(userEntity.getId());
                            roleUserQuery.setRoleIdList(Arrays.asList(new Long[]{2L}));
                            roleUserService.doDistributionRole(roleUserQuery);
                        }
                    }
                }

            }
            log.debug("user resp:{}", JSON.toJSONString(apiResp));
        } catch (Exception e) {
            log.error("用户同步异常，结束执行", e);
        }
    }

    private void updateDefaultDept(UserEntity userEntity) {
        if(ObjectUtils.isEmpty(userEntity.getDeptId())){
            //没有部门 默认添加一个
            DeptEntity deptEntity = deptService.selectOne(new DeptQuery());
            if(!ObjectUtils.isEmpty(deptEntity)){
                userEntity.setDeptId(deptEntity.getId());
                userEntity.setDeptName(deptEntity.getDeptName());
            }
        }
    }


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

    }


}
