INSERT INTO `personnel_oa`.`com_base_info` (
    `tlkId`,
    `createTime`,
    `updateTime`,
    `comName`,
    `logoUrl`,
    `industryType`,
    `institutionType`)
SELECT
    o.id,
    o.created_time,
    o.last_updated_time,
    o.`name`,
    o.logo_path,
    o.industry_code,
    o.institutional_code
FROM obpm2.tenant_organizations o;


INSERT INTO `personnel_oa`.`per_base_info` (
    `tlkId`,
    `createTime`,
    `updateTime`,
    `name`,
    `photoUrl`,
    `sex`,
    `birthday`,
    `mobilePhone`,
    `isIncumbency`)
SELECT
    u.id,
    u.created_time,
    u.last_updated_time,
    u.`name`,
    u.head_photo,
    u.sex,
    u.birthdate,
    u.telephone,
    0
FROM obpm2.tenant_users u;

UPDATE personnel_oa.per_base_info pbi
SET pbi.isIncumbency = '1'
WHERE
    EXISTS (
            SELECT
                e.id
            FROM
                obpm2.tenant_employees e
            WHERE
                    e.tenant_user_id = pbi.tlkId and e.`status` = 0
        );

UPDATE `personnel_oa`.`per_base_info` pbi
SET pbi.idCardNo = (
    SELECT
        tuc.number
    FROM
        obpm2.tenant_user_credentials tuc
    WHERE
            tuc.tenant_user_id = pbi.tlkId
      AND tuc.credential_type = 0
    LIMIT 0,
    1);

UPDATE `personnel_oa`.`per_base_info` pbi
SET pbi.idCardType = '1'
WHERE
    pbi.idCardNo IS NOT NULL;

INSERT INTO `personnel_oa`.`com_depart` (
    `tlkId`,
    `createTime`,
    `updateTime`,
    `isDelete`,
    `departName`,
    `isActive`,
    `seq`,
    `departTreeCode`,
    `parentDepartId`,
    `comId`)
SELECT
    td.id,
    td.created_time,
    td.last_updated_time,
    td.is_deleted,
    td.`name`,
    td.`status`,
    td.display_order,
    td.index_tree,
       -1,
    (SELECT cbi.comId from personnel_oa.com_base_info cbi WHERE cbi.tlkId = td.organization_id)
FROM obpm2.tenant_departments td WHERE td.is_deleted = 0;

UPDATE `personnel_oa`.`com_depart` cd1,
    `personnel_oa`.`com_depart` cd2
SET cd1.parentDepartId = cd2.departId
WHERE
    cd2.tlkId = ( SELECT td.parent_id FROM obpm2.tenant_departments td WHERE td.id = cd1.tlkId );

INSERT INTO `personnel_oa`.`per_org_relation` (
    `tlkId`,
    `createTime`,
    `updateTime`,
    `entryDate`,
    `leaveDate`,
    `orgType`,
    `orgId`,
    `perId`,
    `comId`)
SELECT
    e.id,
    e.created_time,
    e.last_updated_time,
    e.hired_date,
    e.leave_time,
    '2',
    (SELECT cd.departId from personnel_oa.com_depart cd WHERE cd.tlkId = e.department_id),
	(SELECT pbi.perId from personnel_oa.per_base_info pbi WHERE pbi.tlkId = e.tenant_user_id),
    (SELECT cbi.comId from personnel_oa.com_base_info cbi WHERE cbi.tlkId = e.organization_id)
FROM obpm2.tenant_employees e;


