package org.springblade.modules.app.manager;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wn.common.exception.BusinessException;
import org.apache.commons.text.StringEscapeUtils;
import org.springblade.common.auth.UserContext;
import org.springblade.common.cache.CachesService;
import com.wn.common.datamodel.ModelConvertUtil;
import com.wn.common.datamodel.ResultDTO;
import org.springblade.common.notify.sms.AliSmsMsgNotify;
import com.wn.common.perfmonitor.annotation.ServiceTimeLog;
import com.wn.common.tools.date.DateUtils;
import com.wn.common.tools.security.MD5Utils;
import com.wn.common.tools.string.AccountValidatorUtils;
import com.wn.common.validator.Validator;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.app.dto.InnerCaptchaResultDTO;
import org.springblade.modules.app.client.IWidgetService;
import org.springblade.modules.app.client.ZmtClientService;
import org.springblade.modules.app.common.dto.*;
import org.springblade.modules.app.common.enums.*;
import org.springblade.modules.app.common.query.*;
import org.springblade.modules.app.common.vo.*;
import org.springblade.modules.app.constant.Constants;
import org.springblade.modules.app.constant.ErrorCode;
import org.springblade.modules.app.entity.CityDO;
import org.springblade.modules.app.entity.UserDO;
import org.springblade.modules.app.service.*;
import org.springblade.modules.app.utils.ErrorMsg;
import org.springblade.modules.app.utils.ResponseHandelUtil;
import org.springblade.modules.app.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IUserService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

@Slf4j
@Component
@RefreshScope
public class UserManager {

    private final String HEAD = this.getClass().getSimpleName() + ":";

    @Autowired
    private CaptchaManager captchaManager;

    @Autowired
    private ICityService cityService;
    @Autowired
    private BladeRedis redis;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private IAppUserService userService;
    @Autowired
    private IContractService contractService;
    @Autowired
    private IApplicationInfoService applicationInfoService;
    //    @Autowired
//    private IWidgetService widgetService;
    @Autowired
    private AliSmsMsgNotify aliSmsMsgNotify;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private ITransportService transportService;
    @Autowired
    private IWaybillService waybillService;
    @Autowired
    private ZmtClientService zmtClientService;
    @Autowired
    private ISlaughterBuyerRelationService slaughterBuyerRelationService;
    @Autowired
    private ISlaughterBuyerRelationLogService slaughterBuyerRelationLogService;
    @Autowired
    private MessageLoggingManager messageLoggingManager;

    @Resource
    private CachesService cachesService;
    @Value("${ifRegisterUserApproval}")
    private boolean ifRegisterUserApproval;
    @Value("${ali.sms.register.template}")
    private String registerPassTemplate;
    @Value("${ali.sms.register.template.reject}")
    private String registerRejectTemplate;
    @Value("${ali.sms.checkCode.template}")
    private String checkCodeTemplate;
    @Value("${debug.mode}")
    private Boolean debugMode;
    @Value("${debug.phone}")
    private String debugPhone;
    @Value("${debug.check.code}")
    private String debugCheckCode;
    @Value("${debug.user.id}")
    private Long debugUserId;

