package shop.alien.entity.store;

import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import shop.alien.util.encryption.EncryptTypeHandler;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

/**
 * 律师用户
 *
 * @author system
 * @since 2025-01-XX
 */
@Data
@JsonInclude
@TableName(value = "lawyer_user", autoResultMap = true)
@ApiModel(value = "LawyerUser对象", description = "律师用户")
public class LawyerUser extends Model<LawyerUser> {

    /** logout_flag：未注销 */
    public static final int LOGOUT_FLAG_NORMAL = 0;
    /** logout_flag：已注销（冷静期结束后） */
    public static final int LOGOUT_FLAG_DONE = 1;
    /** logout_flag：注销冷静期 */
    public static final int LOGOUT_FLAG_COOLING = 2;
    /** 注销完成后禁止重新注册的天数（自 logoutTime 日起，T+14 00:00 起可注册） */
    public static final int RE_REGISTER_BLOCK_DAYS = 14;

    public LawyerUser() {
    }

    public LawyerUser(Integer id, Integer money) {
        this.id = id;
        this.money = money;
    }

    @ApiModelProperty(value = "主键")
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @ApiModelProperty(value = "律所id")
    @TableField("firm_id")
    private Integer firmId;

    @ApiModelProperty(value = "律所明细id")
    @TableField("firm_payment_id")
    private Integer firmPaymentId;

    @ApiModelProperty(value = "手机号")
    @TableField("phone")
    private String phone;

    @ApiModelProperty(value = "姓名")
    @TableField("name")
    private String name;

    @ApiModelProperty(value = "身份证")
    @TableField("id_card")
    private String idCard;

    @ApiModelProperty(value = "密码")
    @TableField(value = "password", typeHandler = EncryptTypeHandler.class)
    private String password;

    @ApiModelProperty(value = "支付密码")
    @TableField("pay_password")
    private String payPassword;

    @ApiModelProperty(value = "用户余额,单位分")
    @TableField("money")
    private Integer money;

    @ApiModelProperty(value = "用户状态, 0:禁用, 1:启用")
    @TableField("status")
    private Integer status;

    @ApiModelProperty(value = "密码状态, 0:初始密码, 1:已修改, 2:手机号已验证")
    @TableField("pass_type")
    private Integer passType;

    @ApiModelProperty(value = "删除标记, 0:未删除, 1:已删除")
    @TableField("delete_flag")
    @TableLogic
    private Integer deleteFlag;

    @ApiModelProperty(value = "创建时间")
    @TableField(value = "created_time", fill = FieldFill.INSERT)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createdTime;

    @ApiModelProperty(value = "创建人ID")
    @TableField("created_user_id")
    private Integer createdUserId;

    @ApiModelProperty(value = "修改时间")
    @TableField(value = "updated_time", fill = FieldFill.UPDATE)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date updatedTime;

    @ApiModelProperty(value = "修改人ID")
    @TableField("updated_user_id")
    private Integer updatedUserId;

    @ApiModelProperty(value = "注销标记, 0:未注销, 1:已注销, 2:注销冷静期")
    @TableField("logout_flag")
    private Integer logoutFlag;

    @ApiModelProperty(value = "注销原因")
    @TableField("logout_reason")
    private String logoutReason;

    @ApiModelProperty(value = "注销申请时间")
    @TableField(value = "logout_time", fill = FieldFill.INSERT)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date logoutTime;

    @ApiModelProperty(value = "注销code")
    @TableField("logout_code")
    private String logoutCode;

    @ApiModelProperty(value = "昵称")
    @TableField("nick_name")
    private String nickName;

    @ApiModelProperty(value = "账号简介")
    @TableField("account_blurb")
    private String accountBlurb;

    @ApiModelProperty(value = "头像")
    @TableField("head_img")
    private String headImg;

    @ApiModelProperty(value = "支付宝账号")
    @TableField("alipay_account")
    private String alipayAccount;

    @ApiModelProperty(value = "律师支付宝appid")
    @TableField("lawyer_ali_id")
    private String lawyerAliId;

