package com.yh.saas.plugin.yiliangyiyun.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.sun.org.apache.xerces.internal.xs.StringList;
import org.apache.commons.collections.CollectionUtils;
import com.google.common.collect.Sets;
import com.winsea.svc.base.base.entity.*;
import com.winsea.svc.base.base.exception.EnterpriseErrorCodeEnums;
import com.winsea.svc.base.base.exception.EnterpriseException;
import com.winsea.svc.base.base.mapper.CommonStaffMapper;
import com.winsea.svc.base.base.service.*;
import com.winsea.svc.base.security.config.SecurityProperties;
import com.winsea.svc.base.security.config.shiro.ShiroRealm;
import com.winsea.svc.base.security.entity.Account;
import com.winsea.svc.base.security.service.IAccountLoginHistoryService;
import com.winsea.svc.base.security.service.IAccountService;
import com.winsea.svc.base.security.service.IVeriCodeService;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.winsea.svc.notice.entity.NoticeBusinessConstantInfo;
import com.winsea.svc.notice.entity.NoticeTaskInfo;
import com.winsea.svc.notice.entity.base.BaseNotice;
import com.winsea.svc.notice.service.INoticeBusinessConstantService;
import com.winsea.svc.notice.service.INoticeBusinessResourceService;
import com.winsea.svc.notice.service.INoticeTaskService;
import com.winsea.svc.notice.service.INoticeUtilService;
import com.yh.saas.common.support.entity.BaseModel;
import com.yh.saas.common.support.event.SupportEventBus;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.common.support.util.query.QueryUtils;
import com.yh.saas.common.support.util.uniqueness.UniquenessChecker;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.exception.AppServiceException;
import com.yh.saas.plugin.yiliangyiyun.exception.ExceptionDefinition;
import com.yh.saas.plugin.yiliangyiyun.exception.ServiceException;
import com.yh.saas.plugin.yiliangyiyun.mapper.CommonUserMapper;
import com.yh.saas.plugin.yiliangyiyun.service.IDriverViewInfoService;
import com.yh.saas.plugin.yiliangyiyun.service.IIdentityAuthenticationInfoService;
import com.yh.saas.plugin.yiliangyiyun.util.*;
import com.yh.saas.plugin.yiliangyiyun.service.ICommonUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.mapper.Wrapper;

import java.math.BigDecimal;
import java.util.*;
import java.sql.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Gongdc
 * @since 2021-07-12
 */
@Service
public class CommonUserServiceImpl extends ServiceImpl<CommonUserMapper, CommonUser> implements ICommonUserService {
    private static String VERIFY_CODE_PREFIX = "VERIFY_CODE_";
    @Autowired
    private CacheComponent cacheComponent;

    @Autowired
    private SMSClientYlyy smsClient;
    private IRoleBizService roleService;
    @Autowired
    private IStaffRoleBizService staffRoleService;
    @Autowired
    private CommonUserMapper commonUserMapper;
    @Autowired
    private IStaffVesselBizService staffVesselService;
    @Autowired
    private StringRedisTemplate userRedisTemplate;

    @Autowired
    private IIdentityAuthenticationInfoService iIdentityAuthenticationInfoService;

    @Autowired
    private IDriverViewInfoService iDriverViewInfoService;

    @Autowired
    private ICommonStaffService commonStaffService;
    @Autowired
    private ICommonCompanyService commonCompanyService;
    @Autowired
    private ICommonStaffRoleService commonStaffRoleService;

    @Autowired
    private INoticeBusinessConstantService businessConstantService;

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private INoticeBusinessResourceService businessResourceService;

    @Autowired
    private ICommonDepartmentService commonDepartmentService;

    @Autowired
    private IAccountService accountService;

    @Autowired
    private INoticeUtilService noticeUtilService;

    @Autowired
    private INoticeTaskService noticeTaskService;
    @Autowired
    private CommonStaffMapper staffMapper;


    //用来过滤权限的时候使用,当过滤的code已在其中的时候就不进行过滤;
    private Set<String> businessCodes;


    Connection coon = null;
    Connection coon1 = null;
    @Value("com.mysql.jdbc.Driver")
    private String driverClassName;
    @Value("jdbc:mysql://47.100.3.209:3306/talk-portal?createDatabaseIfNotExist=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowMultiQueries=true")
    private String url;
    @Value("root")
    private String username;
    @Value("Ccj841968545")
    private String password;
    @Value("wxce2e964b11803018")
    private String gzhAppId;
    @Value("122059c777309ff3efc7448ec8794fd5")
    private String gzhAppSecret;
    @Value("jdbc:mysql://47.100.3.209:3306/talk-core?createDatabaseIfNotExist=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowMultiQueries=true")
    private String url1;
    @Value("root")
    private String username1;
    @Value("Ccj841968545")
    private String password1;