    /**
     * @param userLoginVO
     * @return java.lang.Boolean
     * @Param: request
     * @author FUXINSHENG
     * @date 2021/11/8 15:59
     * @describe 1、校验字段非空
     * 2、校验滑动验证码正常
     * 3、校验验证码发送次数
     * 4、根据不同的请求修改验证码模板
     * 5、发送短信
     */
    @ServiceTimeLog
    public Boolean sendSmsCode(UserLoginVO userLoginVO) {
        Validator.notNull(userLoginVO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(userLoginVO.getPhone(), ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(userLoginVO.getCaptcha(), ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(userLoginVO.getType(), ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.isTrue(AccountValidatorUtils.isMobile(userLoginVO.getPhone()), ErrorCode.AUTH_PHONE_REG_UNMATCH);


        InnerCaptchaResultDTO resultDTO = captchaManager.checkCaptcha(userLoginVO.getCaptcha());
        Validator.isTrue(StringUtils.isNotBlank(resultDTO.getRepCode()) && resultDTO.getRepCode().equals(Constants.RepCodesSuccessCode), ErrorMsg.NEW(resultDTO.getRepCode(), resultDTO.getRepMsg()));

        //每个手机获取验证码次数限制
        Integer smsLoginLimit = Constants.MAX_XYB_USER_SMS_COUNT;
        Integer phoneSmsCount = cachesService.getFromCache(Constants.XYB_SMS_COUNT, userLoginVO.getPhone());
        phoneSmsCount = phoneSmsCount == null ? 0 : phoneSmsCount;
        Validator.isTrue(phoneSmsCount < smsLoginLimit, ErrorCode.SMS_COUNT_LIMIT_OVER);
        phoneSmsCount++;
        log.info("获取手机短信验证码，手机号: {}, 今日已使用次数: {}", userLoginVO.getPhone(), phoneSmsCount);

        //过期时间设为当天剩余时间
        int remainSeconds = DateUtils.getSecondsFromNowToDayEnd().intValue();
        cachesService.putInCache(Constants.XYB_SMS_COUNT, userLoginVO.getPhone(), phoneSmsCount);
        cachesService.setExpired(Constants.XYB_SMS_COUNT, userLoginVO.getPhone(), remainSeconds);

        String smsCode = aliSmsMsgNotify.generateSmsCode(userLoginVO.getPhone());
        aliSmsMsgNotify.sendSms(userLoginVO.getPhone(), smsCode, checkCodeTemplate, null);
        return true;
    }

    /**
     * 登录
     *
     * @param userLoginVO
     * @return java.lang.Boolean
     * @Param: response
     * @Param: session
     * @author FUXINSHENG
     * @date 2021/11/8 17:59
     * @describe 1、校验用户验证码正确
     * 2、根据用户手机号获取用户信息，不存在则报错
     * 3、若存在，则获取用户所有信息，并存入session中
     */
    @ServiceTimeLog
    public UserDTO login(UserLoginVO userLoginVO, HttpServletResponse response, String ipAddress, HttpSession session) {
        Validator.notNull(userLoginVO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notEmpty(userLoginVO.getPhone(), ErrorCode.LOGIN_PHONE_NULL);
        log.info(HEAD + "用户登录:{}, 请求参数:{}", userLoginVO.getPhone(), JSON.toJSONString(userLoginVO));
        UserDTO user = new UserDTO();
        UserDTO userDTO;
        if (Boolean.TRUE.equals(debugMode) && userLoginVO.getPhone().equals(debugPhone) && userLoginVO.getSmsCode().equals(debugCheckCode)) {
            userDTO = userService.getUserById(debugUserId);
        } else {
            UserQuery userQuery = new UserQuery();
            userQuery.setPhone(userLoginVO.getPhone());
            userDTO = userService.getOneUser(userQuery);
//            validatorLoginLimit(userLoginVO.getPhone(), ipAddress);
            if (userLoginVO.getLoginType() == UserLoginTypeEnum.SMSCODE_LOGIN.getCode()) {
                checkSms(userLoginVO.getPhone(), userLoginVO.getSmsCode());
            } else if (userLoginVO.getLoginType() == UserLoginTypeEnum.PASSWORD_LOGIN.getCode()) {
                Validator.notBlank(userLoginVO.getPassword(), ErrorCode.PASSWORD_NULL);
                if (userDTO == null || StringUtils.isBlank(userDTO.getPassword())) {
                    Validator.isTrue(false, ErrorCode.USER_IS_NOT_REGISTERED);
                }
                if (!userDTO.getPassword().equals(userLoginVO.getPassword())) {
                    putSmsOrPassWordFailCache(userLoginVO.getPhone(), ipAddress);
                    Validator.isTrue(false, ErrorCode.ACCOUNT_NOT_FOUND_EXP);
                }
            } else {
                Validator.isTrue(false, ErrorCode.USER_IS_EXP);
            }

            if (userDTO == null) {
                log.info(HEAD + "用户登录:{}, 用户不存在, 需要注册！", userLoginVO.getPhone());
                user.setIfLogin(-1);
                return user;
            } else if (userDTO.getState() == 4) {
                log.info(HEAD + "用户登录:{}, 用户已禁用！", userLoginVO.getPhone());
                user.setIfLogin(UserLoginStateEnum.DISABLE.getCode());
                return user;
            } else if (userDTO.getState() == 6) {
                log.info(HEAD + "用户登录:{}, 用户已注销！", userLoginVO.getPhone());
                user.setIfLogin(UserLoginStateEnum.DELETED.getCode());
                return user;
            } else if (userDTO.getState() == UserStateEnum.UNCHECK.getCode()) {
//                ApplicationQuery query = new ApplicationQuery();
//                query.setLinkId(userDTO.getId());
//                query.setType(ApplicationTypeEnum.USER.getCode());
//                ApplicationInfoDTO applicationInfo = applicationInfoService.getApplicationInfoByQuery(query);
//                if (applicationInfo != null) {
//                    if (applicationInfo.getState() == ApplicationStateEnum.REJECT.getCode()) {
//                        user.setIfLogin(UserLoginStateEnum.REJECT.getCode());
//                        log.info(HEAD + "用户登录:{}, 用户已驳回, 需要重新提交！", userLoginVO.getPhone());
//                        return user;
//                    } else if (applicationInfo.getState() == ApplicationStateEnum.UNCHECK.getCode()) {
//                        user.setIfLogin(UserLoginStateEnum.UNCHECK.getCode());
//                        log.info(HEAD + "用户登录:{}, 用户审核中, 需要注册！", userLoginVO.getPhone());
//                        return user;
//                    }
//                }
//                if (userDTO.getType() == UserTypeEnum.SLAUGHTER_HOUSE.getCode()) {
//                    query.setType(ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode());
//                    applicationInfo = applicationInfoService.getApplicationInfoByQuery(query);
//                    if (applicationInfo.getState() == ApplicationStateEnum.REJECT.getCode()) {
//                        user.setIfLogin(UserLoginStateEnum.REJECT.getCode());
//                        log.info(HEAD + "用户登录:{}, 用户已驳回, 需要重新提交！", userLoginVO.getPhone());
//                        return user;
//                    } else if (applicationInfo.getState() == ApplicationStateEnum.UNCHECK.getCode()) {
//                        user.setIfLogin(UserLoginStateEnum.UNCHECK.getCode());
//                        log.info(HEAD + "用户登录:{}, 用户审核中。", userLoginVO.getPhone());
//                        return user;
//                    }
//                }
//                Validator.isTrue(false, ErrorCode.USER_IS_EXP);
            } else if (userDTO.getState() != UserStateEnum.PASS.getCode()) {
                //Validator.isTrue(false, ErrorCode.USER_IS_EXP);
            }
//            else if (UserTypeEnum.SLAUGHTER_HOUSE.getCode() == userDTO.getType() && (userDTO.getSlaughterHouseParentId() == null || userDTO.getSlaughterHouseParentId() == 0)) {
//                //log.info(HEAD + "用户:{}, 无挂靠屠宰场！", userLoginVO.getPhone(), JSON.toJSONString(userDTO));
//                user.setIfLogin(UserLoginStateEnum.NO_SLAUGHTER.getCode());
//                user.setId(userDTO.getId());
//                user.setUserName(userDTO.getUserName());
//                user.setPhone(userDTO.getPhone());
//                return user;
//            }
        }
        //缓存用户信息
        log.info(HEAD + "用户:{}, 登录成功！,用户信息{}", userLoginVO.getPhone(), JSON.toJSONString(userDTO));
        String token = cacheSession(userDTO, session, response, 0);
        userDTO.setIfLogin(userDTO.getState());
        userDTO.setToken(token);
        redis.set(userDTO.getId().toString(), token);
        return userDTO;
    }

    private void putSmsOrPassWordFailCache(String loginName, String ipAddress) {
        // 设置过期时间为当天剩余时间
        int remainSeconds = DateUtils.getSecondsFromNowToDayEnd().intValue();
        // 账号密码登录
        // 同一设备输错密码五次后，暂停其登录1小时
        Integer pausePwdFailCount = cachesService.getFromCache(Constants.LOGIN_FAIL_PWD_PAUSE_COUNT, loginName + ipAddress);
        pausePwdFailCount = pausePwdFailCount == null ? 1 : pausePwdFailCount + 1;
        cachesService.putInCache(Constants.LOGIN_FAIL_PWD_PAUSE_COUNT, loginName + ipAddress, pausePwdFailCount, remainSeconds);

        if (pausePwdFailCount >= 5) {
            // 如果连续输错指定错误次数，则暂停其登录1小时
            cachesService.putInCache(Constants.PWD_LOGIN_PAUSE, loginName + ipAddress, YesNoEnum.YES.getCode(), Constants.LOGIN_PAUSE_TIME);
        }
    }

    /**
     * 防刷配置校验
     *
     * @param loginName
     * @param ipAddress
     * @return void
     * @throws
     * @描述 :防刷配置校验
     * @创建人:WangPanPan
     * @创建时间:2021-06-28 3:36 PM
     * @修改人:
     * @修改时间:
     * @修改描述:
     * @date 2021-06-28 3:36 PM
     */
    private void validatorLoginLimit(String loginName, String ipAddress) {
        // 设置过期时间为当天剩余时间
        int remainSeconds = DateUtils.getSecondsFromNowToDayEnd().intValue();

        // 账号密码登录
        // 同一设备输错密码五次后，暂停其登录1小时分钟
        Integer pausePwdLogin = cachesService.getFromCache(Constants.PWD_LOGIN_PAUSE, loginName + ipAddress);
        Validator.isTrue(pausePwdLogin == null || YesNoEnum.NO.getCode().equals(pausePwdLogin), ErrorCode.LOGIN_PAUSE_COUNT_LIMIT_OVER);

        // 每日验证码或密码输入错误暂停1小时登录限量
        Integer loginPauseLimit = 5;

        // 如果同一设备输错密码次数到达5此后，但是暂停时间已到，则将错误次数清空
        Integer loginFailPwdPauseCount = cachesService.getFromCache(Constants.LOGIN_FAIL_PWD_PAUSE_COUNT, loginName + ipAddress);
        loginFailPwdPauseCount = loginFailPwdPauseCount == null ? 0 : loginFailPwdPauseCount;
        if (loginFailPwdPauseCount >= loginPauseLimit) {
            cachesService.putInCache(Constants.LOGIN_FAIL_PWD_PAUSE_COUNT, loginName + ipAddress, 0, remainSeconds);
        }
    }

    public void logout(HttpSession session) {
        Validator.notNullParameter(session, ErrorCode.MEMBER_NOT_EXIST);
        try {
            session.removeAttribute(session.getId());
            log.info("Member logout successfully");
        } catch (Exception e) {
            log.error("登出失败：" + e);
            Validator.isTrue(false, ErrorCode.LOGIN_OUT_FAIL);
        }
    }

    public Boolean checkSms(String phone, String smsCode) {
        Validator.isTrue(StringUtils.isNotBlank(phone), ErrorCode.USER_PHONE_NULL);
        Validator.isTrue(AccountValidatorUtils.isMobile(phone), ErrorCode.AUTH_PHONE_REG_UNMATCH);
        Validator.isTrue(StringUtils.isNotBlank(smsCode), ErrorCode.USER_SMS_CODE_NULL);
        //校验短信验证码
        Validator.isTrue(aliSmsMsgNotify.verifySmsCode(phone, smsCode), ErrorCode.USER_SMS_CODE_ERROR);
        return true;
    }


    public UserDTO getNoPassUser(UserLoginVO userLoginVO) {
        Validator.notNull(userLoginVO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(userLoginVO.getPhone(), ErrorCode.LOGIN_PHONE_NULL);
        log.info(HEAD + "查询已驳回用户, 请求参数:{}", JSON.toJSONString(userLoginVO));
        UserQuery userQuery = new UserQuery();
        userQuery.setPhone(userLoginVO.getPhone());
        UserDTO userDTO = userService.getOneUser(userQuery);
        Validator.notNull(userDTO, ErrorCode.USER_IS_NOT_REGISTERED);
        Boolean userPass = true;
        ApplicationQuery query = new ApplicationQuery();
        query.setSubmitUserId(userDTO.getId());
        if (ifRegisterUserApproval) {
            query.setType(ApplicationTypeEnum.USER.getCode());
            ApplicationInfoDTO applicationInfoBySubmitId = applicationInfoService.getApplicationInfoByQuery(query);
            userPass = applicationInfoBySubmitId.getState() == ApplicationStateEnum.PASS.getCode();
        }
        if (userDTO.getType() == UserTypeEnum.SLAUGHTER_HOUSE.getCode()) {
            query.setType(ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode());
            ApplicationInfoDTO applicationInfoBySubmitId = applicationInfoService.getApplicationInfoByQuery(query);
            userPass = userPass && applicationInfoBySubmitId.getState() == ApplicationStateEnum.PASS.getCode();
        }

        Validator.isTrue(!userPass, ErrorCode.USER_IS_PASS);
        return userDTO;
    }

    /**
     * @param userDTO
     * @param session
     * @param response
     * @description: 缓存用户信息
     * @return: void
     * @author: FUXINSHENG
     * @time: 2021-11-09 6:56 AM
     * @version:
     */
    private String cacheSession(UserDTO userDTO, HttpSession session,
                                HttpServletResponse response, Integer ifRememberLogin) {

        if (ifRememberLogin.equals(YesNoEnum.YES.getCode())) {
            session.setAttribute("PHONE", userDTO.getPhone());
            String sign = userDTO.getId() + userDTO.getPassword();
            String md5 = MD5Utils.getMD5(sign);
            session.setAttribute("PASSWORD", md5);
        }

        userDTO.setPassword(null);

        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.HOUR, 120);

        Map<String, Object> payload = new HashMap<String, Object>();
        payload.put(JWTPayload.ISSUED_AT, now);
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        payload.put(JWTPayload.NOT_BEFORE, now);

        payload.put("userName", userDTO.getUserName());
        payload.put("userId", userDTO.getId());
        payload.put("phone", userDTO.getPhone());
        payload.put("userDto", JSON.toJSONString(userDTO));

        String key = "xumutong";
        String token = JWTUtil.createToken(payload, key.getBytes());


        return token;

//        log.info("Member {} login successfully, cookie = {}", userDTO.getPhone(),
//                JSON.toJSONString(cookie));
    }

    public UserDTO getUserInfo(String token) {
        return userUtils.getUser(token);
    }


    /**
     * 用户注册
     *
     * @param userDTO
     * @return java.lang.String
     * @author FUXINSHENG
     * @date 2021/11/9 8:50
     * @describe 1、获取用户手机号码
     * 2、校验用户注册验证码正确
     * 3、校验用户未注册
     * 4、校验用户数据正确
     * 5、添加用户审核
     * 6、新增用户
     */
    @Transactional(rollbackFor = Exception.class)
    public String register(UserDTO userDTO, int isPsaa) {
        Validator.notNull(userDTO, ErrorCode.INPUT_PARAMETERS_NULL);
        checkSms(userDTO.getPhone(), userDTO.getSmsCode());
        log.info(HEAD + "用户注册, 请求参数:{}", JSON.toJSONString(userDTO));

        int Initiator = UserTypeEnum.SLAUGHTER_HOUSE.getCode();
        registercheckUserParam(userDTO);
        if (isPsaa == UserStateEnum.PASS.getCode()) {
            userDTO.setState(UserStateEnum.PASS.getCode());
            Initiator = UserTypeEnum.SLAUGHTER.getCode();
        }
        Long userId = userService.addUser(userDTO);
        userDTO.setId(userId);
        if (ifRegisterUserApproval) {
            ApplicationInfoDTO applicationInfoDTO = new ApplicationInfoDTO();
            applicationInfoDTO.setType(ApplicationTypeEnum.USER.getCode());
            applicationInfoDTO.setLinkId(userId);
            applicationInfoDTO.setLinkTable(Constants.TB_USER);
            applicationInfoDTO.setSubmitUserId(userId);
            applicationInfoDTO.setSubmitPhone(userDTO.getPhone());
            applicationInfoDTO.setSubmitUserName(userDTO.getUserName());
            if (isPsaa == UserStateEnum.PASS.getCode()) {
                applicationInfoDTO.setState(ApplicationStateEnum.PASS.getCode());
                applicationInfoDTO.setMessage("自动审核通过");
            }
            log.info(HEAD + "用户注册, 初始化审核记录:{}", JSON.toJSONString(applicationInfoDTO));
            applicationInfoService.addApplicationInfo(applicationInfoDTO);
        }
        if (userDTO.getType() == UserTypeEnum.SLAUGHTER_HOUSE.getCode()) {
            UserDTO slaughter = null;
            ApplicationInfoDTO applicationInfoDTO = initApplicationInfo(ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode(), userId, slaughter, userDTO);
            applicationInfoDTO.setLinkTable(Constants.TB_USER);
            if (isPsaa == UserStateEnum.PASS.getCode()) {
                applicationInfoDTO.setState(ApplicationStateEnum.PASS.getCode());
                applicationInfoDTO.setMessage("自动审核通过");
            }
            log.info(HEAD + "用户注册, 初始化代宰户审核记录:{}", JSON.toJSONString(applicationInfoDTO));
            applicationInfoService.addApplicationInfo(applicationInfoDTO);
        }
        //改造：建立绑定关系，只有是创建代宰户才建立
//        if (userDTO.getType() == UserTypeEnum.SLAUGHTER_HOUSE.getCode()) {
//            SlaughterBuyerRelationDTO dto = new SlaughterBuyerRelationDTO();
//            dto.setBuyerUserId(userDTO.getSlaughterHouseParentId());
//            dto.setSlaughterHouseId(Long.valueOf(userId));
//            dto.setInitiator(Initiator);
//            //如果是屠宰场新增的直接是已绑定
//            if (isPsaa == UserStateEnum.PASS.getCode()) {
//                dto.setState(RelationStateEnum.BIND.getCode());
//                dto.setBindTime(new Date());
//                dto.setRemark("自动审核通过");
//            }
//            Validator.notNull(slaughterBuyerRelationService.insert(dto), ErrorCode.RELATION_INSERT_FAIL);
//        }
        if (isPsaa == UserStateEnum.PASS.getCode() || (!ifRegisterUserApproval && userDTO.getType() != UserTypeEnum.SLAUGHTER_HOUSE.getCode())) {
            sendPassNotifyMessage(userDTO.getPhone());
        }

        User user = new User();
        user.setUserType(2);
        user.setTenantId("000000");
        user.setPassword("040bd08a4290267535cd247b8ba2eca129d9fe9f");
        user.setName(userDTO.getUserName());
//        user.setRealName(userDTO.getUserName());
        user.setPhone(userDTO.getPhone());
        user.setAccount(userDTO.getPhone());
        iUserService.save(user);
        userService.update(Wrappers.<UserDO>lambdaUpdate().eq(UserDO::getId, userId).set(UserDO::getSysUserId, user.getId()));

        return userId.toString();
    }

    public ApplicationInfoDTO initApplicationInfo(Integer type, Long linkId, UserDTO applyUser, UserDTO submitUser) {
        ApplicationInfoDTO applicationInfoDTO = new ApplicationInfoDTO();
        applicationInfoDTO.setType(type);
        applicationInfoDTO.setLinkId(linkId);
        applicationInfoDTO.setState(ApplicationStateEnum.UNCHECK.getCode());
        applicationInfoDTO.setSubmitUserId(submitUser.getId());
        applicationInfoDTO.setSubmitUserName(submitUser.getUserName());
        applicationInfoDTO.setSubmitPhone(submitUser.getPhone());
        applicationInfoDTO.setApplyUserId(StringUtil.isEmpty(applyUser) ? 0L : applyUser.getId());
        applicationInfoDTO.setApplyPhone(StringUtil.isEmpty(applyUser) ? "" : applyUser.getPhone());
        applicationInfoDTO.setApplyUserName(StringUtil.isEmpty(applyUser) ? "" : applyUser.getUserName());
        return applicationInfoDTO;
    }

    private void checkUserPassword(String password, String confirmPassword) {
        Validator.notNull(password, ErrorCode.USER_PASSWORD_NULL);
        Validator.notNull(confirmPassword, ErrorCode.USER_CONFIRM_PASSWORD_NULL);
        Validator.isTrue(password.equals(confirmPassword), ErrorCode.USER_CONFIRM_PASSWORD_ERROR);
    }

    private void checkUserParam(UserDTO userDTO) {
        Integer userType = userDTO.getType();
        checkUserPassword(userDTO.getPassword(), userDTO.getConfirmPassword());
        Validator.notNull(userDTO.getProvId(), ErrorCode.USER_PROV_NULL);
        Validator.notNull(userDTO.getCityId(), ErrorCode.USER_CITY_NULL);
        Validator.notNull(userDTO.getAreaId(), ErrorCode.USER_AREA_NULL);
        UserQuery userQuery = new UserQuery();
        userQuery.setPhone(userDTO.getPhone());
        UserDTO userByPhone = userService.getOneUser(userQuery);
        log.error("user phone is {}", userByPhone);
        if (userByPhone != null && userDTO.getId() != null) {
            Validator.isTrue(userByPhone.getId().equals(userDTO.getId()), ErrorCode.USER_IS_REGISTERED);
        } else {
            log.error("user phone is {}", userByPhone);
            Validator.isNull(userByPhone, ErrorCode.USER_IS_REGISTERED);
        }
        if (userType == UserTypeEnum.SLAUGHTER.getCode() || userType == UserTypeEnum.FARM.getCode()) {
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getBusinessLinkMan()), ErrorCode.USER_LINK_NAME_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getBusinessUrl()), ErrorCode.USER_BUSINESS_URL_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getUserName()), ErrorCode.USER_COMPANY_NAME_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getBusinessIndustryCategrory()), ErrorCode.USER_BUSINESS_CATEGORY_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getAddress()), ErrorCode.USER_BUSINESS_ADDRESS_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getBusinessLegalPerson()), ErrorCode.USER_BUSINESS_LEGAL_NULL);
//            Validator.notNull(userDTO.getBusinessTerm(), ErrorCode.USER_BUSINESS_TERM_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getBusinessScope()), ErrorCode.USER_BUSINESS_SCOPE_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getCreditCode()), ErrorCode.USER_CREDIT_CODE_NULL);
            userQuery = new UserQuery();
            userQuery.setName(userDTO.getUserName());
            UserDTO oneUser = userService.getOneUser(userQuery);
            Validator.isTrue(StringUtil.isEmpty(oneUser), ErrorCode.USER_IS_REGISTERED);
        } else {
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getUserName()), ErrorCode.USER_NAME_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getCreditCode()), ErrorCode.USER_ID_CODE_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getAddress()), ErrorCode.USER_ADDRESS_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getIdCardFrontUrl()), ErrorCode.USER_ID_CARD_FRONT_URL_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getIdCardBehindUrl()), ErrorCode.USER_ID_CARD_BEHIND_URL_NULL);
        }

        if (userType == UserTypeEnum.SLAUGHTER.getCode()) {
            OutApiSyncUserParamVO userParamVO = new OutApiSyncUserParamVO();
            userParamVO.setUser_name(userDTO.getZmtName());
            userParamVO.setBusiness_license(userDTO.getCreditCode());
            OutApiSyncUserResultVO subject = zmtClientService.getSubject(userParamVO);
            Validator.notNull(subject, ErrorCode.USER_IS_REGISTERED_IN_ZMT);
            UserDO userDO = userService.getOne(Wrappers.<UserDO>lambdaQuery().eq(UserDO::getZmtId,subject.getCompanyId()));
            Validator.isTrue(StringUtil.isEmpty(userDO), ErrorCode.RELATION_IS_EXISTED);
            userDTO.setZmtId(subject.getCompanyId());
            userDTO.setZmtType(subject.getType());
            userDTO.setZmtUserId(subject.getUserId());
            userDTO.setZmtUserName(subject.getName());
        }

        if (userType == UserTypeEnum.FARM.getCode()) {
            Validator.isTrue(StringUtils.isNotBlank(userDTO.getBreedCode()), ErrorCode.NO_BREED_CODE_PASS_NULL);
        }

        if (userType == UserTypeEnum.DRIVER.getCode()) {
            //Validator.isTrue(StringUtils.isNotBlank(userDTO.getDriverLicenceUrl()), ErrorCode.USER_DRIVER_LICENSE_URL_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getDriverLicenceCode()), ErrorCode.USER_DRIVER_LICENSE_CODE_NULL);
            Validator.isTrue(StringUtils.isNotBlank(userDTO.getDriverCarType()), ErrorCode.USER_DRIVER_LICENSE_CAR_TYPE_NULL);
            Validator.notNull(userDTO.getDriverLicenceExpiryDate(), ErrorCode.USER_DRIVER_LICENSE_EXPIRY_DATE_NULL);
            Validator.isTrue(StringUtils.isNotBlank(userDTO.getVehicleLicenseUrl()), ErrorCode.USER_VEHICLE_LICENSE_URL_NULL);
            Validator.isTrue(StringUtils.isNotBlank(userDTO.getVehicleLicenseCode()), ErrorCode.USER_VEHICLE_LICENSE_CODE_NULL);
            Validator.isTrue(StringUtils.isNotBlank(userDTO.getTransportPermitUrl()), ErrorCode.USER_TRANSPORT_PERMIT_URL_NULL);
            Validator.isTrue(StringUtils.isNotBlank(userDTO.getTransportPermitCode()), ErrorCode.USER_TRANSPORT_PERMIT_CODE_NULL);
        }

        if (userType == UserTypeEnum.SLAUGHTER_HOUSE.getCode()) {
            Validator.notNull(userDTO.getSlaughterHouseType(), ErrorCode.USER_SLAUGHTER_HOUSE_TYPE_NULL);
            Validator.notNull(StringUtils.isNotBlank(userDTO.getSlaughterHouseParentName()), ErrorCode.USER_SLAUGHTER_HOUSE_PARENT_NULL);
            UserQuery query = new UserQuery();
            query.setName(userDTO.getSlaughterHouseParentName());
            query.setType(UserTypeEnum.SLAUGHTER.getCode());
            UserDTO slaughter = userService.getOneUser(query);
            Validator.notNull(slaughter, ErrorCode.SLAUGHTER_IS_NULL);
            userDTO.setSlaughterHouseParentId(slaughter.getId());
        }
        userDTO.setState(!ifRegisterUserApproval && userDTO.getType() != UserTypeEnum.SLAUGHTER_HOUSE.getCode() ? YesNoEnum.YES.getCode() : YesNoEnum.NO.getCode());
    }

    private void registercheckUserParam(UserDTO userDTO) {
        Integer userType = userDTO.getType();
        checkUserPassword(userDTO.getPassword(), userDTO.getConfirmPassword());
//        Validator.notNull(userDTO.getProvId(), ErrorCode.USER_PROV_NULL);
//        Validator.notNull(userDTO.getCityId(), ErrorCode.USER_CITY_NULL);
//        Validator.notNull(userDTO.getAreaId(), ErrorCode.USER_AREA_NULL);
        UserQuery userQuery = new UserQuery();
        userQuery.setPhone(userDTO.getPhone());
        UserDTO userByPhone = userService.getOneUser(userQuery);
        log.error("user phone is {}", userByPhone);
        if (userByPhone != null && userDTO.getId() != null) {
            Validator.isTrue(userByPhone.getId().equals(userDTO.getId()), ErrorCode.USER_IS_REGISTERED);
        } else {
            log.error("user phone is {}", userByPhone);
            Validator.isNull(userByPhone, ErrorCode.USER_IS_REGISTERED);
        }
        if (userType == UserTypeEnum.SLAUGHTER.getCode() || userType == UserTypeEnum.FARM.getCode()) {
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getBusinessLinkMan()), ErrorCode.USER_LINK_NAME_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getBusinessUrl()), ErrorCode.USER_BUSINESS_URL_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getUserName()), ErrorCode.USER_COMPANY_NAME_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getBusinessIndustryCategrory()), ErrorCode.USER_BUSINESS_CATEGORY_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getAddress()), ErrorCode.USER_BUSINESS_ADDRESS_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getBusinessLegalPerson()), ErrorCode.USER_BUSINESS_LEGAL_NULL);
//            Validator.notNull(userDTO.getBusinessTerm(), ErrorCode.USER_BUSINESS_TERM_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getBusinessScope()), ErrorCode.USER_BUSINESS_SCOPE_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getCreditCode()), ErrorCode.USER_CREDIT_CODE_NULL);
            userQuery = new UserQuery();
            userQuery.setName(userDTO.getUserName());
            UserDTO oneUser = userService.getOneUser(userQuery);