    @ApiModelProperty(value = "律师支付宝名称")
    @TableField("lawyer_ali_name")
    private String lawyerAliName;

    @ApiModelProperty(value = "律师微信appid")
    @TableField("lawyer_wechat_id")
    private String lawyerWechatId;

    @ApiModelProperty(value = "律师微信名称")
    @TableField("lawyer_wechat_name")
    private String lawyerWechatName;

    @ApiModelProperty(value = "银行卡号")
    @TableField("bank_card_no")
    private String bankCardNo;

    @ApiModelProperty(value = "开户银行名称")
    @TableField("bank_name")
    private String bankName;

    // ========== 律师特有字段 ==========

    @ApiModelProperty(value = "律师执业证号")
    @TableField("lawyer_certificate_no")
    private String lawyerCertificateNo;

    @ApiModelProperty(value = "所属律师事务所")
    @TableField("law_firm")
    private String lawFirm;

    @ApiModelProperty(value = "执业年限（根据执业开始日期自动计算）")
    @TableField(exist = false)
    private Integer practiceYears;

    @ApiModelProperty(value = "执业开始日期")
    @TableField("practice_start_date")
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    private Date practiceStartDate;

    /**
     * 获取执业年限（根据执业开始日期自动计算）
     * 返回当前时间减去执业开始时间的年数
     *
     * @return 执业年限（年）
     */
    public Integer getPracticeYears() {
        if (practiceStartDate == null) {
            return null;
        }
        try {
            // 将 Date 转换为 LocalDate
            LocalDate startDate = practiceStartDate.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate();
            LocalDate currentDate = LocalDate.now();

            // 计算年数差
            long years = ChronoUnit.YEARS.between(startDate, currentDate);
            return (int) Math.max(0, years); // 确保不为负数
        } catch (Exception e) {
            return null;
        }
    }

    @ApiModelProperty(value = "专业领域,多个用逗号分隔")
    @TableField("specialty_fields")
    private String specialtyFields;

    @ApiModelProperty(value = "资质认证状态, 0:未认证, 1:认证中, 2:已认证, 3:认证失败")
    @TableField("certification_status")
    private Integer certificationStatus;

    @ApiModelProperty(value = "认证失败原因")
    @TableField("certification_fail_reason")
    private String certificationFailReason;

