{*
 Шаблон вычисления "Работа с дубликатами"
*}

{assign var="dpl_field" value=sql_fetch_assoc(sql_select_field(FIELDS_TABLE, 'type_field as type', {'id = '|cat:{$dupl_field|substr:1}}))}
if (in_array($line['status'], [{$status_filter}])) {
    if ($line['{$dupl_field}']{if $dpl_field.type == 5}['raw']{/if}) {
        $result = data_select_field($table_id, 'id', "{$dupl_field} = '", $line['{$dupl_field}']{if $dpl_field.type == 5}['raw']{/if}, "' AND status IN ({$status_filter}) ORDER BY {$sort_field} {$sort_dir}");
        if (sql_num_rows($result) > 1) {
            $duplicate = 0;
            while ($row = sql_fetch_assoc($result)) {
                if ($row['id'] == $line['id']) {
                    $line['{$mark_field}'] = $duplicate ? '{$dupl_value}' : '{$main_value}';
                } else {
                    data_update($table_id, EVENTS_ENABLE, ['{$mark_field}' => $duplicate ? '{$dupl_value}' : '{$main_value}'], 'id = ', $row['id']);
                }
                $duplicate = 1;
            }
        } else {
            $line['{$mark_field}'] = '{$uniq_value}';
        }
    } else {
        $line['{$mark_field}'] = '{$empty_value}';
    }
    if ($old_value = $event['changed'][{$dupl_field|substr:1}]['old']) {
        $result = data_select_field($table_id, 'id', "{$dupl_field} = '", $old_value, "' AND status IN ({$status_filter}) ORDER BY {$sort_field} {$sort_dir}");
        if (sql_num_rows($result) > 1) {
            $duplicate = 0;
            while ($row = sql_fetch_assoc($result)) {
                data_update($table_id, EVENTS_ENABLE, ['{$mark_field}' => $duplicate ? '{$dupl_value}' : '{$main_value}'], 'id = ', $row['id']);
                $duplicate = 1;
            }
        } else {
            $row = sql_fetch_assoc($result);
            data_update($table_id, EVENTS_ENABLE, ['{$mark_field}' => '{$uniq_value}'], 'id = ', $row['id']);
        }
    }
}