package com.bcxin.tenant.domain.entities.reports;

import com.bcxin.Infrastructures.entities.IAggregate;
import com.bcxin.Infrastructures.entities.DomainEntityAbstract;
import com.bcxin.Infrastructures.entities.SyncDomainEntityAbstract;
import com.bcxin.Infrastructures.enums.*;
import com.bcxin.tenant.domain.entities.*;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;

@Getter
@Setter(AccessLevel.PROTECTED)
@Table(name = "report_employees")
@Entity
public class EmployeeReportEntity extends SyncDomainEntityAbstract implements IAggregate {
    /**
     * employee的id
     */
    @Id
    @Column(name = "id")
    private String id;
    /**
     * 姓名
     */
    @Column(name = "name")
    private String name;
    /**
     * 所在部门
     */
    @Column(name = "depart_id")
    private String departId;
    /**
     * 所在部门
     */
    @Column(name = "depart_name")
    private String departName;

    /**
     * 职业, 对应
     */
    @Column(name = "occupation_type")
    private OccupationType occupationType;

    /**
     * 人员类型, 该值由occupationType来推出
     */
    @Column(name = "job_type")
    private String jobType;

    /**
     * 证件类型
     */
    @Column(name = "credential_type")
    private CredentialType credentialType;
    /**
     * 证件号
     */
    @Column(name = "credential_number")
    private String credentialNumber;
    /**
     * 手机号码
     */
    @Column(name = "telephone")
    private String telephone;
    /**
     * 入职日期
     */
    @Column(name = "hired_date")
    private Date hiredDate;
    /**
     * 生日
     */
    @Column(name = "birth_date")
    private Date birthDate;

    @Column(name = "sex")
    private Sex sex;
    /**
     * 国级
     */
    @Column(name = "nationality")
    private String nationality;
    /**
     * 学历
     */
    @Column(name = "education")
    private String education;
    /**
     * 身高
     */
    @Column(name = "stature")
    private String stature;
    /**
     * 血型
     */
    @Column(name = "blood_type")
    private String bloodType;
    /**
     * 民族
     */
    @Column(name = "nation")
    private String nation;
    /**
     * 政治面貌
     */
    @Column(name = "politics_status")
    private String politicsStatus;
    /**
     * 婚姻状况
     */
    @Column(name = "military_status")
    private String militaryStatus;
    /**
     * 居住地址
     */
    @Column(name = "home_address")
    private String homeAddress;
    /**
     * 户籍类型
     */
    @Column(name = "household_type")
    private String householdType;
    /**
     * 紧急联系人
     */
    @Column(name = "emergency_contact")
    private String emergencyContact;

    /**
     * 紧急联系人
     */
    @Column(name = "emergency_phone")
    private String emergencyPhone;

    /**
     * 驾照等级
     */
    @Column(name = "license_level")
    private String licenseLevel;

    /**
     * 是否退伍军人
     */
    @Column(name = "is_veteran")
    private TrueFalseStatus isVeteran;

    /**
     * 从业年限
     */
    @Column(name = "work_years")
    private String workYears;

    /**
     * 疾病史
     */
    @Column(name = "disease_history")
    private String diseaseHistory;

    /**
     * 证件核验
     */
    @Column(name = "is_certified")
    private String isCertified;

    /**
     * 身份证人像面
     */
    @Column(name = "id_face_photo")
    private String IDFacePhoto;

    /**
     * 身份证国徽面
     */
    @Column(name = "id_nation_photo")
    private String IDNationPhoto;

    /**
     * 身份证头像
     */
    @Column(name = "id_header_photo")
    private String IDHeaderPhoto;

    /**
     * 用户是否在本企业
     */
    @Column(name = "is_in_my_company")
    private TrueFalseStatus isInMyCompany;

    /**
     * 最后认证时间
     */
    @Column(name = "last_auth_time")
    private Timestamp LastAuthTime;