//            if (userDTO.getId() != null && oneUser != null) {
//                Validator.isTrue(oneUser.getId().equals(userDTO.getId()), ErrorCode.USER_IS_REGISTERED);
//            } else {
//                log.error("user oneUser is {}", oneUser);
//                Validator.notNull(oneUser, ErrorCode.USER_IS_REGISTERED);
//            }
        } else {
            Validator.isTrue(StringUtils.isNotBlank(userDTO.getUserName()), ErrorCode.USER_NAME_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getCreditCode()), ErrorCode.USER_ID_CODE_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getAddress()), ErrorCode.USER_ADDRESS_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getIdCardFrontUrl()), ErrorCode.USER_ID_CARD_FRONT_URL_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getIdCardBehindUrl()), ErrorCode.USER_ID_CARD_BEHIND_URL_NULL);
        }

        if (userType == UserTypeEnum.SLAUGHTER.getCode()) {
//            OutApiSyncUserParamVO userParamVO = new OutApiSyncUserParamVO();
//            userParamVO.setUser_name(userDTO.getZmtName());
//            userParamVO.setBusiness_license(userDTO.getCreditCode());
//            OutApiSyncUserResultVO subject = zmtClientService.getSubject(userParamVO);
//            Validator.notNull(subject, ErrorCode.USER_IS_REGISTERED_IN_ZMT);
//            userDTO.setZmtId(subject.getCompanyId());
//            userDTO.setZmtType(subject.getType());
//            userDTO.setZmtUserId(subject.getUserId());
//            userDTO.setZmtUserName(subject.getName());
        }

        if (userType == UserTypeEnum.FARM.getCode()) {
            //Validator.isTrue(StringUtils.isNotBlank(userDTO.getBreedCode()), ErrorCode.NO_BREED_CODE_PASS_NULL);
        }

        if (userType == UserTypeEnum.DRIVER.getCode()) {
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getDriverLicenceUrl()), ErrorCode.USER_DRIVER_LICENSE_URL_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getDriverLicenceCode()), ErrorCode.USER_DRIVER_LICENSE_CODE_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getDriverCarType()), ErrorCode.USER_DRIVER_LICENSE_CAR_TYPE_NULL);
//            Validator.notNull(userDTO.getDriverLicenceExpiryDate(), ErrorCode.USER_DRIVER_LICENSE_EXPIRY_DATE_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getVehicleLicenseUrl()), ErrorCode.USER_VEHICLE_LICENSE_URL_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getVehicleLicenseCode()), ErrorCode.USER_VEHICLE_LICENSE_CODE_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getTransportPermitUrl()), ErrorCode.USER_TRANSPORT_PERMIT_URL_NULL);
//            Validator.isTrue(StringUtils.isNotBlank(userDTO.getTransportPermitCode()), ErrorCode.USER_TRANSPORT_PERMIT_CODE_NULL);
        }

        if (userType == UserTypeEnum.SLAUGHTER_HOUSE.getCode()) {
            //Validator.notNull(userDTO.getSlaughterHouseType(), ErrorCode.USER_SLAUGHTER_HOUSE_TYPE_NULL);
            //Validator.notNull(StringUtils.isNotBlank(userDTO.getSlaughterHouseParentName()), ErrorCode.USER_SLAUGHTER_HOUSE_PARENT_NULL);
//            UserQuery query = new UserQuery();
//            query.setName(userDTO.getSlaughterHouseParentName());
//            query.setType(UserTypeEnum.SLAUGHTER.getCode());
//            UserDTO slaughter = userService.getOneUser(query);
//            Validator.notNull(slaughter, ErrorCode.SLAUGHTER_IS_NULL);
//            userDTO.setSlaughterHouseParentId(slaughter.getId());
        }
        userDTO.setState(!ifRegisterUserApproval && userDTO.getType() != UserTypeEnum.SLAUGHTER_HOUSE.getCode() ? YesNoEnum.YES.getCode() : YesNoEnum.NO.getCode());
    }

    public UserDTO checkSmsCode(UserLoginVO userLoginVO) {
        UserDTO user = new UserDTO();
        checkSms(userLoginVO.getPhone(), userLoginVO.getSmsCode());
        if (userLoginVO.getType() == 3) {
            UserDTO presentUser = userUtils.getUser(userLoginVO.getToken());
            log.info(HEAD + "用户更换手机号短信验证码校验, 请求参数:{}, 当前用户:{}", JSON.toJSONString(userLoginVO), presentUser.getId());
            Validator.isTrue(userLoginVO.getPhone().equals(presentUser.getPhone()), ErrorCode.NO_POWER_GET);
        } else if (userLoginVO.getType() == 4) {
            UserDTO presentUser = userUtils.getUser(userLoginVO.getToken());
            log.info(HEAD + "用户更换手机号短信验证码校验, 请求参数:{}, 当前用户:{}", JSON.toJSONString(userLoginVO), presentUser.getId());
            Validator.isTrue(!userLoginVO.getPhone().equals(presentUser.getPhone()), ErrorCode.NO_EQUALS_PHONE);
        } else if (userLoginVO.getType() == 2) {
            log.info(HEAD + "注册短信验证码校验, 请求参数:{}", JSON.toJSONString(userLoginVO));
            UserQuery userQuery = new UserQuery();
            userQuery.setPhone(userLoginVO.getPhone());
            checkUserPassword(userLoginVO.getPassword(), userLoginVO.getConfirmPassword());
            UserDTO userDTO = userService.getOneUser(userQuery);
            if (userDTO == null) {
                log.info(HEAD + "用户注册:{}, 用户不存在", userLoginVO.getPhone());
                user.setIfLogin(UserLoginStateEnum.UNREGISTER.getCode());
            } else if (userDTO.getState() == UserStateEnum.REJECT.getCode()) {
                log.info(HEAD + "用户注册:{}, 用户已禁用！", userLoginVO.getPhone());
                user.setIfLogin(UserLoginStateEnum.DISABLE.getCode());
                Validator.isTrue(false, ErrorCode.USER_IS_DISABLE);
            } else if (userDTO.getState() == UserStateEnum.PASS.getCode()) {
                log.info(HEAD + "用户注册:{}, 用户已注册！", userLoginVO.getPhone());
                user.setIfLogin(UserLoginStateEnum.PASS.getCode());
                Validator.isTrue(false, ErrorCode.USER_IS_REGISTERED);
            } else if (userDTO.getState() == UserStateEnum.UNCHECK.getCode()) {
                ApplicationQuery query = new ApplicationQuery();
                query.setLinkId(userDTO.getId());
                query.setType(ApplicationTypeEnum.USER.getCode());
                ApplicationInfoDTO applicationInfo = applicationInfoService.getApplicationInfoByQuery(query);
                if (applicationInfo != null) {
                    if (applicationInfo.getState() == ApplicationStateEnum.REJECT.getCode()) {
                        user.setIfLogin(UserLoginStateEnum.REJECT.getCode());
                        log.info(HEAD + "用户注册:{}, 管理单已驳回, 需要重新提交！", userLoginVO.getPhone());
                    } else if (applicationInfo.getState() == ApplicationStateEnum.UNCHECK.getCode()) {
                        user.setIfLogin(UserLoginStateEnum.UNCHECK.getCode());
                        log.info(HEAD + "用户注册:{}, 管理端审核中.！", userLoginVO.getPhone());
                    }
                }
                if (userDTO.getType() == UserTypeEnum.SLAUGHTER_HOUSE.getCode()) {
                    query.setType(ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode());
                    applicationInfo = applicationInfoService.getApplicationInfoByQuery(query);
                    if (applicationInfo.getState() == ApplicationStateEnum.REJECT.getCode()) {
                        if (user.getIfLogin() == null || user.getIfLogin() != UserLoginStateEnum.REJECT.getCode()) {
                            user.setIfLogin(UserLoginStateEnum.REJECT.getCode());
                            log.info(HEAD + "用户注册:{}, 屠宰场用户已驳回, 需要重新提交！", userLoginVO.getPhone());
                        }
                    } else if (applicationInfo.getState() == ApplicationStateEnum.UNCHECK.getCode() && (user.getIfLogin() == null || user.getIfLogin() != UserLoginStateEnum.REJECT.getCode())) {
                        user.setIfLogin(UserLoginStateEnum.UNCHECK.getCode());
                        log.info(HEAD + "用户注册:{}, 屠宰场用户审核中。", userLoginVO.getPhone());
                    }
                }
            }
            if (user.getIfLogin() == UserLoginStateEnum.UNCHECK.getCode()) {
                Validator.isTrue(false, ErrorCode.USER_IS_APPLY);
            }
        } else if (userLoginVO.getType() == 1) {
            log.info(HEAD + "登录短信验证码校验, 请求参数:{}", JSON.toJSONString(userLoginVO));
        }
        return user;
    }

    @ServiceTimeLog
    public UserDTO getAgent(UserQuery query) {
        UserDTO presentUser = userUtils.getUser(query.getToken());
        log.info(HEAD + "查询经纪人基本信息, 请求参数:{}, 当前登录用户id:{}", JSON.toJSONString(query), presentUser.getId());
        Validator.isTrue(presentUser.getType() == UserTypeEnum.SLAUGHTER.getCode()
                || presentUser.getType() == UserTypeEnum.SLAUGHTER_HOUSE.getCode(), ErrorCode.NO_POWER_GET);
        Validator.notNull(query, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(query.getPhone(), ErrorCode.INPUT_PARAMETERS_NULL);
        query.setName(null);
        query.setType(UserTypeEnum.AGENT.getCode());
        UserDTO userDTO = userService.getOneUser(query);
        Validator.notNull(userDTO, ErrorCode.AGENT_IS_NULL);
        UserDTO agent = new UserDTO();
        agent.setId(userDTO.getId());
        agent.setUserName(userDTO.getUserName());
        agent.setPhone(userDTO.getPhone());
        return agent;
    }

    @ServiceTimeLog
    public UserDTO getDriver(UserQuery query) {
        UserDTO presentUser = userUtils.getUser(query.getToken());
        log.info(HEAD + "查询司机基本信息, 请求参数:{}, 当前登录用户id:{}", JSON.toJSONString(query), presentUser.getId());
        Validator.isTrue(presentUser.getType() != UserTypeEnum.DRIVER.getCode()
                , ErrorCode.NO_POWER_GET);
        Validator.notNull(query, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(query.getPhone(), ErrorCode.USER_PHONE_NULL);
        query.setName(null);
        query.setType(UserTypeEnum.DRIVER.getCode());
        UserDTO userDTO = userService.getOneUser(query);
        Validator.notNull(userDTO, ErrorCode.DRIVER_IS_NULL);
        UserDTO driver = new UserDTO();
        driver.setId(userDTO.getId());
        driver.setUserName(userDTO.getUserName());
        driver.setPhone(userDTO.getPhone());
        driver.setDriverLicenceCode(userDTO.getDriverLicenceCode());
        driver.setVehicleLicenseCode(userDTO.getVehicleLicenseCode());
        driver.setTransportPermitCode(userDTO.getTransportPermitCode());
        return driver;
    }

    public Page<SlaughterHouseVO> getSlaughterHousePage(SlaughterHouseQuery query) {
        UserDTO presentUser = userUtils.getUser(query.getToken());
        log.info(HEAD + "分页查询待宰户基本信息, 请求参数:{}, 当前登录用户id:{}", JSON.toJSONString(query), presentUser.getId());
        Validator.isTrue(presentUser.getType() == UserTypeEnum.SLAUGHTER.getCode(), ErrorCode.NO_POWER_GET);
        query.setUserId(presentUser.getId());
        Page<SlaughterHouseVO> page = userService.getSlaughterHousePage(query);
        List<SlaughterHouseVO> records = page.getRecords();
        ApplicationQuery applicationQuery = new ApplicationQuery();
        applicationQuery.setType(ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode());
        for (SlaughterHouseVO slaughterHouseVO : records) {
            applicationQuery.setSubmitUserId(slaughterHouseVO.getId());
            ApplicationInfoDTO applicationInfoDTO = applicationInfoService.getApplicationInfoByQuery(applicationQuery);
            slaughterHouseVO.setState(applicationInfoDTO.getState() + 1);
        }
        return page;
    }

    public UserDTO getSlaughterHouse(Long slaughterHouseId, String token) {
        UserDTO presentUser = userUtils.getUser(token);
        log.info(HEAD + "分页查询待宰户基本信息, 代宰户id:{}, 当前登录用户id:{}", slaughterHouseId, presentUser.getId());
        UserDTO slaughterHouse = userService.getUserById(slaughterHouseId);
        Validator.notNull(slaughterHouse, ErrorCode.SLAUGHTER_HOUSE_IS_NULL);
        //Validator.isTrue(slaughterHouse.getSlaughterHouseParentId().equals(presentUser.getId()), ErrorCode.NO_POWER_GET);
        Validator.notNull(slaughterBuyerRelationService.queryByHouseIdAndBuyerId(slaughterHouseId, presentUser.getId()), ErrorCode.NO_POWER_GET);
        //修改：绑定关系状态从绑定关系表取
        SlaughterBuyerRelationDTO slaughterBuyerRelationDTO = slaughterBuyerRelationService.queryByHouseIdAndBuyerId(slaughterHouseId, presentUser.getId());
        Validator.notNull(slaughterBuyerRelationDTO, ErrorCode.RELATION_ISNULL);
        slaughterHouse.setRelationState(slaughterBuyerRelationDTO.getState());
//        ApplicationQuery applicationQuery = new ApplicationQuery();
//        applicationQuery.setType(ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode());
//        applicationQuery.setSubmitUserId(slaughterHouse.getId());
//        ApplicationInfoDTO applicationInfoDTO = applicationInfoService.getApplicationInfoByQuery(applicationQuery);
//        if (applicationInfoDTO.getState() != ApplicationStateEnum.UNCHECK.getCode()) {
//            slaughterHouse.setState(applicationInfoDTO.getState() == ApplicationStateEnum.PASS.getCode() ? UserStateEnum.PASS.getCode() : UserStateEnum.REJECT.getCode());
//        }
        return slaughterHouse;
    }

    public String creatSlaughterHouse(UserDTO slaughterHouse) {
        UserDTO presentUser = userUtils.getUser(slaughterHouse.getToken());
        log.info(HEAD + "创建代宰户, 请求参数:{}, 当前登录用户id:{}", slaughterHouse, presentUser.getId());
        Validator.isTrue(slaughterHouse.getSlaughterHouseParentId().equals(presentUser.getId()), ErrorCode.NO_POWER_GET);
        Validator.isTrue(slaughterHouse.getType() == UserTypeEnum.SLAUGHTER_HOUSE.getCode(), ErrorCode.INPUT_PARAMETERS_INVALID);
        UserDTO userById = userService.getUserById(presentUser.getId());
        Validator.notNull(userById, ErrorCode.USER_IS_EXP);
        Validator.isTrue(UserStateEnum.PASS.getCode() == userById.getState(), ErrorCode.USER_IS_EXP);
        slaughterHouse.setSlaughterHouseParentName(userById.getUserName());
        String id = ((UserManager) AopContext.currentProxy()).register(slaughterHouse, UserStateEnum.PASS.getCode());
//        //改造：建立绑定关系
//        SlaughterBuyerRelationDTO dto = new SlaughterBuyerRelationDTO();
//        dto.setBuyerUserId(presentUser.getId());
//        dto.setSlaughterHouseId(Long.valueOf(id));
//        dto.setInitiator(UserTypeEnum.SLAUGHTER.getCode());
//        Validator.notNull(slaughterBuyerRelationService.insert(dto),ErrorCode.RELATION_INSERT_FAIL);

        return id;
    }

    /**
     * 审批代宰户
     *
     * @param approvalVO
     * @return java.lang.Boolean
     * @author FUXINSHENG
     * @date 2021/11/9 14:31
     * @describe 1、校验用户权限，是否可以审批该代宰户
     * 2、对用户进行审批，校验审批失败原因
     * 3、修改用户审批信息表
     * 4、发送消息
     */
    @ServiceTimeLog
    @Transactional(rollbackFor = Exception.class)
    public Boolean approvalSlaughterHouse(ApprovalVO approvalVO) {
        UserDTO presentUser = userUtils.getUser(approvalVO.getToken());
        log.info(HEAD + "审批代宰户, 请求参数:{}, 当前登录用户id:{}", approvalVO, presentUser.getId());
        UserDTO slaughterHouse = userService.getUserById(approvalVO.getLinkId());
        //修改：逻辑调整不需要判断用户的状态，如果用户状态是未启用，同时间更新用户状态，如果是已启用不处理用户状态（原来的的代宰户确认逻辑仍然保留）
        //Validator.isTrue(slaughterHouse.getSlaughterHouseParentId().equals(presentUser.getId()), ErrorCode.NO_POWER_GET);
        //Validator.isTrue(slaughterHouse.getState().equals(UserStateEnum.UNCHECK.getCode()), ErrorCode.USER_IS_PASS);
        ApplicationQuery applicationQuery = new ApplicationQuery();
        applicationQuery.setLinkId(approvalVO.getLinkId());
        applicationQuery.setType(ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode());
        ApplicationInfoDTO applicationInfo = applicationInfoService.getApplicationInfoByQuery(applicationQuery);
        //Validator.isTrue(applicationInfo.getState() == ApplicationStateEnum.UNCHECK.getCode(), ErrorCode.INPUT_PARAMETERS_INVALID);
        applicationInfo.setState(approvalVO.getResult().equals(YesNoEnum.YES.getCode()) ? ApplicationStateEnum.PASS.getCode() : ApplicationStateEnum.REJECT.getCode());
        applicationInfoService.updateApplicationInfo(applicationInfo);
        if (slaughterHouse.getState().equals(UserStateEnum.UNCHECK.getCode())) {
            //applicationQuery.setType(ApplicationTypeEnum.USER.getCode());
            //ApplicationInfoDTO applicationUserInfoDTO = applicationInfoService.getApplicationInfoByQuery(applicationQuery);
            if (approvalVO.getResult().equals(YesNoEnum.YES.getCode())) {
                slaughterHouse.setState(UserStateEnum.PASS.getCode());
                userService.updateUser(slaughterHouse);
                sendPassNotifyMessage(slaughterHouse.getPhone());
            } else if (approvalVO.getResult().equals(YesNoEnum.NO.getCode())) {
//                applicationUserInfoDTO.setState(ApplicationStateEnum.REJECT.getCode());
//                applicationUserInfoDTO.setMessage("屠宰场审批未通过");
//                applicationInfoService.updateApplicationInfo(applicationUserInfoDTO);
                sendRejectNotifyMessage(slaughterHouse.getPhone(), "屠宰场审批未通过");
            }
        }
        //新增逻辑：增加代、屠绑定关系建立
        SlaughterBuyerRelationDTO relationDTO = slaughterBuyerRelationService.queryByHouseIdAndBuyerId(approvalVO.getLinkId(), presentUser.getId());
        Validator.notNull(relationDTO, ErrorCode.RELATION_ISNULL);
        int messageCode = 0;
        if (approvalVO.getResult().equals(YesNoEnum.YES.getCode())) {
            relationDTO.setState(RelationStateEnum.BIND.getCode());
            relationDTO.setBindTime(new Date());
            //保存绑定记录
            SlaughterBuyerRelationLogDTO logDTO = ModelConvertUtil.copyTo(relationDTO, SlaughterBuyerRelationLogDTO.class);
            logDTO.setType(RelationTypeEnum.BIND.getCode());
            logDTO.setId(null);
            Long logId = slaughterBuyerRelationLogService.insert(logDTO);
            Validator.notNull(logId, ErrorCode.RELATION_LOG_INSERT_FAIL);
            messageCode = MessageEnum.BIND_SUCCESS.getCode();
        } else if (approvalVO.getResult().equals(YesNoEnum.NO.getCode())) {
            relationDTO.setState(RelationStateEnum.REJECT.getCode());
            relationDTO.setRefuseTime(new Date());
            messageCode = MessageEnum.BIND_FAILED.getCode();
        }
        Validator.isTrue(slaughterBuyerRelationService.update(relationDTO), ErrorCode.RELATION_UPDATE_FAIL);
        messageLoggingManager.messageHandling(approvalVO.getLinkId(), messageCode);

        return true;
    }


    @Async
    public void sendPassNotifyMessage(String phone) {
        try {
            aliSmsMsgNotify.sendSms(phone, phone, registerPassTemplate, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Async
    public void sendRejectNotifyMessage(String phone, String msg) {
        try {
            Map<String, Object> prams = new HashMap<>(16);
            prams.put(Constants.NAME, phone);
            prams.put(Constants.MESSAGE, msg);
            aliSmsMsgNotify.sendSms(phone, phone, registerRejectTemplate, prams);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 重新提交注册
     *
     * @param userDTO
     * @return java.lang.String
     * @author FUXINSHENG
     * @date 2021/11/9 15:28
     * @describe 1、获取用户已经存在
     * 2、用户之前的审批为未通过
     * 3、用户短信验证码
     * 4、用户基础参数校验
     * 5、用户修改
     * 6、重新添加审批
     */
    @ServiceTimeLog
    @Transactional(rollbackFor = Exception.class)
    public String resubmitUser(UserDTO userDTO) {
        log.info(HEAD + "重新提交, 请求参数:{}", userDTO);
        UserDTO user = userService.getUserById(userDTO.getId());
        Validator.notNull(user, ErrorCode.INPUT_PARAMETERS_INVALID);
        //Validator.isTrue(UserStateEnum.UNCHECK.getCode() == user.getState(), ErrorCode.USER_IS_EXP);
//        ApplicationQuery applicationQuery = new ApplicationQuery();
//        applicationQuery.setSubmitUserId(userDTO.getId());
//        applicationQuery.setType(ApplicationTypeEnum.USER.getCode());
//        ApplicationInfoDTO applicationInfoByUser = applicationInfoService.getApplicationInfoByQuery(applicationQuery);
//        if (user.getType() != UserTypeEnum.SLAUGHTER_HOUSE.getCode()) {
//            Validator.isTrue(applicationInfoByUser != null && applicationInfoByUser.getState() == ApplicationStateEnum.REJECT.getCode(), ErrorCode.INPUT_PARAMETERS_INVALID);
//        }
//        if (user.getType() == UserTypeEnum.SLAUGHTER_HOUSE.getCode() && applicationInfoByUser != null && applicationInfoByUser.getState() != ApplicationStateEnum.REJECT.getCode()) {
//            applicationQuery.setType(ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode());
//            ApplicationInfoDTO applicationInfoDTO = applicationInfoService.getApplicationInfoByQuery(applicationQuery);
//            Validator.notNull(applicationInfoDTO, ErrorCode.APPLY_NULL);
//            Validator.isTrue(applicationInfoDTO.getState() == ApplicationStateEnum.REJECT.getCode(), ErrorCode.APPLY_NULL);
//        }
//        checkSms(userDTO.getPhone(), userDTO.getSmsCode());


        userDTO.setUserName(formateHtml(userDTO.getUserName()));
        userDTO.setSlaughterHouseType(user.getEnterprise());
        checkUserParam(userDTO);
        userDTO.setEnterprise(user.getEnterprise());
        userDTO.setPassword(user.getPassword());
        userDTO.setPhone(user.getPhone());
        userDTO.setBusinessLinkMan(user.getBusinessLinkMan());

        userDTO.setState(3);
        userService.updateUser(userDTO);
//        if (ifRegisterUserApproval) {
//            ApplicationInfoDTO applicationInfoDTO = new ApplicationInfoDTO();
//            applicationInfoDTO.setType(ApplicationTypeEnum.USER.getCode());
//            applicationInfoDTO.setLinkId(userDTO.getId());
//            applicationInfoDTO.setSubmitUserId(userDTO.getId());
//            applicationInfoDTO.setLinkTable(Constants.TB_USER);
//            applicationInfoDTO.setSubmitPhone(userDTO.getPhone());
//            applicationInfoDTO.setSubmitUserName(userDTO.getUserName());
//            log.info(HEAD + "重新提交, 初始化审批信息:{}", applicationInfoDTO);
//            applicationInfoService.addApplicationInfo(applicationInfoDTO);
//        }
        if (userDTO.getType() == UserTypeEnum.SLAUGHTER_HOUSE.getCode()) {
            UserQuery query = new UserQuery();
            query.setName(userDTO.getSlaughterHouseParentName());
            query.setType(UserTypeEnum.SLAUGHTER.getCode());
            UserDTO oneUser = userService.getOneUser(query);
            Validator.isTrue(oneUser!=null && oneUser.getState() == UserStateEnum.PASS.getCode(), ErrorCode.SLAUGHTER_IS_NULL);
            SlaughterBuyerRelationDTO dto = new SlaughterBuyerRelationDTO();
            dto.setBuyerUserId(oneUser.getId());
            dto.setSlaughterHouseId(userDTO.getId());
            dto.setInitiator(UserTypeEnum.SLAUGHTER_HOUSE.getCode());
            Validator.notNull(slaughterBuyerRelationService.insert(dto),ErrorCode.RELATION_INSERT_FAIL);
        }

        return userDTO.getId().toString();
    }

    public List<IndexNotifyVO> taskList(String token) {
        UserDTO userDTO = userUtils.getUser(token);
        Integer type = userDTO.getType();
        log.info(HEAD + "获取菜单通知项, 当前用户id: {}, 当前用户类型: {}", userDTO.getId(), UserTypeEnum.findByCode(userDTO.getType()).getText());

        List<IndexNotifyVO> notifyVOList = new ArrayList<>();
        if (type == UserTypeEnum.SLAUGHTER.getCode()) {
            IndexNotifyVO notifyVOBySlaughterHouse = getNotifyVO(userDTO.getId(), ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode(), TaskModelEnum.SLAUGHTER_HOUSE.getCode());
            IndexNotifyVO notifyVOByTransport = getNotifyVO(userDTO.getId(), ApplicationTypeEnum.ACCEPT_STAGE.getCode(), TaskModelEnum.TRANSPORT.getCode());
            notifyVOList.add(notifyVOBySlaughterHouse);
            notifyVOList.add(notifyVOByTransport);
        } else if (type == UserTypeEnum.FARM.getCode()) {
            IndexNotifyVO notifyVOByContract = getNotifyVO(userDTO.getId(), ApplicationTypeEnum.CONTRACT.getCode(), TaskModelEnum.CONTRACT.getCode());
            IndexNotifyVO notifyVOByWaybill = getNotifyVO(userDTO.getId(), ApplicationTypeEnum.WAYBILL.getCode(), TaskModelEnum.ORDER.getCode());
            notifyVOList.add(notifyVOByContract);
            notifyVOList.add(notifyVOByWaybill);
        } else if (type == UserTypeEnum.DRIVER.getCode()) {
            IndexNotifyVO notifyVO = getNotifyVO(userDTO.getId(), ApplicationTypeEnum.TRANSPORT.getCode(), TaskModelEnum.TRANSPORT.getCode());
            notifyVOList.add(notifyVO);
        } else if (type == UserTypeEnum.AGENT.getCode()) {
            IndexNotifyVO notifyVO = getNotifyVO(userDTO.getId(), ApplicationTypeEnum.WAYBILL.getCode(), TaskModelEnum.ORDER.getCode());
            notifyVOList.add(notifyVO);
        } else if (type == UserTypeEnum.SLAUGHTER_HOUSE.getCode()) {
            IndexNotifyVO notifyVO = getNotifyVO(userDTO.getId(), ApplicationTypeEnum.ACCEPT_STAGE.getCode(), TaskModelEnum.TRANSPORT.getCode());
            notifyVOList.add(notifyVO);
        }
        log.info(HEAD + "获取菜单通知项, 当前用户id: {}, 通知项信息: {}", userDTO.getId(), JSON.toJSONString(notifyVOList));
        return notifyVOList;
    }

    public IndexNotifyVO getNotifyVO(Long userId, Integer applicationType, Integer taskType) {
        IndexNotifyVO notifyVO = new IndexNotifyVO();
        notifyVO.setType(taskType);
        if (taskType == ApplicationTypeEnum.CONTRACT.getCode()) {
            ContractQuery contractQuery = new ContractQuery();
            contractQuery.setSalerId(userId);
            contractQuery.setState(ApplicationStateEnum.UNCHECK.getCode());
            ContractDTO contract = contractService.getContract(contractQuery);
            if (contract != null) {
                notifyVO.setIfNotify(YesNoEnum.YES.getCode());
                notifyVO.setNum(1);
            } else {
                notifyVO.setIfNotify(YesNoEnum.NO.getCode());
            }
        } else {
            int ifNotify = YesNoEnum.NO.getCode();
            ApplicationQuery applicationQuery = new ApplicationQuery();
            applicationQuery.setApplyUserId(userId);
            applicationQuery.setState(ApplicationStateEnum.UNCHECK.getCode());
            applicationQuery.setType(applicationType);
            List<ApplicationInfoDTO> applicationInfoByApplyId = applicationInfoService.listApplicationInfo(applicationQuery);
            if (CollectionUtils.isNotEmpty(applicationInfoByApplyId)) {
                //如果是代宰户确认，需要判断代宰户当前的用户状态是不是已启用
                //这里直接获取审核信息中的提交用户，用户不是启用状态不能统计到红点数量
                if (taskType == ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode()) {
                    int counts = 0;
                    for (ApplicationInfoDTO applicationInfoDTO : applicationInfoByApplyId) {
                        UserDTO userDTO = userService.getUserById(applicationInfoDTO.getSubmitUserId());
                        if (!StringUtil.isEmpty(userDTO)) {
                            if (userDTO.getState().intValue() == UserStateEnum.PASS.getCode()) {
                                counts += 1;
                            }
                        }

                    }
                    notifyVO.setNum(counts);
                } else {
                    notifyVO.setNum(applicationInfoByApplyId.size());
                }
                if (notifyVO.getNum() > 0) {
                    ifNotify = YesNoEnum.YES.getCode();
                }

            }
            notifyVO.setIfNotify(ifNotify);
        }
        return notifyVO;
    }

    /**
     * 获取用户所有签订过合同的养殖场基础信息
     *
     * @param
     * @return java.util.List<org.springblade.modules.app.common.vo.FarmSimpleInfoVO>
     * @author FUXINSHENG
     * @date 2021/11/10 11:43
     * @describe
     */
    @ServiceTimeLog
    public List<FarmSimpleInfoVO> listContractFarm(String token) {
        UserDTO userDTO = userUtils.getUser(token);
        log.info(HEAD + "获取签订合同的养殖场基础信息, 当前用户id: {}, 当前用户类型: {}", userDTO.getId(), UserTypeEnum.findByCode(userDTO.getType()).getText());

        ContractQuery query = new ContractQuery();
        if (userDTO.getType().equals(UserTypeEnum.SLAUGHTER.getCode())) {
            query.setBuyerId(userDTO.getId());
        } else if (userDTO.getType().equals(UserTypeEnum.SLAUGHTER_HOUSE.getCode())) {
            query.setBuyerId(userDTO.getSlaughterHouseParentId());
        } else {
            Validator.isTrue(false, ErrorCode.NO_POWER_GET);
        }
        query.setState(YesNoEnum.YES.getCode());
        List<ContractDTO> contractDTOList = contractService.getContractList(query);
        Validator.isTrue(CollectionUtils.isNotEmpty(contractDTOList), ErrorCode.NO_CONTRACT_FARM);
        List<FarmSimpleInfoVO> farmSimpleInfoVOList = new ArrayList<>();
        for (ContractDTO contractDTO : contractDTOList) {
            FarmSimpleInfoVO farmSimpleInfoVO = new FarmSimpleInfoVO();
            farmSimpleInfoVO.setId(contractDTO.getSalerUserId());
            farmSimpleInfoVO.setUserName(contractDTO.getSalerUserName());
            farmSimpleInfoVO.setAddress(contractDTO.getSalerUserAddress());
            farmSimpleInfoVOList.add(farmSimpleInfoVO);
        }
        return farmSimpleInfoVOList;
    }


    @ServiceTimeLog
    public List<FarmSimpleInfoVO> listSimpleFarm(Long buyerUserId, String token) {
        UserDTO userDTO = userUtils.getUser(token);

        log.info(HEAD + "屠户根据浙牧通获取可申请的养殖场信息, 当前用户id: {}, 当前用户类型: {}", userDTO.getId(), UserTypeEnum.findByCode(userDTO.getType()).getText());
        OutApiSyncSupplierParamVO supplierParamVO = new OutApiSyncSupplierParamVO();
        if (userDTO.getType().equals(UserTypeEnum.SLAUGHTER.getCode())) {
            supplierParamVO.setOrgId(userDTO.getZmtId());
            supplierParamVO.setOrgName(userDTO.getUserName());
        } else if (userDTO.getType().equals(UserTypeEnum.SLAUGHTER_HOUSE.getCode())) {
//            UserDTO slaughter = userService.getUserById(userDTO.getSlaughterHouseParentId());
//            supplierParamVO.setOrgId(slaughter.getZmtId());
            //改版：这里取参数，因为对应的屠宰场可能会有多个
            UserDTO buyerUser = userService.getUserById(buyerUserId);
            Validator.notNull(buyerUser, ErrorCode.USER_IS_EXP);
            SlaughterBuyerRelationDTO slaughterBuyerRelationDTO = slaughterBuyerRelationService.queryByHouseIdAndBuyerId(userDTO.getId(), buyerUserId);
            Validator.isTrue(slaughterBuyerRelationDTO != null && slaughterBuyerRelationDTO.getState().intValue() == RelationStateEnum.BIND.getCode(), ErrorCode.RELATION_ISNULL);
            supplierParamVO.setOrgId(buyerUser.getZmtId());
        } else {
            Validator.isTrue(false, ErrorCode.NO_POWER_GET);
        }
        List<FarmSimpleInfoVO> list = new ArrayList<>();
        List<OutApiSyncSupplierResultVO> eastSupplier = zmtClientService.getEastSupplier(supplierParamVO);
        if (CollectionUtils.isNotEmpty(eastSupplier)) {
            for (OutApiSyncSupplierResultVO resultVO : eastSupplier) {
//                saveSupplier(resultVO);
                FarmSimpleInfoVO farmSimpleInfoVO = new FarmSimpleInfoVO();
//                farmSimpleInfoVO.setUserName(resultVO.getSupplierName().replaceAll(Constants.SUPPLIER_NAME_REGEX_1, "").replaceAll(Constants.SUPPLIER_NAME_REGEX_2, ""));
                farmSimpleInfoVO.setUserName(resultVO.getSupplierName());
                farmSimpleInfoVO.setAddress(resultVO.getAreaName());
                farmSimpleInfoVO.setPhone(resultVO.getSupplierTel());
                farmSimpleInfoVO.setSupplierType(resultVO.getSupplierType());
                farmSimpleInfoVO.setSupplierId(resultVO.getSupplierId());
                list.add(farmSimpleInfoVO);
            }
        }
        return list;
    }

    public void saveSupplier(OutApiSyncSupplierResultVO resultVO) {
        UserQuery userQuery = new UserQuery();
        userQuery.setType(2);
        String supplierName = resultVO.getSupplierName().replaceAll(Constants.SUPPLIER_NAME_REGEX_1, "").replaceAll(Constants.SUPPLIER_NAME_REGEX_2, "");
        userQuery.setName(supplierName);
        UserDTO userDTO = userService.getOneUser(userQuery);
        if (StringUtil.isEmpty(userDTO)) {
            userDTO = new UserDTO();
            userDTO.setType(2);
            userDTO.setPhone(StringUtil.isEmpty(resultVO.getSupplierTel()) ? "" : resultVO.getSupplierTel());
            userDTO.setUserName(supplierName);
            userDTO.setAddress(resultVO.getAreaName());


//            String[] area = resultVO.getAreaName().split("/");
//            List<CityDO> province = cityService.list(Wrappers.<CityDO>lambdaQuery()
//                    .eq(CityDO::getName,area[0].replace("省","")
//                            .replace("市","")).orderByAsc(CityDO::getId));
//            CityDO city = cityService.getOne(Wrappers.<CityDO>lambdaQuery()
//                    .eq(CityDO::getName,area[1].replace("市",""))
//                    .eq(CityDO::getFid,province.get(0).getId()));
//            if(area.length == 3){
//                CityDO ara = cityService.getOne(Wrappers.<CityDO>lambdaQuery().eq(CityDO::getName,area[2])
//                    .eq(CityDO::getFid,city.getId()));
//                userDTO.setAreaId(StringUtil.isEmpty(ara)?0:ara.getId());
//                userDTO.setAreaName(area[2]);
//            }
//
//            userDTO.setProvId(province.get(0).getId());
//            userDTO.setCityId(city.getId());
//
//            userDTO.setProvName(area[0].replace("省",""));
//            userDTO.setCityName(area[1].replace("市",""));

            userDTO.setZmtUserId(resultVO.getSupplierId());
            userDTO.setState(1);
            userDTO.setZmtType(resultVO.getSupplierType());
            userService.addUser(userDTO);
        }
    }

    @ServiceTimeLog
    public UserDTO getFarmPicture(Long userId, String token) {
        UserDTO userDTO = userUtils.getUser(token);
        log.info(HEAD + "获取养殖场附件信息, 当前用户id: {}, 查询养殖场id: {}", userDTO.getId(), userId);
        ContractDTO contract = null;
        ContractQuery contractQuery = new ContractQuery();
        contractQuery.setSalerId(userId);
        if (userDTO.getType().equals(UserTypeEnum.SLAUGHTER.getCode())) {
            contractQuery.setBuyerId(userDTO.getId());
        } else if (userDTO.getType().equals(UserTypeEnum.SLAUGHTER_HOUSE.getCode())) {
            contractQuery.setBuyerId(userDTO.getSlaughterHouseParentId());
        } else {
            Validator.isTrue(false, ErrorCode.NO_POWER_GET);
        }
        contractQuery.setState(YesNoEnum.YES.getCode());
        contract = contractService.getContract(contractQuery);
        Validator.notNull(contract, ErrorCode.FARM_NOT_CONTRACT);
        UserDTO user = userService.getUserById(userId);
        Validator.notNull(user, ErrorCode.USER_IS_EXP);
        Validator.isTrue(UserStateEnum.PASS.getCode() == user.getState(), ErrorCode.USER_IS_EXP);
        UserDTO farm = new UserDTO();
        farm.setBusinessUrl(user.getBusinessUrl());
        farm.setNoEpidemicProofPassDate(user.getNoEpidemicProofPassDate());
        farm.setNoEpidemicProofPassUrl(user.getNoEpidemicProofPassUrl());
        farm.setLivestockPreventionPassUrl(user.getLivestockPreventionPassUrl());
        return farm;
    }

    @ServiceTimeLog
    public UserDTO getSlaughterByHouse(String token) {
        UserDTO userDTO = userUtils.getUser(token);
        log.info(HEAD + "获取代宰户挂靠的屠宰场信息, 当前用户id: {}, 当前用户类型: {}", userDTO.getId(), UserTypeEnum.findByCode(userDTO.getType()).getText());
        Validator.isTrue(userDTO.getType().equals(UserTypeEnum.SLAUGHTER_HOUSE.getCode()), ErrorCode.NO_POWER_GET);
//        ApplicationQuery applicationQuery = new ApplicationQuery();
//        applicationQuery.setSubmitUserId(userDTO.getId());
//        applicationQuery.setType(ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode());
//        ApplicationInfoDTO applicationInfoDTO = applicationInfoService.getApplicationInfoByQuery(applicationQuery);
//        Validator.isTrue(applicationInfoDTO.getState() == ApplicationStateEnum.PASS.getCode(), ErrorCode.USER_IS_NOT_PASS);
        UserDTO user = userService.getUserById(userDTO.getId());
        Validator.notNull(user, ErrorCode.USER_IS_EXP);
        Validator.isTrue(UserStateEnum.PASS.getCode() == user.getState(), ErrorCode.USER_IS_EXP);
        log.info(HEAD + "获取代宰户挂靠的屠宰场信息,屠宰场id: {}", userDTO.getSlaughterHouseParentId());
        return userService.getUserById(userDTO.getSlaughterHouseParentId());
    }

    public Boolean businessLicenseUpdate(Long id, UserDTO userDTO) {
        Validator.notNull(userDTO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(id, ErrorCode.INPUT_PARAMETERS_NULL);
        log.info("用户id为:{},修改数据为:{}", id, userDTO);
        UserDTO userDTO1 = userService.getUserById(id);
        Validator.notNull(userDTO1, ErrorMsg.NEW("用户不存在"));
        // 验证姓名未改变或未注册
        if (!userDTO.getUserName().equals(userDTO1.getUserName())) {
            UserQuery userQuery = new UserQuery();
            userQuery.setName(userDTO.getUserName());
            Validator.isNull(userService.getOneUser(userQuery), ErrorMsg.NEW("该名称用户已存在"));
        }

        Validator.notBlank(userDTO.getUserName(), ErrorCode.USER_COMPANY_NAME_NULL);
        Validator.notBlank(userDTO.getBusinessIndustryCategrory(), ErrorCode.USER_BUSINESS_CATEGORY_NULL);
        Validator.notBlank(userDTO.getProvId(), ErrorCode.USER_PROV_NULL);
        Validator.notBlank(userDTO.getCityId(), ErrorCode.USER_CITY_NULL);
        Validator.notBlank(userDTO.getAreaId(), ErrorCode.USER_AREA_NULL);
        Validator.notBlank(userDTO.getAddress(), ErrorCode.USER_ADDRESS_NULL);
        Validator.notBlank(userDTO.getBusinessLegalPerson(), ErrorCode.USER_BUSINESS_LEGAL_NULL);
        Validator.notBlank(userDTO.getBusinessTerm(), ErrorCode.USER_BUSINESS_TERM_NULL);
        Validator.notBlank(userDTO.getBusinessScope(), ErrorCode.USER_BUSINESS_SCOPE_NULL);
        Validator.notBlank(userDTO.getCreditCode(), ErrorCode.USER_CREDIT_CODE_NULL);
        Validator.notNull(userDTO.getBusinessUrl(), ErrorCode.USER_BUSINESS_URL_NULL);

        UserDTO updateUserDTO = new UserDTO();
        updateUserDTO.setId(id);
        updateUserDTO.setUserName(userDTO.getUserName());
        updateUserDTO.setBusinessIndustryCategrory(userDTO.getBusinessIndustryCategrory());
        updateUserDTO.setProvId(userDTO.getProvId());
        updateUserDTO.setCityId(userDTO.getCityId());
        updateUserDTO.setAreaId(userDTO.getAreaId());
        updateUserDTO.setAddress(userDTO.getAddress());
        updateUserDTO.setBusinessLegalPerson(userDTO.getBusinessLegalPerson());
        updateUserDTO.setBusinessTerm(userDTO.getBusinessTerm());
        updateUserDTO.setBusinessScope(userDTO.getBusinessScope());
        updateUserDTO.setCreditCode(userDTO.getCreditCode());
        updateUserDTO.setBusinessUrl(userDTO.getBusinessUrl());
        updateUserDTO.setBusinessRegisterMoney(userDTO.getBusinessRegisterMoney());
        updateUserDTO.setBusinessRegisterDate(userDTO.getBusinessRegisterDate());

        userService.updateUser(updateUserDTO);
        return true;
    }

    public Boolean slaughteringLicenseUpdate(Long id, UserDTO userDTO) {
        Validator.notNull(userDTO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(id, ErrorCode.INPUT_PARAMETERS_NULL);
        log.info("用户id为:{},修改数据为:{}", id, userDTO);
        Validator.notNull(userService.getUserById(id), ErrorMsg.NEW("用户不存在"));

        Validator.notBlank(userDTO.getLivestockSlaughterPermitCode(), ErrorCode.USER_LIVESTOCK_SLAUGHTER_PERMIT_CODE_NULL);
        Validator.notNull(userDTO.getLivestockSlaughterPermitUrl(), ErrorCode.USER_LIVESTOCK_SLAUGHTER_PERMIT_URL_NULL);

        UserDTO updateUserDTO = new UserDTO();
        updateUserDTO.setId(id);
        updateUserDTO.setLivestockSlaughterPermitUrl(userDTO.getLivestockSlaughterPermitUrl());
        updateUserDTO.setLivestockSlaughterPermitCode(userDTO.getLivestockSlaughterPermitCode());

        userService.updateUser(updateUserDTO);
        return true;
    }

    public Boolean antiepidemicCertificateUpdate(Long id, UserDTO userDTO) {
        Validator.notNull(userDTO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(id, ErrorCode.INPUT_PARAMETERS_NULL);
        log.info("用户id为:{},修改数据为:{}", id, userDTO);
        Validator.notNull(userService.getUserById(id), ErrorMsg.NEW("用户不存在"));

        Validator.notNull(userDTO.getLivestockPreventionPassUrl(), ErrorCode.USER_LIVESTOCK_PREVENTION_PASS_URL_NULL);
        Validator.notBlank(userDTO.getLivestockPreventionPassCode(), ErrorCode.USER_LIVESTOCK_PREVENTION_PASS_CODE_NULL);

        UserDTO updateUserDTO = new UserDTO();
        updateUserDTO.setId(id);
        updateUserDTO.setLivestockPreventionPassCode(userDTO.getLivestockPreventionPassCode());
        updateUserDTO.setLivestockPreventionPassUrl(userDTO.getLivestockPreventionPassUrl());

        userService.updateUser(updateUserDTO);
        return true;
    }

    public Boolean pollutantsDischargeLicenseUpdate(Long id, UserDTO userDTO) {
        Validator.notNull(userDTO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(id, ErrorCode.INPUT_PARAMETERS_NULL);
        log.info("用户id为:{},修改数据为:{}", id, userDTO);
        Validator.notNull(userService.getUserById(id), ErrorMsg.NEW("用户不存在"));

        Validator.notBlank(userDTO.getPollutantDischargePermitCode(), ErrorCode.USER_POLLUTANT_DISCHARGE_PERMIT_CODE_NULL);
        Validator.notNull(userDTO.getPollutantDischargePermitLicenseUrl(), ErrorCode.USER_POLLUTANT_DISCHARGE_PERMIT_LICENSE_URL_NULL);
        Validator.notBlank(userDTO.getBusinessIndustryCategrory(), ErrorCode.USER_POLLUTANT_DISCHARGE_PERMIT_INDUSTRY_NULL);
        Validator.notBlank(userDTO.getPollutantDischargePermitDate(), ErrorCode.USER_POLLUTANT_DISCHARGE_PERMIT_DATE_NULL);

        UserDTO updateUserDTO = new UserDTO();
        updateUserDTO.setId(id);
        updateUserDTO.setPollutantDischargePermitCode(userDTO.getPollutantDischargePermitCode());
        updateUserDTO.setPollutantDischargePermitLicenseUrl(userDTO.getPollutantDischargePermitLicenseUrl());
        updateUserDTO.setBusinessIndustryCategrory(userDTO.getBusinessIndustryCategrory());
        updateUserDTO.setPollutantDischargePermitDate(userDTO.getPollutantDischargePermitDate());

        userService.updateUser(updateUserDTO);
        return true;
    }

    public Boolean noEpidemicProofUpdate(Long id, UserDTO userDTO) {
        Validator.notNull(userDTO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(id, ErrorCode.INPUT_PARAMETERS_NULL);
        log.info("用户id为:{},修改数据为:{}", id, userDTO);
        Validator.notNull(userService.getUserById(id), ErrorMsg.NEW("用户不存在"));

        Validator.notNull(userDTO.getNoEpidemicProofPassUrl(), ErrorMsg.NEW("三年无疫情证明url为空"));

        UserDTO updateUserDTO = new UserDTO();
        updateUserDTO.setId(id);
        updateUserDTO.setNoEpidemicProofPassUrl(userDTO.getNoEpidemicProofPassUrl());

        userService.updateUser(updateUserDTO);
        return true;
    }

    public Boolean identityCardUpdate(Long id, UserDTO userDTO) {
        Validator.notNull(userDTO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(id, ErrorCode.INPUT_PARAMETERS_NULL);
        log.info("用户id为:{},修改数据为:{}", id, userDTO);
        Validator.notNull(userService.getUserById(id), ErrorMsg.NEW("用户不存在"));

        Validator.notNull(userDTO.getIdCardFrontUrl(), ErrorCode.USER_ID_CARD_FRONT_URL_NULL);
        Validator.notNull(userDTO.getIdCardBehindUrl(), ErrorCode.USER_ID_CARD_BEHIND_URL_NULL);
        Validator.notBlank(userDTO.getUserName(), ErrorCode.USER_NAME_NULL);
        Validator.notBlank(userDTO.getCreditCode(), ErrorCode.USER_ID_CODE_NULL);
        Validator.notBlank(userDTO.getProvId(), ErrorCode.USER_PROV_NULL);
        Validator.notBlank(userDTO.getCityId(), ErrorCode.USER_CITY_NULL);
        Validator.notBlank(userDTO.getAreaId(), ErrorCode.USER_AREA_NULL);
        Validator.notBlank(userDTO.getAddress(), ErrorCode.USER_ADDRESS_NULL);

        UserDTO updateUserDTO = new UserDTO();
        updateUserDTO.setId(id);
        updateUserDTO.setIdCardFrontUrl(userDTO.getIdCardFrontUrl());
        updateUserDTO.setIdCardBehindUrl(userDTO.getIdCardBehindUrl());
        updateUserDTO.setUserName(userDTO.getUserName());
        updateUserDTO.setCreditCode(userDTO.getCreditCode());
        updateUserDTO.setProvId(userDTO.getProvId());
        updateUserDTO.setCityId(userDTO.getCityId());
        updateUserDTO.setAreaId(userDTO.getAreaId());
        updateUserDTO.setAddress(userDTO.getAddress());

        UserQuery userQuery = new UserQuery();
        userQuery.setName(userDTO.getUserName());
        UserDTO oneUser = userService.getOneUser(userQuery);
        if(!StringUtil.isEmpty(oneUser) && !oneUser.getId().equals(id)){
            throw new BusinessException(ErrorCode.USER_IS_REGISTERED);
        }

        userService.updateUser(updateUserDTO);
        return true;
    }

    public Boolean driverLicenceUpdate(Long id, UserDTO userDTO) {
        Validator.notNull(userDTO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(id, ErrorCode.INPUT_PARAMETERS_NULL);
        log.info("用户id为:{},修改数据为:{}", id, userDTO);
        Validator.notNull(userService.getUserById(id), ErrorMsg.NEW("用户不存在"));

        Validator.notNull(userDTO.getDriverLicenceUrl(), ErrorCode.USER_DRIVER_LICENSE_URL_NULL);
        Validator.notBlank(userDTO.getDriverLicenceCode(), ErrorCode.USER_DRIVER_LICENSE_CODE_NULL);
        Validator.notBlank(userDTO.getDriverCarType(), ErrorCode.USER_DRIVER_LICENSE_CAR_TYPE_NULL);
        Validator.notBlank(userDTO.getDriverLicenceExpiryDate(), ErrorCode.USER_DRIVER_LICENSE_EXPIRY_DATE_NULL);

        UserDTO updateUserDTO = new UserDTO();
        updateUserDTO.setId(id);
        updateUserDTO.setDriverLicenceUrl(userDTO.getDriverLicenceUrl());
        updateUserDTO.setDriverLicenceCode(userDTO.getDriverLicenceCode());
        updateUserDTO.setDriverCarType(userDTO.getDriverCarType());
        updateUserDTO.setDriverIssuing(userDTO.getDriverIssuing());
        updateUserDTO.setDriverFirstIssueDate(userDTO.getDriverFirstIssueDate());
        updateUserDTO.setDriverLicenceExpiryDate(userDTO.getDriverLicenceExpiryDate());

        userService.updateUser(updateUserDTO);
        return true;
    }

    public Boolean drivingLicenceUpdate(Long id, UserDTO userDTO) {
        Validator.notNull(userDTO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(id, ErrorCode.INPUT_PARAMETERS_NULL);
        log.info("用户id为:{},修改数据为:{}", id, userDTO);
        Validator.notNull(userService.getUserById(id), ErrorMsg.NEW("用户不存在"));

        Validator.notNull(userDTO.getVehicleLicenseUrl(), ErrorCode.USER_VEHICLE_LICENSE_URL_NULL);
        Validator.notBlank(userDTO.getVehicleLicenseCode(), ErrorCode.USER_VEHICLE_LICENSE_CODE_NULL);

        UserDTO updateUserDTO = new UserDTO();
        updateUserDTO.setId(id);
        updateUserDTO.setVehicleLicenseUrl(userDTO.getVehicleLicenseUrl());
        updateUserDTO.setVehicleLicenseCode(userDTO.getVehicleLicenseCode());

        userService.updateUser(updateUserDTO);
        return true;
    }

    public Boolean roadTransportLicenceUpdate(Long id, UserDTO userDTO) {
        Validator.notNull(userDTO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(id, ErrorCode.INPUT_PARAMETERS_NULL);
        log.info("用户id为:{},修改数据为:{}", id, userDTO);
        Validator.notNull(userService.getUserById(id), ErrorMsg.NEW("用户不存在"));

        Validator.notNull(userDTO.getTransportPermitUrl(), ErrorCode.USER_TRANSPORT_PERMIT_URL_NULL);
        Validator.notBlank(userDTO.getTransportPermitCode(), ErrorCode.USER_TRANSPORT_PERMIT_CODE_NULL);

        UserDTO updateUserDTO = new UserDTO();
        updateUserDTO.setId(id);
        updateUserDTO.setTransportPermitUrl(userDTO.getTransportPermitUrl());
        updateUserDTO.setTransportPermitCode(userDTO.getTransportPermitCode());

        userService.updateUser(updateUserDTO);
        return true;
    }

    public Boolean phoneNumberUpdate(Long id, UserDTO userDTO) {
        Validator.notNull(userDTO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(id, ErrorCode.INPUT_PARAMETERS_NULL);
        log.info("用户id为:{},修改数据为:{}", id, userDTO);
        Validator.notNull(userService.getUserById(id), ErrorMsg.NEW("用户不存在"));

        Validator.notNull(userDTO.getPhone(), ErrorCode.USER_PHONE_NULL);
        UserQuery userQuery = new UserQuery();
        userQuery.setPhone(userDTO.getPhone());
        Validator.isNull(userService.getOneUser(userQuery), ErrorMsg.NEW("该手机号已被注册"));

        UserDTO updateUserDTO = new UserDTO();
        updateUserDTO.setId(id);
        updateUserDTO.setPhone(userDTO.getPhone());

        userService.updateUser(updateUserDTO);
        return true;
    }


    public UserDTO getFarmInfo(UserQuery userQuery) {
        Validator.notNull(userQuery, ErrorCode.INPUT_PARAMETERS_NULL);
        userQuery.setType(UserTypeEnum.FARM.getCode());

        UserDTO userDTO = userService.getOneUser(userQuery);
        log.info("返回数据为：{}", userDTO);
        return userDTO;
    }

    public UserDTO getSlaughterByName(UserQuery userQuery) {
        Validator.notNull(userQuery, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(userQuery.getName(), ErrorCode.INPUT_PARAMETERS_NULL);
        log.info("通过名称查询屠宰场：{}", userQuery.getName());
        UserQuery query = new UserQuery();
        query.setName(userQuery.getName());
        query.setType(UserTypeEnum.SLAUGHTER.getCode());
        UserDTO oneUser = userService.getOneUser(query);
        UserDTO userDTO = new UserDTO();
        userDTO.setId(oneUser.getId());
        userDTO.setUserName(oneUser.getUserName());
        return userDTO;
    }

    public UserDTO getUserByID(Long id) {
        return userService.getUserById(id);
    }

    public Page<UserDTO> pageUser(AdminUserQuery userQuery) {
        return userService.pageUser(userQuery);
    }

    public Boolean changeUserState(ChangeUserStateVO stateVO) {
        UserDTO user = userService.getUserById(stateVO.getId());
        Validator.isTrue(!user.getState().equals(UserStateEnum.UNCHECK.getCode()), ErrorCode.USER_IS_NOT_REGISTERED);
        Validator.isTrue(!user.getState().equals(stateVO.getState()), ErrorCode.INPUT_PARAMETERS_INVALID);
        user.setState(stateVO.getState());
        userService.updateUser(user);
        return true;
    }

    /**
     * 获取所有已注册用户（无论失败还是成功）的审批信息
     *
     * @param userQuery
     * @return java.lang.Object
     * @author FUXINSHENG
     * @date 2021/11/24 13:32
     * @describe
     */
    public Page<UserDTO> pageRegisterUser(AdminUserQuery userQuery) {
        Page<UserDTO> page = userService.pageRegisterUser(userQuery);
        List<UserDTO> records = page.getRecords();
        for (UserDTO userDTO : records) {
            if (userDTO.getCheckState() == null) {
                userDTO.setCheckState(ApplicationStateEnum.PASS.getCode());
            }
        }
        return page;
    }

    /**
     * 批量审批用户
     *
     * @param approvalVO
     * @return java.lang.Boolean
     * @author FUXINSHENG
     * @date 2021/11/24 17:06
     * @describe
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean approvalRegisterUser(ApprovalVO approvalVO) {
        Validator.notNull(approvalVO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.isTrue(CollectionUtils.isNotEmpty(approvalVO.getLinkIdList()), ErrorCode.INPUT_PARAMETERS_NULL);

        List<Long> linkIdList = approvalVO.getLinkIdList();
        UserQuery userQuery = new UserQuery();
        userQuery.setUserIdList(linkIdList);
        List<UserDTO> userDTOList = userService.listUser(userQuery);
        Validator.isTrue(CollectionUtils.isNotEmpty(userDTOList), ErrorCode.INPUT_PARAMETERS_INVALID);
        ApplicationQuery applicationQuery = new ApplicationQuery();
        applicationQuery.setType(ApplicationTypeEnum.USER.getCode());
        for (UserDTO userDTO : userDTOList) {
            //Validator.isTrue(userDTO.getState() == UserStateEnum.UNCHECK.getCode(), ErrorCode.USER_STATE_EXP);
            //applicationQuery.setLinkId(userDTO.getId());
            //ApplicationInfoDTO applicationInfoByQuery = applicationInfoService.getApplicationInfoByQuery(applicationQuery);
//            Validator.isTrue(applicationInfoByQuery.getState() == ApplicationStateEnum.UNCHECK.getCode(), ErrorCode.APPLY_STATE_ERROR);
            //applicationInfoByQuery.setState(approvalVO.getResult().equals(YesNoEnum.YES.getCode()) ? ApplicationStateEnum.PASS.getCode() : ApplicationStateEnum.REJECT.getCode());
            if (approvalVO.getResult().equals(2)) {
                //applicationInfoByQuery.setMessage(approvalVO.getMessage());
                if (userDTO.getType() == UserTypeEnum.SLAUGHTER_HOUSE.getCode()) {
                    //ApplicationQuery query = new ApplicationQuery();
//                    query.setType(ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode());
                    //query.setLinkId(userDTO.getId());
                    //ApplicationInfoDTO infoByQuery = applicationInfoService.getApplicationInfoByQuery(query);
//                    infoByQuery.setState(ApplicationStateEnum.REJECT.getCode());
                    //infoByQuery.setMessage("未通过用户审批");
                    //applicationInfoService.updateApplicationInfo(infoByQuery);
                }
                userDTO.setState(approvalVO.getResult());
                sendRejectNotifyMessage(userDTO.getPhone(), approvalVO.getMessage());
            } else {
//                if (userDTO.getType() != UserTypeEnum.SLAUGHTER_HOUSE.getCode()) {
//                    userDTO.setState(UserStateEnum.PASS.getCode());
//                } else {
//                    applicationQuery.setType(ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode());
//                    ApplicationInfoDTO applicationInfo = applicationInfoService.getApplicationInfoByQuery(applicationQuery);
//                    if (applicationInfo.getState() == ApplicationStateEnum.PASS.getCode()) {
//                        userDTO.setState(UserStateEnum.PASS.getCode());
//                    }
//                }
                userDTO.setState(approvalVO.getResult());
                if(approvalVO.getResult().equals(1)){
                    sendPassNotifyMessage(userDTO.getPhone());
                }

            }
            //applicationInfoService.updateApplicationInfo(applicationInfoByQuery);
            userService.updateUser(userDTO);
        }
        return true;
    }


    @Transactional(rollbackFor = Exception.class)
    public Boolean userCancel(Long id) {
        Validator.notNull(id, ErrorCode.INPUT_PARAMETERS_NULL);
        UserDTO userDTO = userService.getUserById(id);
        Validator.notNull(userDTO, ErrorMsg.NEW("用户不存在或已删除"));
        Integer type = userDTO.getType();

        // 当类型是屠宰场时
        if (type.equals(UserTypeEnum.SLAUGHTER.getCode())) {
            // 检查合同
            ContractQuery contractQuery = new ContractQuery();
            contractQuery.setBuyerId(id);
            checkContract(contractQuery);

            // 检查运输单
            TransportQuery transportQuery = new TransportQuery();
            transportQuery.setBuyerId(id);
            checkTransport(transportQuery);

            // 检查调运单
            WaybillQuery waybillQuery = new WaybillQuery();
            waybillQuery.setBuyerId(id);
            checkWaybill(waybillQuery);

            // 查询挂靠该屠宰场的待宰户
            UserQuery userQuery = new UserQuery();
            userQuery.setSlaughterHouseParentId(id);
            List<UserDTO> userDTOS = userService.listUser(userQuery);

            // 检查待宰户的调运单和运输单
            if (CollectionUtils.isNotEmpty(userDTOS)) {
                for (UserDTO dto : userDTOS) {
                    Long slaughterHouseId = dto.getId();
                    TransportQuery transportQuery1 = new TransportQuery();
                    transportQuery1.setSlaughterHouseId(slaughterHouseId);
                    List<TransportDTO> transportDTOS = transportService.listTransport(transportQuery1);
                    if (CollectionUtils.isNotEmpty(transportDTOS)) {
                        for (TransportDTO transportDTO : transportDTOS) {
                            boolean flag = transportDTO.getState().equals(UserStateEnum.UNCHECK.getCode()) ||
                                    transportDTO.getState().equals(UserStateEnum.PASS.getCode());
                            Validator.isTrue(!flag, ErrorMsg.NEW("屠宰场名下的待宰户存在新建或是调运中的运输单，待宰户id为:" + slaughterHouseId));
                        }
                    }

                    WaybillQuery waybillQuery1 = new WaybillQuery();
                    waybillQuery1.setSlaughterHouseId(slaughterHouseId);
                    List<WaybillListVO> waybillListVOS = waybillService.listWaybill(waybillQuery1);
                    if (CollectionUtils.isNotEmpty(waybillListVOS)) {
                        for (WaybillListVO waybillListVO : waybillListVOS) {
                            boolean flag = waybillListVO.getState().equals(WaybillStateEnum.UNCHECK.getCode()) ||
                                    waybillListVO.getState().equals(WaybillStateEnum.PASS.getCode()) ||
                                    waybillListVO.getState().equals(WaybillStateEnum.TRANSPORT.getCode());
                            Validator.isTrue(!flag, ErrorMsg.NEW("屠宰场名下的待宰户存在待确认、待审批或是调运中的调运单，待宰户id为:" + slaughterHouseId));
                        }
                    }

                    // 挂靠待宰户挂靠屠宰场id和名称删除
                    UserDTO userDTO1 = new UserDTO();
                    userDTO1.setId(slaughterHouseId);
                    userDTO1.setSlaughterHouseParentId(0L);
                    userDTO1.setSlaughterHouseParentName("");
                    userService.updateUser(userDTO1);
                }
            }

            //新增逻辑：解绑已经绑定的代宰户
            RelationQuery query = new RelationQuery();
            query.setBuyerUserId(userDTO.getId());
            List<SlaughterBuyerRelationDTO> relationDTOS = slaughterBuyerRelationService.queryList(query);
            if (CollectionUtils.isNotEmpty(relationDTOS)) {
                for (SlaughterBuyerRelationDTO relationDTO : relationDTOS) {
                    Validator.isTrue(slaughterBuyerRelationService.deleteById(relationDTO.getId()), ErrorCode.RELATION_DELETE_FAIL);
                    //如果绑定关系是已绑定，增加一条解绑记录
                    if (relationDTO.getState().intValue() == RelationStateEnum.BIND.getCode()) {
                        SlaughterBuyerRelationLogDTO logDTO = ModelConvertUtil.copyTo(relationDTO, SlaughterBuyerRelationLogDTO.class);
                        logDTO.setType(RelationTypeEnum.UNBIND.getCode());
                        logDTO.setReason("屠宰场注销自动解绑");
                        logDTO.setInitiator(userDTO.getType());//设置解绑的发起方
                        Long logId = slaughterBuyerRelationLogService.insert(logDTO);
                        Validator.notNull(logId, ErrorCode.RELATION_LOG_INSERT_FAIL);
                    } else if (relationDTO.getState().intValue() == RelationStateEnum.UNCHECK.getCode()) {
                        Validator.isTrue(false, ErrorCode.RELATION_STATE_IS_ERROR);
                    }

                }
            }
        }

        // 当类型是养殖场时
        if (type.equals(UserTypeEnum.FARM.getCode())) {
            // 检查合同
            ContractQuery contractQuery = new ContractQuery();
            contractQuery.setSalerId(id);
            checkContract(contractQuery);

            // 检查运输单
            TransportQuery transportQuery = new TransportQuery();
            transportQuery.setSalerId(id);
            checkTransport(transportQuery);

            // 检查调运单
            WaybillQuery waybillQuery = new WaybillQuery();
            waybillQuery.setSalerId(id);
            checkWaybill(waybillQuery);
        }

        // 当类型是司机时
        if (type.equals(UserTypeEnum.DRIVER.getCode())) {
            // 检查运输单
            TransportQuery transportQuery = new TransportQuery();
            transportQuery.setDriverId(id);
            List<TransportDTO> transportDTOS = transportService.listTransport(transportQuery);
            if (CollectionUtils.isNotEmpty(transportDTOS)) {
                for (TransportDTO transportDTO : transportDTOS) {
                    boolean flag = transportDTO.getState().equals(WaybillStateEnum.UNCHECK.getCode()) ||
                            transportDTO.getState().equals(WaybillStateEnum.PASS.getCode()) ||
                            transportDTO.getState().equals(WaybillStateEnum.TRANSPORT.getCode());
                    Validator.isTrue(!flag, ErrorMsg.NEW("存在新建或是调运中的运输单"));
                }
            }
        }

        // 当类型是经纪人时
        if (type.equals(UserTypeEnum.AGENT.getCode())) {
            // 检查运输单
            TransportQuery transportQuery = new TransportQuery();
            transportQuery.setAgentId(id);
            checkTransport(transportQuery);

            // 检查调运单
            WaybillQuery waybillQuery = new WaybillQuery();
            waybillQuery.setAgentId(id);
            checkWaybill(waybillQuery);
        }

        // 当类型是待宰户时
        if (type.equals(UserTypeEnum.SLAUGHTER_HOUSE.getCode())) {
            // 检查运输单
            TransportQuery transportQuery = new TransportQuery();
            transportQuery.setSlaughterHouseId(id);
            checkTransport(transportQuery);

            // 检查调运单
            WaybillQuery waybillQuery = new WaybillQuery();
            waybillQuery.setSlaughterHouseId(id);
            checkWaybill(waybillQuery);

            //新增逻辑：解绑已经绑定的代宰户
            RelationQuery query = new RelationQuery();
            query.setSlaughterHouseId(userDTO.getId());
            List<SlaughterBuyerRelationDTO> relationDTOS = slaughterBuyerRelationService.queryList(query);
            if (CollectionUtils.isNotEmpty(relationDTOS)) {
                for (SlaughterBuyerRelationDTO relationDTO : relationDTOS) {
                    Validator.isTrue(slaughterBuyerRelationService.deleteById(relationDTO.getId()), ErrorCode.RELATION_DELETE_FAIL);
                    //如果绑定关系是已绑定，增加一条解绑记录
                    if (relationDTO.getState().intValue() == RelationStateEnum.BIND.getCode()) {
                        SlaughterBuyerRelationLogDTO logDTO = ModelConvertUtil.copyTo(relationDTO, SlaughterBuyerRelationLogDTO.class);
                        logDTO.setType(RelationTypeEnum.UNBIND.getCode());
                        logDTO.setReason("代宰户注销自动解绑");
                        logDTO.setInitiator(type);//设置解绑的发起方
                        Long logId = slaughterBuyerRelationLogService.insert(logDTO);
                        Validator.notNull(logId, ErrorCode.RELATION_LOG_INSERT_FAIL);
                    } else if (relationDTO.getState().intValue() == RelationStateEnum.UNCHECK.getCode()) {
                        Validator.isTrue(false, ErrorCode.RELATION_STATE_IS_ERROR);
                    }

                }
            }
        }

        // 用户注销
        userService.deleteById(id);
        return true;
    }

    /**
     * 检查是否存在新建或是生效的合同
     *
     * @param contractQuery
     * @return
     */
    private void checkContract(ContractQuery contractQuery) {
        List<ContractDTO> contractDTOS = contractService.getContractList(contractQuery);
        if (CollectionUtils.isNotEmpty(contractDTOS)) {
            for (ContractDTO contractDTO : contractDTOS) {
                boolean flag = contractDTO.getState().equals(UserStateEnum.UNCHECK.getCode()) ||
                        contractDTO.getState().equals(UserStateEnum.PASS.getCode());
                Validator.isTrue(!flag, ErrorMsg.NEW("存在新建或是生效的合同"));
            }
        }
    }

    /**
     * 检查是否存在待确认、待审批或是调运中的调运单
     *
     * @param waybillQuery
     * @return
     */
    private void checkWaybill(WaybillQuery waybillQuery) {
        List<WaybillListVO> waybillListVOS = waybillService.listWaybill(waybillQuery);
        if (CollectionUtils.isNotEmpty(waybillListVOS)) {
            for (WaybillListVO waybillListVO : waybillListVOS) {
                boolean flag = waybillListVO.getState().equals(WaybillStateEnum.UNCHECK.getCode()) ||
                        waybillListVO.getState().equals(WaybillStateEnum.PASS.getCode()) ||
                        waybillListVO.getState().equals(WaybillStateEnum.TRANSPORT.getCode());
                Validator.isTrue(!flag, ErrorMsg.NEW("存在待确认、待审批或是调运中的调运单"));
            }
        }
    }

    /**
     * 检查是否存在新建或是调运中的运输单
     *
     * @param transportQuery
     * @return
     */
    private void checkTransport(TransportQuery transportQuery) {
        List<TransportDTO> transportDTOS = transportService.listTransport(transportQuery);
        if (CollectionUtils.isNotEmpty(transportDTOS)) {
            for (TransportDTO transportDTO : transportDTOS) {
                boolean flag = transportDTO.getState().equals(WaybillStateEnum.UNCHECK.getCode()) ||
                        transportDTO.getState().equals(WaybillStateEnum.PASS.getCode()) ||
                        transportDTO.getState().equals(WaybillStateEnum.TRANSPORT.getCode()) ||
                        transportDTO.getState().equals(WaybillStateEnum.REJECT.getCode());
                Validator.isTrue(!flag, ErrorMsg.NEW("存在新建、已驳回或是调运中的运输单"));
            }
        }
    }

    public Boolean updatePassword(UpdatePasswordVO updatePasswordVO) {
        Validator.notNull(updatePasswordVO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(updatePasswordVO.getPhone(), ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(updatePasswordVO.getSmsCode(), ErrorCode.INPUT_PARAMETERS_NULL);
        checkUserPassword(updatePasswordVO.getPassword(), updatePasswordVO.getConfirmPassword());
        checkSms(updatePasswordVO.getPhone(), updatePasswordVO.getSmsCode());
        UserQuery userQuery = new UserQuery();
        userQuery.setPhone(updatePasswordVO.getPhone());
        UserDTO user = userService.getOneUser(userQuery);
        Validator.notNull(user, ErrorCode.USER_IS_NOT_REGISTERED);
        Validator.isTrue(!user.getPassword().equals(updatePasswordVO.getPassword()), ErrorCode.NEW_USER_PASSWORD);
        user.setPassword(updatePasswordVO.getPassword());
        userService.updateUser(user);
        return true;
    }

    public AccountInfoVo getAccount(HttpSession session) {
        AccountInfoVo infoVo = new AccountInfoVo();
        String password = (String) session.getAttribute(Constants.PASSWORD);
        String phone = (String) session.getAttribute(Constants.PHONE);

        if (StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(password)) {
            AccountValidatorUtils.isMobile(phone);
            UserQuery userQuery = new UserQuery();
            userQuery.setPhone(phone);
            UserDTO oneUser = userService.getOneUser(userQuery);
            if (oneUser != null && oneUser.getState() == UserStateEnum.PASS.getCode()) {
                String sign = oneUser.getId() + oneUser.getPassword();
                String md5 = MD5Utils.getMD5(sign);
                if (md5.equals(password)) {
                    infoVo.setPassword(oneUser.getPassword());
                    infoVo.setPhone(oneUser.getPhone());
                }
            }
        }
        return infoVo;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean resubmitSlaughter(UserDTO userDTO) {
        Validator.notNull(userDTO, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(userDTO.getId(), ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(userDTO.getSlaughterHouseParentName(), ErrorCode.INPUT_PARAMETERS_NULL);
        UserDTO user = userService.getUserById(userDTO.getId());
        Validator.notNull(user, ErrorCode.INPUT_PARAMETERS_INVALID);
        Validator.isTrue(UserTypeEnum.SLAUGHTER_HOUSE.getCode() == user.getType(), ErrorCode.INPUT_PARAMETERS_INVALID);
        Validator.isTrue(user.getSlaughterHouseParentId() == null || user.getSlaughterHouseParentId() == 0, ErrorCode.INPUT_PARAMETERS_INVALID);
        Validator.isTrue(StringUtils.isBlank(user.getSlaughterHouseParentName()), ErrorCode.INPUT_PARAMETERS_INVALID);
        UserQuery userQuery = new UserQuery();
        userQuery.setName(userDTO.getSlaughterHouseParentName());
        UserDTO slaughter = userService.getOneUser(userQuery);
        Validator.notNull(slaughter, ErrorCode.SLAUGHTER_IS_NULL);
        Validator.isTrue(UserStateEnum.PASS.getCode() == slaughter.getState(), ErrorCode.SLAUGHTER_IS_EXP);
        Validator.isTrue(UserTypeEnum.SLAUGHTER.getCode() == slaughter.getType(), ErrorCode.SLAUGHTER_IS_EXP);

        user.setSlaughterHouseParentId(slaughter.getId());
        user.setSlaughterHouseParentName(userDTO.getSlaughterHouseParentName());
        user.setState(UserStateEnum.UNCHECK.getCode());
        userService.updateUser(user);

//        ApplicationInfoDTO applicationInfoDTO = initApplicationInfo(ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode(), userDTO.getId(), slaughter, user);
//        applicationInfoDTO.setLinkTable(Constants.TB_USER);
//        applicationInfoService.addApplicationInfo(applicationInfoDTO);
        return true;
    }

    public Boolean checkPassword(Long id, String password) {
        Validator.notNull(id, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(password, ErrorCode.INPUT_PARAMETERS_NULL);

        UserDTO userDTO1 = userService.getUserById(id);
        Validator.isTrue(password.equals(userDTO1.getPassword()), ErrorCode.USER_CONFIRM_PASSWORD_ERROR);
        return true;
    }

    private String formateHtml(String chars){
        String str = chars.replace("amp;","");
        return StringEscapeUtils.unescapeHtml4(str);
    }

}