    @ApiModelProperty(value = "认证时间")
    @TableField("certification_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date certificationTime;

    @ApiModelProperty(value = "认证审核人ID")
    @TableField("certification_reviewer_id")
    private Integer certificationReviewerId;

    @ApiModelProperty(value = "执业证照片")
    @TableField("certificate_image")
    private String certificateImage;

    @ApiModelProperty(value = "身份证正面照片")
    @TableField("id_card_front_image")
    private String idCardFrontImage;

    @ApiModelProperty(value = "身份证反面照片")
    @TableField("id_card_back_image")
    private String idCardBackImage;

    @ApiModelProperty(value = "营业执照照片")
    @TableField("business_license_image")
    private String businessLicenseImage;

    @ApiModelProperty(value = "服务评分, 0-5分（保留一位小数）")
    @TableField("service_score")
    private Double serviceScore;

    @ApiModelProperty(value = "服务次数")
    @TableField("service_count")
    private Integer serviceCount;

    @ApiModelProperty(value = "好评数")
    @TableField("good_review_count")
    private Integer goodReviewCount;

    @ApiModelProperty(value = "中评数")
    @TableField("medium_review_count")
    private Integer mediumReviewCount;

    @ApiModelProperty(value = "差评数")
    @TableField("bad_review_count")
    private Integer badReviewCount;

    @ApiModelProperty(value = "咨询收费标准(单位分/小时)")
    @TableField("consultation_fee")
    private Integer consultationFee;

    @ApiModelProperty(value = "代理收费标准(单位分)")
    @TableField("agency_fee")
    private Integer agencyFee;

    @ApiModelProperty(value = "所属省份")
    @TableField("province")
    private String province;

    @ApiModelProperty(value = "所属城市")
    @TableField("city")
    private String city;

    @ApiModelProperty(value = "所属区县")
    @TableField("district")
    private String district;

    @ApiModelProperty(value = "详细地址")
    @TableField("address")
    private String address;

    @ApiModelProperty(value = "邮箱")
    @TableField("email")
    private String email;

    @ApiModelProperty(value = "性别, 0:未知, 1:男, 2:女")
    @TableField("gender")
    private Integer gender;

    @ApiModelProperty(value = "生日")
    @TableField("birthday")
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    private Date birthday;

    @ApiModelProperty(value = "个人简介(详细)")
    @TableField("personal_introduction")
    private String personalIntroduction;

    @ApiModelProperty(value = "教育背景")
    @TableField("education_background")
    private String educationBackground;

    @ApiModelProperty(value = "工作经历")
    @TableField("work_experience")
    private String workExperience;

    @ApiModelProperty(value = "擅长案件类型")
    @TableField("expertise_cases")
    private String expertiseCases;

    @ApiModelProperty(value = "是否在线, 0:离线, 1:在线")
    @TableField("is_online")
    private Integer isOnline;

    @ApiModelProperty(value = "最后在线时间")
    @TableField("last_online_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date lastOnlineTime;

    @ApiModelProperty(value = "是否推荐, 0:不推荐, 1:推荐")
    @TableField("is_recommended")
    private Integer isRecommended;

    @ApiModelProperty(value = "推荐排序")
    @TableField("recommend_sort")
    private Integer recommendSort;

    @ApiModelProperty(value = "接单状态, 0:不接单, 1:接单中")
    @TableField("order_receiving_status")
    private Integer orderReceivingStatus;

    @ApiModelProperty(value = "领域ID")
    @TableField("lawyer_expertise_area_id")
    private Integer lawyerExpertiseAreaId;

    @ApiModelProperty(value = "法律问题场景")
    @TableField(exist = false)
    private List<LawyerLegalProblemScenario> lawyerLegalProblemScenarioList;

    @ApiModelProperty(value = "佣金比例")
    @TableField("commission_rate")
    private Integer commissionRate;

    @ApiModelProperty(value = "律师事务所收款账号")
    @TableField("payment_num")
    private String paymentNum;

    @TableField(exist = false)
    private String userName;

    @TableField(exist = false)
    private String userImage;

    @TableField(exist = false)
    private String jianjie;

    @TableField(exist = false)
    private String moneyStr;

    @ApiModelProperty(value = "评价数（只统计评价，不包含评论）")
    @TableField(exist = false)
    private Integer reviewCount;

    @ApiModelProperty(value = "分钟收费-钱数")
    @TableField("charge_minute")
    private Integer chargeMinute;

    @ApiModelProperty(value = "分钟收费-分钟数")
    @TableField("minute_num")
    private Integer minuteNum;

    @ApiModelProperty(value = "次数收费-钱数")
    @TableField("charge_time")
    private Integer chargeTime;

    @ApiModelProperty(value = "次数收费-次数")
    @TableField("time_num")
    private Integer timeNum;

    @ApiModelProperty(value = "免费咨询开关, 0:关闭, 1:开启")
    @TableField("free_consultation")
    private Integer freeConsultation;

    @ApiModelProperty(value = "支付宝二级商户是否绑定")
    @TableField("zfb_secondary_merchant_account")
    private String zfbSecondaryMerchantAccount;

    /**
     * 注销完成日 T（logoutTime）起，至 T+{@link #RE_REGISTER_BLOCK_DAYS} 日 00:00 前禁止重新注册/登录。
     */
    public static boolean isWithinReRegisterBlockPeriod(Date logoutTime) {
        if (logoutTime == null) {
            return false;
        }
        LocalDateTime allowFrom = logoutTime.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate()
                .plusDays(RE_REGISTER_BLOCK_DAYS)
                .atStartOfDay();
        return LocalDateTime.now().isBefore(allowFrom);
    }

}