    /**
     * 最后一次筛查时间
     */
    @Column(name = "last_search_past_time")
    private Timestamp lastSearchPastTime;

    /**
     * 离职时间
     */
    @Column(name = "leave_date")
    private Timestamp leaveDate;

    /**
     * 公司名称
     */
    @Column(name = "company_name")
    private String companyName;

    /**
     * 是否投保
     */
    @Column(name = "insure")
    private TrueFalseStatus insure;

    /**
     * 身份证有效期起始时间
     */
    @Column(name = "id_validation_s")
    private String idValidationS;

    /**
     * 身份证有效期结束时间
     */
    @Column(name = "id_validation_e")
    private String idValidationE;

    /**
     * 身份证地址
     */
    @Column(name = "id_address")
    private String idAddress;

    /**
     * 驻勤安排
     */
    @Column(name = "attendance_site_status")
    private String attendanceSiteStatus;

    /**
     * 定位经纬度
     */
    @Column(name = "location")
    private String location;

    /**
     * 日期限制
     */
    @Column(name = "data_restrict")
    private Timestamp dataRestrict;

    @Column(name = "certification")
    private String certification;

    /**
     * 判断身份证返回值
     */
    @Column(name = "document_id_bool")
    private String documentIDBool;

    /**
     * 实名认证状态
     */
    @Column(name = "is_state")
    private String isState;

    /**
     * 备注信息
     */
    @Column(name = "remark")
    private String remark;

    @Column(name = "version")
    private long version;

    @Column(name = "last_updated_time")
    private Timestamp lastUpdatedTime;

    @Column(name = "shi_ming")
    private String shiming;

    @Column(name = "is_deleted")
    private TrueFalseStatus isDeleted;

    @Column(name = "superior_id")
    private String superiorId;

    @Column(name = "tenant_user_id")
    private String tenantUserId;

    @Column(name = "created_time")
    private Timestamp createdTime;

    @Column(name = "organization_id",length = 200)
    private String organizationId;

    /**
     * 一寸免冠白底彩照
     */
    @Column(name = "one_inch_color_white_photo",length = 1000)
    private String oneInchColorWhitePhoto;

    /**
     * 两寸免冠蓝底彩照
     */
    @Column(name = "two_inch_color_blue_photo",length = 1000)
    private String twoInchColorBluePhoto;

    @Column(name = "is_in_mycompany")
    private String isInmycompany;

    protected EmployeeReportEntity() {
        this.setCreatedTime(Timestamp.from(Instant.now()));
    }

    protected EmployeeReportEntity(String id, String organId) {
        this();
        this.setId(id);
        this.setDomainId(organId);
    }

    public static EmployeeReportEntity create(EmployeeEntity employee) {
        EmployeeReportEntity reportEntity =
                new EmployeeReportEntity(employee.getId(), employee.getOrganization().getId());
        reportEntity.update(employee);
        reportEntity.setIsDeleted(TrueFalseStatus.False);

        return reportEntity;
    }

