-- 修复项目总人数统计口径：直接员工、关系人流水归属员工、项目流水账号归属员工统一纳入项目员工范围。
UPDATE ccdi_project project
LEFT JOIN (
    SELECT
        scope_staff.project_id,
        COUNT(DISTINCT scope_staff.id_card) AS target_count
    FROM (
        SELECT
            bs.project_id,
            staff.id_card
        FROM ccdi_bank_statement bs
        INNER JOIN ccdi_base_staff staff
            ON staff.id_card = TRIM(bs.cret_no)
        WHERE bs.cret_no IS NOT NULL
          AND TRIM(bs.cret_no) != ''

        UNION

        SELECT
            bs.project_id,
            family_staff.id_card
        FROM ccdi_bank_statement bs
        INNER JOIN ccdi_staff_fmy_relation relation
            ON relation.relation_cert_no = TRIM(bs.cret_no)
           AND relation.status = 1
        INNER JOIN ccdi_base_staff family_staff
            ON family_staff.id_card = relation.person_id
        WHERE bs.cret_no IS NOT NULL
          AND TRIM(bs.cret_no) != ''

        UNION

        SELECT
            bs.project_id,
            account_staff.id_card
        FROM ccdi_bank_statement bs
        INNER JOIN ccdi_account_info account
            ON TRIM(account.account_no) = TRIM(bs.LE_ACCOUNT_NO)
           AND account.owner_type = 'EMPLOYEE'
        INNER JOIN ccdi_base_staff account_staff
            ON account_staff.id_card = account.owner_id
        WHERE bs.LE_ACCOUNT_NO IS NOT NULL
          AND TRIM(bs.LE_ACCOUNT_NO) != ''
    ) scope_staff
    GROUP BY scope_staff.project_id
) stats ON stats.project_id = project.project_id
SET project.target_count = COALESCE(stats.target_count, 0),
    project.update_by = 'system',
    project.update_time = NOW()
WHERE project.del_flag = '0';