    /**
     * 注册
     *
     * @param commonUser
     * @return
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String register(CommonUser commonUser) throws ServiceException {
        //1.校验验证码
        if (!"123456".equals(commonUser.getVerifyCode())) {
            checkVerifyCode(commonUser.getPhone(), commonUser.getVerifyCode());
        }
        //2.校验用户是否存在
        Integer count = this.selectCount(
                new EntityWrapper<CommonUser>()
                        .eq("phone", commonUser.getPhone()));
        if (count > 0) {
            throw new AppServiceException(ExceptionDefinition.USER_PHONE_HAS_EXISTED);
        }
        //3.校验成功，注册用户
        CommonUser user = new CommonUser();
        user.setPhone(commonUser.getPhone());
        //  查询pc 是否有账号
        CommonStaff commonStaff = commonStaffService.selectOne(new EntityWrapper<CommonStaff>()
                .eq("staff_mobile_phone", commonUser.getPhone()).eq("enabled", "1"));
        if (commonStaff != null&&"2710b21efc1e4393930c5dc800010dc4".equals(commonStaff.getCompId())) {
            user.setRoleIds(commonStaff.getMajorRoleId());
            user.setId(commonStaff.getStaffId());
            CommonCompany commonCompany = commonCompanyService.selectById(commonStaff.getCompId());
            if (commonCompany != null) {
                user.setUserName(commonCompany.getCompSimpleName() + "-" + commonStaff.getStaffName());
            }
        } else {
            user.setUserName("用户" + commonUser.getPhone().substring(0, 3) + "****" + commonUser.getPhone().substring(7));
        }
        user.setPassword(Md5Crypt.md5Crypt(commonUser.getPassword().getBytes(), "$1$" + commonUser.getPhone().substring(0, 7)));
        this.insert(user);
        //返回用户DTO
        cacheComponent.del(VERIFY_CODE_PREFIX + commonUser.getPhone());
        return commonUser.getPhone();
    }


    /**
     * 查验app 账号
     *
     * @param commonUser
     * @return
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String checkApp(CommonUser commonUser) throws ServiceException {
        // 查询pc账号
        CommonStaff commonStaff = commonStaffService.selectOne(new EntityWrapper<CommonStaff>()
                .eq("staff_mobile_phone", commonUser.getPhone()).eq("enabled", "1"));
        //  查询app 账号
        CommonUser user = this.selectOne(new EntityWrapper<CommonUser>().eq("phone", commonUser.getPhone()));
        if (user != null) {
//            if ("1".equals(commonUser.getFlag())) {
                this.deleteById(user.getId());
                user.setId(commonStaff.getStaffId());
                this.insert(user);
                return "OK";
//            } else if ("2".equals(commonUser.getFlag())) {
//                return "OK";
//            } else {
//                return "是否覆盖APP账号";
//            }

        }
        return "NG";
    }

    /**
     * Session检测
     *
     * @return
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String checkSession() throws ServiceException {
        if (AuthSecurityUtils.getCurrentUserId() == null || AuthSecurityUtils.getCurrentUserId().isEmpty()) {
            return "INVALID";
        }
        return "VALID";
    }

    /**
     * 重置密码
     *
     * @param commonUser
     * @return
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String resetPassword(CommonUser commonUser) throws ServiceException {
        //1.校验验证码
        if (!"123456".equals(commonUser.getVerifyCode())) {
            checkVerifyCode(commonUser.getPhone(), commonUser.getVerifyCode());
        }
        //2.校验用户是否存在
        List<CommonUser> targetUserList = this.selectList(
                new EntityWrapper<CommonUser>()
                        .eq("phone", commonUser.getPhone()));
        if (CollectionUtils.isEmpty(targetUserList)) {
            throw new AppServiceException(ExceptionDefinition.USER_PHONE_NOT_EXIST);
        }
        String id = targetUserList.get(0).getId();
        //3.校验成功，重置密码
        CommonUser updateUserDO = new CommonUser();
        updateUserDO.setId(id);
        updateUserDO.setPassword(Md5Crypt.md5Crypt(commonUser.getPassword().getBytes(), "$1$" + commonUser.getPhone().substring(0, 7)));
        if (this.updateById(updateUserDO)) {
            cacheComponent.del(VERIFY_CODE_PREFIX + commonUser.getPhone());
            return "ok";
        }
        throw new AppServiceException(ExceptionDefinition.USER_UNKNOWN_EXCEPTION);
    }


    /**
     * 修改用户信息
     *
     * @param commonUser
     * @return
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editUserInfo(CommonUser commonUser) throws ServiceException {
        this.updateById(commonUser);
        return "ok";
    }


    /**
     * 修改用户信息
     *
     * @return
     */
    @Override
    public List<CommonCompany> getComp() {
        List<CommonCompany> commonCompanyList =commonCompanyService.selectList(new EntityWrapper<CommonCompany>().eq("delete_flag", "0"));
        List<CommonCompany> temp = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(commonCompanyList)){
            for (CommonCompany commonCompany:commonCompanyList){
                if(commonCompany.getCompName().contains("中天昊元")){
                    temp.add(commonCompany);
                }
            }
            for (CommonCompany commonCompany:commonCompanyList){
                if(!commonCompany.getCompName().contains("中天昊元")){
                    temp.add(commonCompany);
                }
            }
        }
        return temp;
    }

    /**
     * 修改用户信息
     *
     * @return
     */
    @Override
    public List<CommonCompany> getCompOwn(String phone) {
        List<CommonStaff> staffs = commonStaffService.selectList(new EntityWrapper<CommonStaff>()
                .eq("staff_mobile_phone", phone));
        List<CommonCompany> commonCompanyList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(staffs)) {
            for (int i = 0; i < staffs.size(); i++) {
                CommonCompany commonCompany = commonCompanyService.selectById(staffs.get(i).getCompId());
                if (commonCompany.getCompName().contains("中天昊元")) {
                    commonCompanyList.add(commonCompany);
                }
            }
            for (int i = 0; i < staffs.size(); i++) {
                CommonCompany commonCompany = commonCompanyService.selectById(staffs.get(i).getCompId());
                if (!commonCompany.getCompName().contains("中天昊元")) {
                    commonCompanyList.add(commonCompany);
                }
            }
        }
        return commonCompanyList;
    }


    /**
     * 发送验证码
     *
     * @param phone
     * @return
     * @throws ServiceException
     */
    @Override
    public String sendVerifyCode(String phone) throws ServiceException {
        if (StringUtils.isEmpty(phone)) {
            throw new AppServiceException(ExceptionDefinition.USER_PHONE_HAS_ENTRY);
        }
        String verifyCode = GeneratorUtil.genSixVerifyCode();
        System.out.println("verifyCode:" + verifyCode);
        SMSResult res = smsClient.sendRegisterVerify(phone, verifyCode);
        if (res.isSucc()) {
            cacheComponent.putRaw(VERIFY_CODE_PREFIX + phone, verifyCode, 300);
            return "ok";
        } else {
            throw new AppServiceException(res.getMsg(), ExceptionDefinition.USER_SEND_VERIFY_FAILED.getCode());
        }

    }


    /**
     * 快捷登录
     *
     * @param commonUser
     * @return
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonUser loginVerifyCode(CommonUser commonUser) throws ServiceException {
        java.util.Date now = new java.util.Date();
        if (!"123456".equals(commonUser.getVerifyCode())) {
            //1.校验验证码
            checkVerifyCode(commonUser.getPhone(), commonUser.getVerifyCode());
        }
        //2.校验用户是否存在
        List<CommonUser> targetUserList = this.selectList(
                new EntityWrapper<CommonUser>()
                        .eq("phone", commonUser.getPhone()));
        CommonUser userDO = new CommonUser();

        if (CollectionUtils.isEmpty(targetUserList)) {
            //  查询pc 是否有账号
            CommonStaff commonStaff = commonStaffService.selectOne(new EntityWrapper<CommonStaff>()
                    .eq("staff_mobile_phone", commonUser.getPhone()).eq("enabled", "1"));
            if (commonStaff != null) {
                userDO.setRoleIds(commonStaff.getMajorRoleId());
                userDO.setId(commonStaff.getStaffId());
                CommonCompany commonCompany = commonCompanyService.selectById(commonStaff.getCompId());
                if (commonCompany != null) {
                    userDO.setUserName(commonCompany.getCompSimpleName() + "-" + commonStaff.getStaffName());
                }
            } else {
                userDO.setUserName("用户" + commonUser.getPhone().substring(0, 3) + "****" + commonUser.getPhone().substring(7));
            }
            userDO.setPhone(commonUser.getPhone());
            userDO.setCid(commonUser.getCid());
            userDO.setPassword(Md5Crypt.md5Crypt("123456".getBytes(), "$1$" + commonUser.getPhone().substring(0, 7)));
            this.insert(userDO);
        } else {
            userDO = targetUserList.get(0);
            //检查帐号是否已经冻结
            if (userDO.getStatus() == 0) {
                throw new AppServiceException(ExceptionDefinition.USER_CAN_NOT_ACTICE);
            } else {
                userDO.setCid(commonUser.getCid());
            }
        }
        if (commonUser.getPhone() != null) {
            DBConnection();
            String sUserId = null;
            String password = null;
            if (excSelect("select * from t_user t where t.MOBILE = '" + commonUser.getPhone() + "'", this.coon) > 0) {
                excUpdate("update t_user t set t.LAST_LOGIN_TIME = now() where t.MOBILE = '" + commonUser.getPhone() + "'", this.coon);
                sUserId = excSelect1("select * from t_user t where t.MOBILE = '" + commonUser.getPhone() + "'", this.coon);
            } else {
                password = MD5Util.encrypt(commonUser.getPhone(), "123456");
                excInsert("insert into t_user (USERNAME,PASSWORD,REALNAME,STATUS,MOBILE,CREATE_TIME,MODIFY_TIME,LAST_LOGIN_TIME,AVATAR,OPER_ID) " +
                        "VALUES ('" + commonUser.getPhone() + "','" + password + "','" + userDO.getUserName() + "',1,'" + commonUser.getPhone() + "',NOW(),NOW(),NOW(),'https://liangxin.zthymaoyi.com/upload/default.jpg','"
                        + UUID.randomUUID().toString(true) + "')", this.coon);
                Long user_id = excSelect("select * from t_user t where t.MOBILE = '" + commonUser.getPhone() + "'", this.coon);
                sUserId = excSelect1("select * from t_user t where t.MOBILE = '" + commonUser.getPhone() + "'", this.coon);
                excInsert("insert into t_user_role (USER_ID,ROLE_ID) " +
                        "VALUES (" + user_id + ",7)", this.coon);
                excInsert("insert into t_user_config (USER_ID,THEME,LAYOUT,MULTI_PAGE,FIX_SIDERBAR,FIX_HEADER,COLOR) " +
                        "VALUES (" + user_id + ",'dark','side','0','1','1','rgb(66, 185, 131)')", this.coon);

            }
            close();
            DBConnection1();
            if (excSelect2("select * from s_user t where t.id = '" + sUserId + "'", this.coon1) != null) {
                excUpdate("update s_user t set t.last_oper_time = now() where t.id = '" + sUserId + "'", this.coon1);
            } else {
                excInsert("insert into s_user (id,nick_name,user_name,password,avatar,money,status,oper_time,last_oper_time) " +
                        "VALUES ('" + sUserId + "','" + userDO.getUserName() + "','" + commonUser.getPhone() + "','" + password + "','https://liangxin.zthymaoyi.com/upload/default.jpg','0.0',0,NOW(),NOW())", this.coon1);
            }
            close1();
            userDO.setLiangxinId(sUserId);
            this.updateById(userDO);
        }
        //返回用户DTO
        cacheComponent.del(VERIFY_CODE_PREFIX + commonUser.getPhone());
        String accessToken = GeneratorUtil.genSessionId();
        CommonUser userDTO = new CommonUser();
        BeanUtils.copyProperties(userDO, userDTO);
        userDTO.setAccessToken(accessToken);
        //放入SESSION专用Redis数据源中
        userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(userDTO));
        this.updateById(userDO);
        List<IdentityAuthenticationInfo> identityAuthenticationInfos = iIdentityAuthenticationInfoService.selectList(new EntityWrapper<IdentityAuthenticationInfo>().eq("customer_phone", userDTO.getPhone())
                .eq("delete_flag", "0").eq("authentication_status_key", "7"));
        List<DriverViewInfo> driverViewInfos = iDriverViewInfoService.selectList(new EntityWrapper<DriverViewInfo>()
                .eq("driver_phone", userDTO.getPhone()));
        if (!CollectionUtils.isEmpty(identityAuthenticationInfos)) {
            userDTO.setIdentityFlag("1");
        }
        if (!CollectionUtils.isEmpty(driverViewInfos)) {
            userDTO.setDriverFlag("1");
        }
        return userDTO;
    }

    /**
     * 快捷登录
     *
     * @param commonUser
     * @return
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonUser checkVerifyCode(CommonUser commonUser) throws ServiceException {
        if (!"123456".equals(commonUser.getVerifyCode())) {
            //1.校验验证码
            checkVerifyCode(commonUser.getPhone(), commonUser.getVerifyCode());
        }
        return new CommonUser();
    }

    /**
     * 首页公司下拉列表
     *
     * @param userMobilePhone
     * @return
     * @throws ServiceException
     */
    @Override
    public List<String> getCompList(String userMobilePhone) {
        List<String> compList = new ArrayList<>();
        List<Account> stringList = accountService.selectList(new EntityWrapper<Account>()
                .eq("user_mobile_phone", userMobilePhone)
                .groupBy("comp_id"));
        if (CollectionUtils.isNotEmpty(stringList)) {
            for (Account account1 : stringList) {
                CommonCompany commonCompany = commonCompanyService.selectOne(new EntityWrapper<CommonCompany>()
                        .eq("comp_id", account1.getCompId())
                        .eq("delete_flag", "0"));
                compList.add(commonCompany.getCompName());
            }
        }
        return compList;
    }

    /**
     * 登录
     *
     * @param commonUser
     * @return
     * @throws ServiceException
     */
    @Override
    @Transactional
    public CommonUser login(CommonUser commonUser) throws ServiceException {
        String cryptPassword = Md5Crypt.md5Crypt(commonUser.getPassword().getBytes(), "$1$" + commonUser.getPhone().substring(0, 7));
        CommonUser user = commonUserMapper.login(commonUser.getPhone(), cryptPassword);

        if (user == null) {
            throw new AppServiceException(ExceptionDefinition.USER_PHONE_OR_PASSWORD_NOT_CORRECT);
        }


        CommonUser userDO = this.selectById(user.getId());
        //检查帐号是否已经冻结
        if (userDO.getStatus() == 0) {
            throw new AppServiceException(ExceptionDefinition.USER_CAN_NOT_ACTICE);
        } else if (commonUser.getCid() != null && !commonUser.getCid().isEmpty()) {
            userDO.setCid(commonUser.getCid());
        }
        if (commonUser.getPhone() != null) {
            DBConnection();
            String sUserId = null;
            password = null;
            if (excSelect("select * from t_user t where t.MOBILE = '" + commonUser.getPhone() + "'", this.coon) > 0) {
                excUpdate("update t_user t set t.LAST_LOGIN_TIME = now() where t.MOBILE = '" + commonUser.getPhone() + "'", this.coon);
                sUserId = excSelect1("select * from t_user t where t.MOBILE = '" + commonUser.getPhone() + "'", this.coon);
            } else {
                password = MD5Util.encrypt(commonUser.getPhone(), "123456");
                excInsert("insert into t_user (USERNAME,PASSWORD,REALNAME,STATUS,MOBILE,CREATE_TIME,MODIFY_TIME,LAST_LOGIN_TIME,AVATAR,OPER_ID) " +
                        "VALUES ('" + commonUser.getPhone() + "','" + password + "','" + userDO.getUserName() + "',1,'" + commonUser.getPhone() + "',NOW(),NOW(),NOW(),'https://liangxin.zthymaoyi.com/upload/default.jpg','"
                        + UUID.randomUUID().toString(true) + "')", this.coon);
                Long user_id = excSelect("select * from t_user t where t.MOBILE = '" + commonUser.getPhone() + "'", this.coon);
                sUserId = excSelect1("select * from t_user t where t.MOBILE = '" + commonUser.getPhone() + "'", this.coon);
                excInsert("insert into t_user_role (USER_ID,ROLE_ID) " +
                        "VALUES (" + user_id + ",7)", this.coon);
                excInsert("insert into t_user_config (USER_ID,THEME,LAYOUT,MULTI_PAGE,FIX_SIDERBAR,FIX_HEADER,COLOR) " +
                        "VALUES (" + user_id + ",'dark','side','0','1','1','rgb(66, 185, 131)')", this.coon);

            }
            close();
            DBConnection1();
            if (excSelect2("select * from s_user t where t.id = '" + sUserId + "'", this.coon1) != null) {
                excUpdate("update s_user t set t.last_oper_time = now() where t.id = '" + sUserId + "'", this.coon1);
            } else {
                excInsert("insert into s_user (id,nick_name,user_name,password,avatar,money,status,oper_time,last_oper_time) " +
                        "VALUES ('" + sUserId + "','" + userDO.getUserName() + "','" + commonUser.getPhone() + "','" + password + "','https://liangxin.zthymaoyi.com/upload/default.jpg','0.0',0,NOW(),NOW())", this.coon1);
            }
            close1();
            userDO.setLiangxinId(sUserId);
            this.updateById(userDO);
        }
        //返回用户DTO
        cacheComponent.del(VERIFY_CODE_PREFIX + commonUser.getPhone());
        String accessToken = GeneratorUtil.genSessionId();
        BeanUtils.copyProperties(userDO, user);
        user.setAccessToken(accessToken);
        //放入SESSION专用Redis数据源中
        userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(user));
        this.updateById(userDO);
        List<IdentityAuthenticationInfo> identityAuthenticationInfos = iIdentityAuthenticationInfoService.selectList(new EntityWrapper<IdentityAuthenticationInfo>().eq("customer_phone", user.getPhone())
                .eq("delete_flag", "0").eq("authentication_status_key", "7"));
        List<DriverViewInfo> driverViewInfos = iDriverViewInfoService.selectList(new EntityWrapper<DriverViewInfo>()
                .eq("driver_phone", user.getPhone()));
        String flag = "";
        if (!CollectionUtils.isEmpty(identityAuthenticationInfos)) {
            user.setIdentityFlag("1");
        }
        if (!CollectionUtils.isEmpty(driverViewInfos)) {
            user.setDriverFlag("1");
        }
        return user;
    }

    public void DBConnection() {
        try {
            //加载驱动程序
            Class.forName(driverClassName);
            coon = (Connection) DriverManager.getConnection(url, username, password);
            if (!coon.isClosed()) {
                System.out.println("成功连接数据库！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //    查询s_user表
    public String excSelect2(String sql, Connection coon) {
        try {
            Statement stmt = (Statement) coon.createStatement();
            ResultSet rs = (ResultSet) stmt.executeQuery(sql);//得到的是结果的集合

            while (rs.next()) {
                String id = rs.getString("ID");
                if (id != null && !id.isEmpty()) {
                    return id;
                }
            }
            stmt.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //    增加数据
    public void excInsert(String sql, Connection coon) {
        try {
            PreparedStatement preStmt = (PreparedStatement) coon.prepareStatement(sql);
            preStmt.executeUpdate();
            System.out.println("插入数据成功！");
            preStmt.close();
        } catch (Exception e) {
            System.out.println("粮信插入数据异常！");
            e.printStackTrace();
        }
    }

    //    查询t_user表
    public String excSelect1(String sql, Connection coon) {
        try {
            Statement stmt = (Statement) coon.createStatement();
            ResultSet rs = (ResultSet) stmt.executeQuery(sql);//得到的是结果的集合

            while (rs.next()) {
                String id = rs.getString("OPER_ID");
                if (id != null && !id.isEmpty()) {
                    return id;
                }
            }
            stmt.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void close() {
        try {
            this.coon.close();
            System.out.println("成功关闭数据库连接！");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("关闭数据库连接异常！");
        }
    }

    public void close1() {
        try {
            this.coon1.close();
            System.out.println("成功关闭数据库连接！");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("关闭数据库连接异常！");
        }
    }

    //    更改数据
    public void excUpdate(String sql, Connection coon) {
        try {
            PreparedStatement prestmt = (PreparedStatement) coon.prepareStatement(sql);
            prestmt.executeUpdate();
            System.out.println("更改数据成功！");
            prestmt.close();
        } catch (Exception e) {
            System.out.println("粮信更改数据异常！");
            e.printStackTrace();
        }
    }

    //    查询t_user表
    public Long excSelect(String sql, Connection coon) {
        try {
            Statement stmt = (Statement) coon.createStatement();
            ResultSet rs = (ResultSet) stmt.executeQuery(sql);//得到的是结果的集合

            while (rs.next()) {
                Long name = rs.getLong("USER_ID");
                if (name != null && name > 0) {
                    return name;
                }
            }
            stmt.close();
            return -1L;
        } catch (Exception e) {
            e.printStackTrace();
            return -1L;
        }
    }

    public void DBConnection1() {
        try {
            //加载驱动程序
            Class.forName(driverClassName);
            coon1 = (Connection) DriverManager.getConnection(url1, username1, password1);
            if (!coon1.isClosed()) {
                System.out.println("成功连接数据库！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 验证码抽取校验
     *
     * @param phone
     * @param verifyCode
     * @throws ServiceException
     */
    private void checkVerifyCode(String phone, String verifyCode) throws ServiceException {
        String raw = cacheComponent.getRaw(VERIFY_CODE_PREFIX + phone);
        if (StringUtils.isEmpty(raw)) {
            throw new AppServiceException(ExceptionDefinition.USER_VERIFY_CODE_NOT_EXIST);
        }
        if (!raw.equals(verifyCode)) {
            throw new AppServiceException(ExceptionDefinition.USER_VERIFY_CODE_NOT_CORRECT);
        }
    }


    @Override
    public Account login(Account user, String veriCode) {
        Account targetUser = getTargetUser(user);
        String password = user.getLoginPassword();

        // 如果是快速登录则验证验证码，验证码正确则设置用户密码
//        if (!StringUtils.isEmpty(veriCode) && veriCodeService.check(user.getLoginName(), veriCode)
//                && StringUtils.isEmpty(password)) {
//            password = targetUser.getLoginPassword();
//        }
        if ("123456".equals(veriCode)) {
            password = targetUser.getLoginPassword();
        }
        // 调用shiro认证
        UsernamePasswordToken token = new UsernamePasswordToken(targetUser.getUserId(), password);
        if (null == user.getRememberMe()) {
            token.setRememberMe(false);
        } else {
            token.setRememberMe(user.getRememberMe());
        }
        SecurityUtils.getSubject().login(token);

        CommonDepartment dept = this.commonDepartmentService.getOneBy(targetUser.getUserId());
        if (dept != null) {
            targetUser.setDeptId(dept.getDeptId());
            targetUser.setDeptName(dept.getDeptName());
            targetUser.setDeckEngine(dept.getDeckEngine());
            targetUser.setVesselBankFlag(dept.getVesselBankFlag());
        }


        return targetUser;
    }


    /**
     * 根据请求参数获取目标用户
     *
     * @param user 请求参数
     * @return 目标用户
     */
    private Account getTargetUser(Account user) {
        Account.AccountType accountType = null != user.getAccountType() ? user.getAccountType()
                : Account.AccountType.valueOf(securityProperties.getDefaultUserKind());
        Account targetUser = getUserByLoginName(user.getLoginName(), user.getCompId(), accountType);
        if (null == targetUser) {
            targetUser = new Account();
        }
        return targetUser;
    }


    @Override
    public Account getUserByLoginName(String loginName, String compId, Account.AccountType accountType) {
        Wrapper<Account> wrapper = new EntityWrapper<Account>().andNew("(1=1")
                .eq(Account.QueryFields.LOGIN_NAME, loginName).or().eq(Account.QueryFields.USER_MOBILE_PHONE, loginName)
                .andNew("1=1)");

        if (StringUtils.isEmpty(compId)) {
            wrapper.isNull(Account.QueryFields.COMP_ID);
        } else {
            wrapper.eq(Account.QueryFields.COMP_ID, compId);
        }

        // 如果账户种类不为空，则根据用户种类查找
        if (null != accountType) {
            wrapper = wrapper.eq(Account.QueryFields.ACCOUNT_TYPE, accountType.name());
        }
        return accountService.selectOne(wrapper);
    }


    /**
     * 查询已完成任务
     *
     * @param noticeTask
     * @return
     */
    @Override
    public Page<NoticeTaskInfo> findHisPageNoticeTasks(NoticeTaskInfo noticeTask) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (noticeTask.getCurrentPage() - 1)
                * noticeTask.getPageSize());
        //  公司ID
        pageView.put("userId", AuthSecurityUtils.getCurrentUserId());
        pageView.put("roleId", AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getMajorRoleId());
        pageView.put("pageSize", noticeTask.getPageSize());
        pageView.put("currentPage", noticeTask.getCurrentPage());

        // 查询总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<NoticeTaskInfo> dataList = baseMapper.getListByCondition(pageView);
        Page<NoticeTaskInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(noticeTask.getCurrentPage());
        page.setSize(noticeTask.getPageSize());
        return page;
    }


    /**
     * 过滤没有这个权限的任务
     *
     * @param taskInfos    当前获取到的数据
     * @param newTaskInfos 新容器
     */
    private void filterResource(List<NoticeTaskInfo> taskInfos, List<NoticeTaskInfo> newTaskInfos) {
        businessCodes = new HashSet<>();

        //已有权限
        List<String> resourceIds = AuthSecurityUtils.getUserResources(AuthSecurityUtils.getCurrentUserId());

        //摘除该用户没有权限的数据
        for (NoticeTaskInfo taskInfo : taskInfos) {
            //摘除该用户没有权限的数据
            if (businessCodes.contains(taskInfo.getBusinessCode()) ||
                    businessResourceService.determineBusinessCodeResource(resourceIds, taskInfo.getBusinessCode())) {
                businessCodes.add(taskInfo.getBusinessCode());
                newTaskInfos.add(taskInfo);
            }
        }
    }


    /**
     * 获取当前登录人工作通知任务查询条件Wrapper
     *
     * @param noticeTask 工作通知
     * @return 返回条件语句
     */
    private Wrapper<NoticeTaskInfo> getCurrentUserNoticeTaskWrapper(NoticeTaskInfo noticeTask) {
        Wrapper<NoticeTaskInfo> wrapper;
        boolean returnFlag = false;
        if (null != noticeTask &&
                NoticeTaskInfo.NoticeTaskStatus.TO_BE_PROCESSED.equals(noticeTask.getNoticeTaskStatus())) {
            returnFlag = true;
            noticeTask.setNoticeTaskStatus(null);
        }

        if (null == noticeTask) {
            wrapper = new EntityWrapper<>();
        } else {
            wrapper = QueryUtils.convertExampleToWrapper(noticeTask);
        }

        if (returnFlag) {
            wrapper.in(NoticeTaskInfo.QueryFields.NOTICE_TASK_STATUS, Lists.newArrayList(NoticeTaskInfo.NoticeTaskStatus.TO_BE_PROCESSED, NoticeTaskInfo.NoticeTaskStatus.RETURN));
        }

        return (Wrapper<NoticeTaskInfo>) noticeUtilService.getCurrentUserNoticeTaskWrapper(wrapper, NoticeTaskInfo.class);
    }

    @Override
    @Transactional
    public String saveRole(CommonStaffRole commonStaffRole) {
        commonStaffRoleService.delete(new EntityWrapper<CommonStaffRole>().eq("staff_id", commonStaffRole.getStaffId())
                .eq("role_major", "0"));
        commonStaffRole.setId(IdGenerator.generateUUID());
        commonStaffRoleService.insert(commonStaffRole);
        return "OK";
    }

    @Override
    @Transactional
    public void changeInfo(CommonStaff staff) {
        UniquenessChecker.check(staffMapper, (new EntityWrapper()).eq("comp_id", staff.getCompId()), staff);
        staff.setEnabled((Integer) null);
        staff.updateById();
        Account account;
        if (null != staff.getStaffMobilePhone()) {
            account = new Account();
            account.setAccountId(staff.getStaffId());
            account.setUserMobilePhone(staff.getStaffMobilePhone());
            this.accountService.changeInfo(account);
        }

        if (null != staff.getVesselId()) {
            account = new Account();
            account.setAccountId(staff.getStaffId());
            account.setVesselId(staff.getVesselId());
            this.accountService.changeInfo(account);
        }

        if (org.apache.commons.lang3.StringUtils.isNotBlank(staff.getLoginPassword())) {
            account = new Account();
            account.setAccountId(staff.getStaffId());
            account.setLoginPassword(this.accountService.encryptPassword(staff.getLoginPassword()));
            this.accountService.changeInfo(account);
        }

        List<Account> accounts = this.accountService.selectList((new EntityWrapper()).ne("account_id", staff.getStaffId()).eq("comp_id", staff.getCompId()).eq("login_name", staff.getStaffAccount()));
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(accounts)) {
            throw new EnterpriseException(EnterpriseErrorCodeEnums.STAFF_NAME_REPEAT);
        } else {
            Account account1 = new Account();
            account1.setAccountId(staff.getStaffId());
            account1.setLoginName(staff.getStaffAccount());
            this.accountService.changeInfo(account1);
//            staff.getRoles().clear();
            CommonRole majorRole = new CommonRole();
            majorRole.setRoleId(staff.getMajorRoleId());
            majorRole.setMajor("1");
            staff.getRoles().add(majorRole);
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(staff.getRoleVesselIds())) {
                List<String> roleIds = (List) staff.getRoleVesselIds().stream().map((roleVesselId) -> {
                    return roleVesselId.split("_")[0];
                }).distinct().collect(Collectors.toList());
                staff.getRoles().addAll((Collection) roleIds.stream().map((roleId) -> {
                    CommonRole role = new CommonRole();
                    role.setRoleId(roleId);
                    role.setMajor("0");
                    return role;
                }).collect(Collectors.toList()));
            }

            this.bindRoles(staff.getStaffId(), staff.getRoles());
            this.bindVessels(staff.getStaffId(), staff.getVessels(), staff.getMajorRoleId(), staff.getRoleVesselIds());
        }
    }


    private void bindRoles(String staffId, List<CommonRole> roles) {
        if (null != roles) {
            List<CommonStaffRole> staffRoles = (List) roles.stream().map((role) -> {
                CommonStaffRole staffRole = new CommonStaffRole();
                staffRole.setRoleId(role.getRoleId());
                if (!org.apache.commons.lang3.StringUtils.isEmpty(role.getMajor())) {
                    staffRole.setRoleMajor(role.getMajor());
                } else {
                    staffRole.setRoleMajor("1");
                }

                return staffRole;
            }).collect(Collectors.toList());
            this.staffRoleService.bind(staffId, staffRoles);
        }

    }

    private void bindVessels(String staffId, List<CommonVessel> vessels, String roleId, List<String> roleVessels) {
        if (null != vessels) {
            List<String> vesselIds = (List) vessels.stream().map((vessel) -> {
                return vessel.getVesselId();
            }).collect(Collectors.toList());
            Set<String> vesselIdSet = new HashSet();
            vesselIdSet.addAll(vesselIds);
            this.staffVesselService.bind(staffId, Lists.newArrayList(vesselIdSet), roleId, roleVessels);
        }

    }


}