    public void update(EmployeeEntity employee) {
        this.markAsDeleted(false);
        TenantUserEntity tenantUser = employee.getTenantUser();
        OrganizationEntity organization = employee.getOrganization();
        TenantUserCredentialsEntity userCredentials = tenantUser.getSelectedCredential();
        DepartmentEntity department = employee.getDefaultDepartment();

        Timestamp now = Timestamp.from(Instant.now());
        this.setLastUpdatedTime(now);
        this.setVersion(now.getTime());

        this.setBirthDate(tenantUser.getBirthdate());
        this.setEducation(tenantUser.getEducation());
        this.setAttendanceSiteStatus("");//todo
        this.setBloodType("");//todo
        this.setCertification("");//todo
        this.setCompanyName(organization.getName());
        this.setDocumentIDBool("");//todo
        this.setSuperiorId(employee.getSuperior()==null?null:employee.getSuperior().getId());

        if (department != null) {
            this.setDepartId(department.getId());
            this.setDepartName(department.getName());
        }
        //this.setDataRestrict();//todo
        this.setDiseaseHistory("");//todo
        this.setAttendanceSiteStatus("");//todo
        this.setEmergencyContact("");//todo
        this.setName(tenantUser.getName());
        this.setOccupationType(OccupationType.Normal);//todo
        this.setJobType("xxxxxxx");

        this.setTelephone(tenantUser.getTelephone());
        this.setTenantUserId(tenantUser.getId());
        this.setHiredDate(employee.getHiredDate());
        this.setSex(tenantUser.getSex());

        this.setNationality("");//todo
        this.setStature(tenantUser.getStature());//todo
        this.setNation(tenantUser.getNation());
        this.setPoliticsStatus(tenantUser.getPoliticsStatus());
        this.setMilitaryStatus(tenantUser.getMilitaryStatus());
        this.setHouseholdType(tenantUser.getHouseholdType());
        this.setEmergencyContact("");//todo
        this.setEmergencyPhone("");//todo
        this.setLicenseLevel("");//todo
        this.setIsVeteran(tenantUser.getUserType() == UserType.exSoldier ? TrueFalseStatus.True : TrueFalseStatus.False);
        this.setWorkYears("");//todo
        this.setDiseaseHistory("");//todo
        this.setShiming("");
        this.setOrganizationId(organization.getId());


        if (tenantUser.getAuthenticateStatus() != null) {
            switch (tenantUser.getAuthenticateStatus()) {
                case Authenticating:
                    this.setShiming("认证中");
                    break;
                case Passed:
                    this.setShiming("已认证");
                    break;
                case Failed:
                    this.setShiming("认证失败");
                    break;
                case UnAuthenticated:
                    this.setShiming("未认证");
                    break;
            }
        }

        this.setIsCertified("");
        if (tenantUser.getCheckedStatus() != null) {
            switch (tenantUser.getCheckedStatus()) {
                case Matched:
                    this.setIsCertified("已核验");
                    break;
                case Commit:
                    this.setIsCertified("已提交");
                    break;
                case None:
                    this.setIsCertified("未提交");
                    break;
            }
        }

        if (userCredentials != null) {
            this.setCredentialNumber(userCredentials.getNumber());
            this.setCredentialType(userCredentials.getCredentialType());//todo
            this.setHomeAddress(userCredentials.getAddress());
            this.setIDFacePhoto(userCredentials.getFrontPhoto());
            this.setIDNationPhoto(userCredentials.getReversePhoto());
            this.setIDHeaderPhoto(userCredentials.getHeadPhoto());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            this.setIdValidationS(userCredentials.getValidDateFrom() == null ? "永久" : simpleDateFormat.format(userCredentials.getValidDateFrom()));
            this.setIdValidationE(userCredentials.getValidDateTo() == null ? "永久" : simpleDateFormat.format(userCredentials.getValidDateTo()));
            this.setIdAddress(userCredentials.getAddress());
        }

        this.setIsInMyCompany(TrueFalseStatus.True);
        if (employee.getStatus() == EmploymentStatus.OffJob) {
            this.setIsInMyCompany(TrueFalseStatus.False);
        }

        this.setLastAuthTime(tenantUser.getAuthenticatedTime());
        this.setLeaveDate(employee.getLeaveTime());
        this.setInsure(employee.getInsure());

        this.setAttendanceSiteStatus("");/// TODO: 2021/12/11
        this.setLocation(tenantUser.getLonLatJson());
        this.setDocumentIDBool("");
        this.setIsState("");
        this.setRemark(tenantUser.getAuthenticatedResult());
    }

    public void markAsDeleted(boolean isDeleted) {
        this.setIsDeleted(isDeleted ? TrueFalseStatus.True : TrueFalseStatus.False);
    }
}